org.el (org-options-keywords): Add "STYLE:"
[org-mode.git] / lisp / org.el
blobee316c4319ea59c359e9b4f5555a3b2ce9b1dd67
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-hook-with-args 'org-font-lock-hook limit))
5866 (defun org-set-font-lock-defaults ()
5867 (let* ((em org-fontify-emphasized-text)
5868 (lk org-activate-links)
5869 (org-font-lock-extra-keywords
5870 (list
5871 ;; Call the hook
5872 '(org-font-lock-hook)
5873 ;; Headlines
5874 `(,(if org-fontify-whole-heading-line
5875 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5876 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5877 (1 (org-get-level-face 1))
5878 (2 (org-get-level-face 2))
5879 (3 (org-get-level-face 3)))
5880 ;; Table lines
5881 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5882 (1 'org-table t))
5883 ;; Table internals
5884 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5885 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5886 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5887 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5888 ;; Drawers
5889 (list org-drawer-regexp '(0 'org-special-keyword t))
5890 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5891 ;; Properties
5892 (list org-property-re
5893 '(1 'org-special-keyword t)
5894 '(3 'org-property-value t))
5895 ;; Links
5896 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5897 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5898 (if (memq 'plain lk) '(org-activate-plain-links))
5899 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5900 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5901 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5902 (if (memq 'footnote lk) '(org-activate-footnote-links))
5903 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5904 '(org-hide-wide-columns (0 nil append))
5905 ;; TODO keyword
5906 (list (format org-heading-keyword-regexp-format
5907 org-todo-regexp)
5908 '(2 (org-get-todo-face 2) t))
5909 ;; DONE
5910 (if org-fontify-done-headline
5911 (list (format org-heading-keyword-regexp-format
5912 (concat
5913 "\\(?:"
5914 (mapconcat 'regexp-quote org-done-keywords "\\|")
5915 "\\)"))
5916 '(2 'org-headline-done t))
5917 nil)
5918 ;; Priorities
5919 '(org-font-lock-add-priority-faces)
5920 ;; Tags
5921 '(org-font-lock-add-tag-faces)
5922 ;; Special keywords
5923 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5924 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5925 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5926 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5927 ;; Emphasis
5928 (if em
5929 (if (featurep 'xemacs)
5930 '(org-do-emphasis-faces (0 nil append))
5931 '(org-do-emphasis-faces)))
5932 ;; Checkboxes
5933 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5934 1 'org-checkbox prepend)
5935 (if (cdr (assq 'checkbox org-list-automatic-rules))
5936 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5937 (0 (org-get-checkbox-statistics-face) t)))
5938 ;; Description list items
5939 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5940 1 'org-list-dt prepend)
5941 ;; ARCHIVEd headings
5942 (list (concat
5943 org-outline-regexp-bol
5944 "\\(.*:" org-archive-tag ":.*\\)")
5945 '(1 'org-archived prepend))
5946 ;; Specials
5947 '(org-do-latex-and-special-faces)
5948 '(org-fontify-entities)
5949 '(org-raise-scripts)
5950 ;; Code
5951 '(org-activate-code (1 'org-code t))
5952 ;; COMMENT
5953 (list (format org-heading-keyword-regexp-format
5954 (concat "\\("
5955 org-comment-string "\\|" org-quote-string
5956 "\\)"))
5957 '(2 'org-special-keyword t))
5958 ;; Blocks and meta lines
5959 '(org-fontify-meta-lines-and-blocks)
5961 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5962 (run-hooks 'org-font-lock-set-keywords-hook)
5963 ;; Now set the full font-lock-keywords
5964 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5965 (org-set-local 'font-lock-defaults
5966 '(org-font-lock-keywords t nil nil backward-paragraph))
5967 (kill-local-variable 'font-lock-keywords) nil))
5969 (defun org-toggle-pretty-entities ()
5970 "Toggle the composition display of entities as UTF8 characters."
5971 (interactive)
5972 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5973 (org-restart-font-lock)
5974 (if org-pretty-entities
5975 (message "Entities are displayed as UTF8 characters")
5976 (save-restriction
5977 (widen)
5978 (org-decompose-region (point-min) (point-max))
5979 (message "Entities are displayed plain"))))
5981 (defvar org-custom-properties-overlays nil
5982 "List of overlays used for custom properties.")
5983 (make-variable-buffer-local 'org-custom-properties-overlays)
5985 (defun org-toggle-custom-properties-visibility ()
5986 "Display or hide properties in `org-custom-properties'."
5987 (interactive)
5988 (if org-custom-properties-overlays
5989 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5990 (setq org-custom-properties-overlays nil))
5991 (unless (not org-custom-properties)
5992 (save-excursion
5993 (save-restriction
5994 (widen)
5995 (goto-char (point-min))
5996 (while (re-search-forward org-property-re nil t)
5997 (mapc (lambda(p)
5998 (when (equal p (substring (match-string 1) 1 -1))
5999 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6000 (overlay-put o 'invisible t)
6001 (overlay-put o 'org-custom-property t)
6002 (push o org-custom-properties-overlays))))
6003 org-custom-properties)))))))
6005 (defun org-fontify-entities (limit)
6006 "Find an entity to fontify."
6007 (let (ee)
6008 (when org-pretty-entities
6009 (catch 'match
6010 (while (re-search-forward
6011 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6012 limit t)
6013 (if (and (not (org-in-indented-comment-line))
6014 (setq ee (org-entity-get (match-string 1)))
6015 (= (length (nth 6 ee)) 1))
6016 (let*
6017 ((end (if (equal (match-string 2) "{}")
6018 (match-end 2)
6019 (match-end 1))))
6020 (add-text-properties
6021 (match-beginning 0) end
6022 (list 'font-lock-fontified t))
6023 (compose-region (match-beginning 0) end
6024 (nth 6 ee) nil)
6025 (backward-char 1)
6026 (throw 'match t))))
6027 nil))))
6029 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6030 "Fontify string S like in Org-mode."
6031 (with-temp-buffer
6032 (insert s)
6033 (let ((org-odd-levels-only odd-levels))
6034 (org-mode)
6035 (font-lock-fontify-buffer)
6036 (buffer-string))))
6038 (defvar org-m nil)
6039 (defvar org-l nil)
6040 (defvar org-f nil)
6041 (defun org-get-level-face (n)
6042 "Get the right face for match N in font-lock matching of headlines."
6043 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6044 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6045 (if org-cycle-level-faces
6046 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6047 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6048 (cond
6049 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6050 ((eq n 2) org-f)
6051 (t (if org-level-color-stars-only nil org-f))))
6054 (defun org-get-todo-face (kwd)
6055 "Get the right face for a TODO keyword KWD.
6056 If KWD is a number, get the corresponding match group."
6057 (if (numberp kwd) (setq kwd (match-string kwd)))
6058 (or (org-face-from-face-or-color
6059 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6060 (and (member kwd org-done-keywords) 'org-done)
6061 'org-todo))
6063 (defun org-face-from-face-or-color (context inherit face-or-color)
6064 "Create a face list that inherits INHERIT, but sets the foreground color.
6065 When FACE-OR-COLOR is not a string, just return it."
6066 (if (stringp face-or-color)
6067 (list :inherit inherit
6068 (cdr (assoc context org-faces-easy-properties))
6069 face-or-color)
6070 face-or-color))
6072 (defun org-font-lock-add-tag-faces (limit)
6073 "Add the special tag faces."
6074 (when (and org-tag-faces org-tags-special-faces-re)
6075 (while (re-search-forward org-tags-special-faces-re limit t)
6076 (add-text-properties (match-beginning 1) (match-end 1)
6077 (list 'face (org-get-tag-face 1)
6078 'font-lock-fontified t))
6079 (backward-char 1))))
6081 (defun org-font-lock-add-priority-faces (limit)
6082 "Add the special priority faces."
6083 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6084 (when (save-match-data (org-at-heading-p))
6085 (add-text-properties
6086 (match-beginning 0) (match-end 0)
6087 (list 'face (or (org-face-from-face-or-color
6088 'priority 'org-special-keyword
6089 (cdr (assoc (char-after (match-beginning 1))
6090 org-priority-faces)))
6091 'org-special-keyword)
6092 'font-lock-fontified t)))))
6094 (defun org-get-tag-face (kwd)
6095 "Get the right face for a TODO keyword KWD.
6096 If KWD is a number, get the corresponding match group."
6097 (if (numberp kwd) (setq kwd (match-string kwd)))
6098 (or (org-face-from-face-or-color
6099 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6100 'org-tag))
6102 (defun org-unfontify-region (beg end &optional maybe_loudly)
6103 "Remove fontification and activation overlays from links."
6104 (font-lock-default-unfontify-region beg end)
6105 (let* ((buffer-undo-list t)
6106 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6107 (inhibit-modification-hooks t)
6108 deactivate-mark buffer-file-name buffer-file-truename)
6109 (org-decompose-region beg end)
6110 (remove-text-properties beg end
6111 '(mouse-face t keymap t org-linked-text t
6112 invisible t intangible t
6113 org-no-flyspell t org-emphasis t))
6114 (org-remove-font-lock-display-properties beg end)))
6116 (defconst org-script-display '(((raise -0.3) (height 0.7))
6117 ((raise 0.3) (height 0.7))
6118 ((raise -0.5))
6119 ((raise 0.5)))
6120 "Display properties for showing superscripts and subscripts.")
6122 (defun org-remove-font-lock-display-properties (beg end)
6123 "Remove specific display properties that have been added by font lock.
6124 The will remove the raise properties that are used to show superscripts
6125 and subscripts."
6126 (let (next prop)
6127 (while (< beg end)
6128 (setq next (next-single-property-change beg 'display nil end)
6129 prop (get-text-property beg 'display))
6130 (if (member prop org-script-display)
6131 (put-text-property beg next 'display nil))
6132 (setq beg next))))
6134 (defun org-raise-scripts (limit)
6135 "Add raise properties to sub/superscripts."
6136 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6137 (if (re-search-forward
6138 (if (eq org-use-sub-superscripts t)
6139 org-match-substring-regexp
6140 org-match-substring-with-braces-regexp)
6141 limit t)
6142 (let* ((pos (point)) table-p comment-p
6143 (mpos (match-beginning 3))
6144 (emph-p (get-text-property mpos 'org-emphasis))
6145 (link-p (get-text-property mpos 'mouse-face))
6146 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6147 (goto-char (point-at-bol))
6148 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6149 comment-p (org-looking-at-p "[ \t]*#"))
6150 (goto-char pos)
6151 ;; FIXME: Should we go back one character here, for a_b^c
6152 ;; (goto-char (1- pos)) ;????????????????????
6153 (if (or comment-p emph-p link-p keyw-p)
6155 (put-text-property (match-beginning 3) (match-end 0)
6156 'display
6157 (if (equal (char-after (match-beginning 2)) ?^)
6158 (nth (if table-p 3 1) org-script-display)
6159 (nth (if table-p 2 0) org-script-display)))
6160 (add-text-properties (match-beginning 2) (match-end 2)
6161 (list 'invisible t
6162 'org-dwidth t 'org-dwidth-n 1))
6163 (if (and (eq (char-after (match-beginning 3)) ?{)
6164 (eq (char-before (match-end 3)) ?}))
6165 (progn
6166 (add-text-properties
6167 (match-beginning 3) (1+ (match-beginning 3))
6168 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6169 (add-text-properties
6170 (1- (match-end 3)) (match-end 3)
6171 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6172 t)))))
6174 ;;;; Visibility cycling, including org-goto and indirect buffer
6176 ;;; Cycling
6178 (defvar org-cycle-global-status nil)
6179 (make-variable-buffer-local 'org-cycle-global-status)
6180 (defvar org-cycle-subtree-status nil)
6181 (make-variable-buffer-local 'org-cycle-subtree-status)
6183 ;;;###autoload
6185 (defvar org-inlinetask-min-level)
6187 (defun org-cycle (&optional arg)
6188 "TAB-action and visibility cycling for Org-mode.
6190 This is the command invoked in Org-mode by the TAB key. Its main purpose
6191 is outline visibility cycling, but it also invokes other actions
6192 in special contexts.
6194 - When this function is called with a prefix argument, rotate the entire
6195 buffer through 3 states (global cycling)
6196 1. OVERVIEW: Show only top-level headlines.
6197 2. CONTENTS: Show all headlines of all levels, but no body text.
6198 3. SHOW ALL: Show everything.
6199 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6200 determined by the variable `org-startup-folded', and by any VISIBILITY
6201 properties in the buffer.
6202 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6203 including any drawers.
6205 - When inside a table, re-align the table and move to the next field.
6207 - When point is at the beginning of a headline, rotate the subtree started
6208 by this line through 3 different states (local cycling)
6209 1. FOLDED: Only the main headline is shown.
6210 2. CHILDREN: The main headline and the direct children are shown.
6211 From this state, you can move to one of the children
6212 and zoom in further.
6213 3. SUBTREE: Show the entire subtree, including body text.
6214 If there is no subtree, switch directly from CHILDREN to FOLDED.
6216 - When point is at the beginning of an empty headline and the variable
6217 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6218 of the headline by demoting and promoting it to likely levels. This
6219 speeds up creation document structure by pressing TAB once or several
6220 times right after creating a new headline.
6222 - When there is a numeric prefix, go up to a heading with level ARG, do
6223 a `show-subtree' and return to the previous cursor position. If ARG
6224 is negative, go up that many levels.
6226 - When point is not at the beginning of a headline, execute the global
6227 binding for TAB, which is re-indenting the line. See the option
6228 `org-cycle-emulate-tab' for details.
6230 - Special case: if point is at the beginning of the buffer and there is
6231 no headline in line 1, this function will act as if called with prefix arg
6232 (C-u TAB, same as S-TAB) also when called without prefix arg.
6233 But only if also the variable `org-cycle-global-at-bob' is t."
6234 (interactive "P")
6235 (org-load-modules-maybe)
6236 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6237 (and org-cycle-level-after-item/entry-creation
6238 (or (org-cycle-level)
6239 (org-cycle-item-indentation))))
6240 (let* ((limit-level
6241 (or org-cycle-max-level
6242 (and (boundp 'org-inlinetask-min-level)
6243 org-inlinetask-min-level
6244 (1- org-inlinetask-min-level))))
6245 (nstars (and limit-level
6246 (if org-odd-levels-only
6247 (and limit-level (1- (* limit-level 2)))
6248 limit-level)))
6249 (org-outline-regexp
6250 (if (not (derived-mode-p 'org-mode))
6251 outline-regexp
6252 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6253 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6254 (not (looking-at org-outline-regexp))))
6255 (org-cycle-hook
6256 (if bob-special
6257 (delq 'org-optimize-window-after-visibility-change
6258 (copy-sequence org-cycle-hook))
6259 org-cycle-hook))
6260 (pos (point)))
6262 (if (or bob-special (equal arg '(4)))
6263 ;; special case: use global cycling
6264 (setq arg t))
6266 (cond
6268 ((equal arg '(16))
6269 (setq last-command 'dummy)
6270 (org-set-startup-visibility)
6271 (message "Startup visibility, plus VISIBILITY properties"))
6273 ((equal arg '(64))
6274 (show-all)
6275 (message "Entire buffer visible, including drawers"))
6277 ;; Table: enter it or move to the next field.
6278 ((org-at-table-p 'any)
6279 (if (org-at-table.el-p)
6280 (message "Use C-c ' to edit table.el tables")
6281 (if arg (org-table-edit-field t)
6282 (org-table-justify-field-maybe)
6283 (call-interactively 'org-table-next-field))))
6285 ((run-hook-with-args-until-success
6286 'org-tab-after-check-for-table-hook))
6288 ;; Global cycling: delegate to `org-cycle-internal-global'.
6289 ((eq arg t) (org-cycle-internal-global))
6291 ;; Drawers: delegate to `org-flag-drawer'.
6292 ((and org-drawers org-drawer-regexp
6293 (save-excursion
6294 (beginning-of-line 1)
6295 (looking-at org-drawer-regexp)))
6296 (org-flag-drawer ; toggle block visibility
6297 (not (get-char-property (match-end 0) 'invisible))))
6299 ;; Show-subtree, ARG levels up from here.
6300 ((integerp arg)
6301 (save-excursion
6302 (org-back-to-heading)
6303 (outline-up-heading (if (< arg 0) (- arg)
6304 (- (funcall outline-level) arg)))
6305 (org-show-subtree)))
6307 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6308 ((and (featurep 'org-inlinetask)
6309 (org-inlinetask-at-task-p)
6310 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6311 (org-inlinetask-toggle-visibility))
6313 ((org-try-cdlatex-tab))
6315 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6316 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6317 (save-excursion (beginning-of-line 1)
6318 (looking-at org-outline-regexp)))
6319 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6320 (org-cycle-internal-local))
6322 ;; From there: TAB emulation and template completion.
6323 (buffer-read-only (org-back-to-heading))
6325 ((run-hook-with-args-until-success
6326 'org-tab-after-check-for-cycling-hook))
6328 ((org-try-structure-completion))
6330 ((run-hook-with-args-until-success
6331 'org-tab-before-tab-emulation-hook))
6333 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6334 (or (not (bolp))
6335 (not (looking-at org-outline-regexp))))
6336 (call-interactively (global-key-binding "\t")))
6338 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6339 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6340 (or (and (eq org-cycle-emulate-tab 'white)
6341 (= (match-end 0) (point-at-eol)))
6342 (and (eq org-cycle-emulate-tab 'whitestart)
6343 (>= (match-end 0) pos))))
6345 (eq org-cycle-emulate-tab t))
6346 (call-interactively (global-key-binding "\t")))
6348 (t (save-excursion
6349 (org-back-to-heading)
6350 (org-cycle)))))))
6352 (defun org-cycle-internal-global ()
6353 "Do the global cycling action."
6354 ;; Hack to avoid display of messages for .org attachments in Gnus
6355 (let ((ga (string-match "\\*fontification" (buffer-name))))
6356 (cond
6357 ((and (eq last-command this-command)
6358 (eq org-cycle-global-status 'overview))
6359 ;; We just created the overview - now do table of contents
6360 ;; This can be slow in very large buffers, so indicate action
6361 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6362 (unless ga (message "CONTENTS..."))
6363 (org-content)
6364 (unless ga (message "CONTENTS...done"))
6365 (setq org-cycle-global-status 'contents)
6366 (run-hook-with-args 'org-cycle-hook 'contents))
6368 ((and (eq last-command this-command)
6369 (eq org-cycle-global-status 'contents))
6370 ;; We just showed the table of contents - now show everything
6371 (run-hook-with-args 'org-pre-cycle-hook 'all)
6372 (show-all)
6373 (unless ga (message "SHOW ALL"))
6374 (setq org-cycle-global-status 'all)
6375 (run-hook-with-args 'org-cycle-hook 'all))
6378 ;; Default action: go to overview
6379 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6380 (org-overview)
6381 (unless ga (message "OVERVIEW"))
6382 (setq org-cycle-global-status 'overview)
6383 (run-hook-with-args 'org-cycle-hook 'overview)))))
6385 (defun org-cycle-internal-local ()
6386 "Do the local cycling action."
6387 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6388 ;; First, determine end of headline (EOH), end of subtree or item
6389 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6390 (save-excursion
6391 (if (org-at-item-p)
6392 (progn
6393 (beginning-of-line)
6394 (setq struct (org-list-struct))
6395 (setq eoh (point-at-eol))
6396 (setq eos (org-list-get-item-end-before-blank (point) struct))
6397 (setq has-children (org-list-has-child-p (point) struct)))
6398 (org-back-to-heading)
6399 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6400 (setq eos (save-excursion
6401 (org-end-of-subtree t)
6402 (unless (eobp)
6403 (skip-chars-forward " \t\n"))
6404 (if (eobp) (point) (1- (point)))))
6405 (setq has-children
6406 (or (save-excursion
6407 (let ((level (funcall outline-level)))
6408 (outline-next-heading)
6409 (and (org-at-heading-p t)
6410 (> (funcall outline-level) level))))
6411 (save-excursion
6412 (org-list-search-forward (org-item-beginning-re) eos t)))))
6413 ;; Determine end invisible part of buffer (EOL)
6414 (beginning-of-line 2)
6415 ;; XEmacs doesn't have `next-single-char-property-change'
6416 (if (featurep 'xemacs)
6417 (while (and (not (eobp)) ;; this is like `next-line'
6418 (get-char-property (1- (point)) 'invisible))
6419 (beginning-of-line 2))
6420 (while (and (not (eobp)) ;; this is like `next-line'
6421 (get-char-property (1- (point)) 'invisible))
6422 (goto-char (next-single-char-property-change (point) 'invisible))
6423 (and (eolp) (beginning-of-line 2))))
6424 (setq eol (point)))
6425 ;; Find out what to do next and set `this-command'
6426 (cond
6427 ((= eos eoh)
6428 ;; Nothing is hidden behind this heading
6429 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6430 (message "EMPTY ENTRY")
6431 (setq org-cycle-subtree-status nil)
6432 (save-excursion
6433 (goto-char eos)
6434 (outline-next-heading)
6435 (if (outline-invisible-p) (org-flag-heading nil))))
6436 ((and (or (>= eol eos)
6437 (not (string-match "\\S-" (buffer-substring eol eos))))
6438 (or has-children
6439 (not (setq children-skipped
6440 org-cycle-skip-children-state-if-no-children))))
6441 ;; Entire subtree is hidden in one line: children view
6442 (run-hook-with-args 'org-pre-cycle-hook 'children)
6443 (if (org-at-item-p)
6444 (org-list-set-item-visibility (point-at-bol) struct 'children)
6445 (org-show-entry)
6446 (org-with-limited-levels (show-children))
6447 ;; FIXME: This slows down the func way too much.
6448 ;; How keep drawers hidden in subtree anyway?
6449 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6450 ;; (org-cycle-hide-drawers 'subtree))
6452 ;; Fold every list in subtree to top-level items.
6453 (when (eq org-cycle-include-plain-lists 'integrate)
6454 (save-excursion
6455 (org-back-to-heading)
6456 (while (org-list-search-forward (org-item-beginning-re) eos t)
6457 (beginning-of-line 1)
6458 (let* ((struct (org-list-struct))
6459 (prevs (org-list-prevs-alist struct))
6460 (end (org-list-get-bottom-point struct)))
6461 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6462 (org-list-get-all-items (point) struct prevs))
6463 (goto-char end))))))
6464 (message "CHILDREN")
6465 (save-excursion
6466 (goto-char eos)
6467 (outline-next-heading)
6468 (if (outline-invisible-p) (org-flag-heading nil)))
6469 (setq org-cycle-subtree-status 'children)
6470 (run-hook-with-args 'org-cycle-hook 'children))
6471 ((or children-skipped
6472 (and (eq last-command this-command)
6473 (eq org-cycle-subtree-status 'children)))
6474 ;; We just showed the children, or no children are there,
6475 ;; now show everything.
6476 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6477 (outline-flag-region eoh eos nil)
6478 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6479 (setq org-cycle-subtree-status 'subtree)
6480 (run-hook-with-args 'org-cycle-hook 'subtree))
6482 ;; Default action: hide the subtree.
6483 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6484 (outline-flag-region eoh eos t)
6485 (message "FOLDED")
6486 (setq org-cycle-subtree-status 'folded)
6487 (run-hook-with-args 'org-cycle-hook 'folded)))))
6489 ;;;###autoload
6490 (defun org-global-cycle (&optional arg)
6491 "Cycle the global visibility. For details see `org-cycle'.
6492 With \\[universal-argument] prefix arg, switch to startup visibility.
6493 With a numeric prefix, show all headlines up to that level."
6494 (interactive "P")
6495 (let ((org-cycle-include-plain-lists
6496 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6497 (cond
6498 ((integerp arg)
6499 (show-all)
6500 (hide-sublevels arg)
6501 (setq org-cycle-global-status 'contents))
6502 ((equal arg '(4))
6503 (org-set-startup-visibility)
6504 (message "Startup visibility, plus VISIBILITY properties."))
6506 (org-cycle '(4))))))
6508 (defun org-set-startup-visibility ()
6509 "Set the visibility required by startup options and properties."
6510 (cond
6511 ((eq org-startup-folded t)
6512 (org-cycle '(4)))
6513 ((eq org-startup-folded 'content)
6514 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6515 (org-cycle '(4)) (org-cycle '(4)))))
6516 (unless (eq org-startup-folded 'showeverything)
6517 (if org-hide-block-startup (org-hide-block-all))
6518 (org-set-visibility-according-to-property 'no-cleanup)
6519 (org-cycle-hide-archived-subtrees 'all)
6520 (org-cycle-hide-drawers 'all)
6521 (org-cycle-show-empty-lines t)))
6523 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6524 "Switch subtree visibilities according to :VISIBILITY: property."
6525 (interactive)
6526 (let (org-show-entry-below state)
6527 (save-excursion
6528 (goto-char (point-min))
6529 (while (re-search-forward
6530 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6531 nil t)
6532 (setq state (match-string 1))
6533 (save-excursion
6534 (org-back-to-heading t)
6535 (hide-subtree)
6536 (org-reveal)
6537 (cond
6538 ((equal state '("fold" "folded"))
6539 (hide-subtree))
6540 ((equal state "children")
6541 (org-show-hidden-entry)
6542 (show-children))
6543 ((equal state "content")
6544 (save-excursion
6545 (save-restriction
6546 (org-narrow-to-subtree)
6547 (org-content))))
6548 ((member state '("all" "showall"))
6549 (show-subtree)))))
6550 (unless no-cleanup
6551 (org-cycle-hide-archived-subtrees 'all)
6552 (org-cycle-hide-drawers 'all)
6553 (org-cycle-show-empty-lines 'all)))))
6555 ;; This function uses outline-regexp instead of the more fundamental
6556 ;; org-outline-regexp so that org-cycle-global works outside of Org
6557 ;; buffers, where outline-regexp is needed.
6558 (defun org-overview ()
6559 "Switch to overview mode, showing only top-level headlines.
6560 Really, this shows all headlines with level equal or greater than the level
6561 of the first headline in the buffer. This is important, because if the
6562 first headline is not level one, then (hide-sublevels 1) gives confusing
6563 results."
6564 (interactive)
6565 (let ((level (save-excursion
6566 (goto-char (point-min))
6567 (if (re-search-forward (concat "^" outline-regexp) nil t)
6568 (progn
6569 (goto-char (match-beginning 0))
6570 (funcall outline-level))))))
6571 (and level (hide-sublevels level))))
6573 (defun org-content (&optional arg)
6574 "Show all headlines in the buffer, like a table of contents.
6575 With numerical argument N, show content up to level N."
6576 (interactive "P")
6577 (save-excursion
6578 ;; Visit all headings and show their offspring
6579 (and (integerp arg) (org-overview))
6580 (goto-char (point-max))
6581 (catch 'exit
6582 (while (and (progn (condition-case nil
6583 (outline-previous-visible-heading 1)
6584 (error (goto-char (point-min))))
6586 (looking-at org-outline-regexp))
6587 (if (integerp arg)
6588 (show-children (1- arg))
6589 (show-branches))
6590 (if (bobp) (throw 'exit nil))))))
6593 (defun org-optimize-window-after-visibility-change (state)
6594 "Adjust the window after a change in outline visibility.
6595 This function is the default value of the hook `org-cycle-hook'."
6596 (when (get-buffer-window (current-buffer))
6597 (cond
6598 ((eq state 'content) nil)
6599 ((eq state 'all) nil)
6600 ((eq state 'folded) nil)
6601 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6602 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6604 (defun org-remove-empty-overlays-at (pos)
6605 "Remove outline overlays that do not contain non-white stuff."
6606 (mapc
6607 (lambda (o)
6608 (and (eq 'outline (overlay-get o 'invisible))
6609 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6610 (overlay-end o))))
6611 (delete-overlay o)))
6612 (overlays-at pos)))
6614 (defun org-clean-visibility-after-subtree-move ()
6615 "Fix visibility issues after moving a subtree."
6616 ;; First, find a reasonable region to look at:
6617 ;; Start two siblings above, end three below
6618 (let* ((beg (save-excursion
6619 (and (org-get-last-sibling)
6620 (org-get-last-sibling))
6621 (point)))
6622 (end (save-excursion
6623 (and (org-get-next-sibling)
6624 (org-get-next-sibling)
6625 (org-get-next-sibling))
6626 (if (org-at-heading-p)
6627 (point-at-eol)
6628 (point))))
6629 (level (looking-at "\\*+"))
6630 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6631 (save-excursion
6632 (save-restriction
6633 (narrow-to-region beg end)
6634 (when re
6635 ;; Properly fold already folded siblings
6636 (goto-char (point-min))
6637 (while (re-search-forward re nil t)
6638 (if (and (not (outline-invisible-p))
6639 (save-excursion
6640 (goto-char (point-at-eol)) (outline-invisible-p)))
6641 (hide-entry))))
6642 (org-cycle-show-empty-lines 'overview)
6643 (org-cycle-hide-drawers 'overview)))))
6645 (defun org-cycle-show-empty-lines (state)
6646 "Show empty lines above all visible headlines.
6647 The region to be covered depends on STATE when called through
6648 `org-cycle-hook'. Lisp program can use t for STATE to get the
6649 entire buffer covered. Note that an empty line is only shown if there
6650 are at least `org-cycle-separator-lines' empty lines before the headline."
6651 (when (not (= org-cycle-separator-lines 0))
6652 (save-excursion
6653 (let* ((n (abs org-cycle-separator-lines))
6654 (re (cond
6655 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6656 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6657 (t (let ((ns (number-to-string (- n 2))))
6658 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6659 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6660 beg end b e)
6661 (cond
6662 ((memq state '(overview contents t))
6663 (setq beg (point-min) end (point-max)))
6664 ((memq state '(children folded))
6665 (setq beg (point) end (progn (org-end-of-subtree t t)
6666 (beginning-of-line 2)
6667 (point)))))
6668 (when beg
6669 (goto-char beg)
6670 (while (re-search-forward re end t)
6671 (unless (get-char-property (match-end 1) 'invisible)
6672 (setq e (match-end 1))
6673 (if (< org-cycle-separator-lines 0)
6674 (setq b (save-excursion
6675 (goto-char (match-beginning 0))
6676 (org-back-over-empty-lines)
6677 (if (save-excursion
6678 (goto-char (max (point-min) (1- (point))))
6679 (org-at-heading-p))
6680 (1- (point))
6681 (point))))
6682 (setq b (match-beginning 1)))
6683 (outline-flag-region b e nil)))))))
6684 ;; Never hide empty lines at the end of the file.
6685 (save-excursion
6686 (goto-char (point-max))
6687 (outline-previous-heading)
6688 (outline-end-of-heading)
6689 (if (and (looking-at "[ \t\n]+")
6690 (= (match-end 0) (point-max)))
6691 (outline-flag-region (point) (match-end 0) nil))))
6693 (defun org-show-empty-lines-in-parent ()
6694 "Move to the parent and re-show empty lines before visible headlines."
6695 (save-excursion
6696 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6697 (org-cycle-show-empty-lines context))))
6699 (defun org-files-list ()
6700 "Return `org-agenda-files' list, plus all open org-mode files.
6701 This is useful for operations that need to scan all of a user's
6702 open and agenda-wise Org files."
6703 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6704 (dolist (buf (buffer-list))
6705 (with-current-buffer buf
6706 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6707 (let ((file (expand-file-name (buffer-file-name))))
6708 (unless (member file files)
6709 (push file files))))))
6710 files))
6712 (defsubst org-entry-beginning-position ()
6713 "Return the beginning position of the current entry."
6714 (save-excursion (outline-back-to-heading t) (point)))
6716 (defsubst org-entry-end-position ()
6717 "Return the end position of the current entry."
6718 (save-excursion (outline-next-heading) (point)))
6720 (defun org-cycle-hide-drawers (state)
6721 "Re-hide all drawers after a visibility state change."
6722 (when (and (derived-mode-p 'org-mode)
6723 (not (memq state '(overview folded contents))))
6724 (save-excursion
6725 (let* ((globalp (memq state '(contents all)))
6726 (beg (if globalp (point-min) (point)))
6727 (end (if globalp (point-max)
6728 (if (eq state 'children)
6729 (save-excursion (outline-next-heading) (point))
6730 (org-end-of-subtree t)))))
6731 (goto-char beg)
6732 (while (re-search-forward org-drawer-regexp end t)
6733 (org-flag-drawer t))))))
6735 (defun org-flag-drawer (flag)
6736 "When FLAG is non-nil, hide the drawer we are within.
6737 Otherwise make it visible."
6738 (save-excursion
6739 (beginning-of-line 1)
6740 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6741 (let ((b (match-end 0)))
6742 (if (re-search-forward
6743 "^[ \t]*:END:"
6744 (save-excursion (outline-next-heading) (point)) t)
6745 (outline-flag-region b (point-at-eol) flag)
6746 (error ":END: line missing at position %s" b))))))
6748 (defun org-subtree-end-visible-p ()
6749 "Is the end of the current subtree visible?"
6750 (pos-visible-in-window-p
6751 (save-excursion (org-end-of-subtree t) (point))))
6753 (defun org-first-headline-recenter (&optional N)
6754 "Move cursor to the first headline and recenter the headline.
6755 Optional argument N means put the headline into the Nth line of the window."
6756 (goto-char (point-min))
6757 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6758 (beginning-of-line)
6759 (recenter (prefix-numeric-value N))))
6761 ;;; Saving and restoring visibility
6763 (defun org-outline-overlay-data (&optional use-markers)
6764 "Return a list of the locations of all outline overlays.
6765 These are overlays with the `invisible' property value `outline'.
6766 The return value is a list of cons cells, with start and stop
6767 positions for each overlay.
6768 If USE-MARKERS is set, return the positions as markers."
6769 (let (beg end)
6770 (save-excursion
6771 (save-restriction
6772 (widen)
6773 (delq nil
6774 (mapcar (lambda (o)
6775 (when (eq (overlay-get o 'invisible) 'outline)
6776 (setq beg (overlay-start o)
6777 end (overlay-end o))
6778 (and beg end (> end beg)
6779 (if use-markers
6780 (cons (move-marker (make-marker) beg)
6781 (move-marker (make-marker) end))
6782 (cons beg end)))))
6783 (overlays-in (point-min) (point-max))))))))
6785 (defun org-set-outline-overlay-data (data)
6786 "Create visibility overlays for all positions in DATA.
6787 DATA should have been made by `org-outline-overlay-data'."
6788 (let (o)
6789 (save-excursion
6790 (save-restriction
6791 (widen)
6792 (show-all)
6793 (mapc (lambda (c)
6794 (outline-flag-region (car c) (cdr c) t))
6795 data)))))
6797 ;;; Folding of blocks
6799 (defvar org-hide-block-overlays nil
6800 "Overlays hiding blocks.")
6801 (make-variable-buffer-local 'org-hide-block-overlays)
6803 (defun org-block-map (function &optional start end)
6804 "Call FUNCTION at the head of all source blocks in the current buffer.
6805 Optional arguments START and END can be used to limit the range."
6806 (let ((start (or start (point-min)))
6807 (end (or end (point-max))))
6808 (save-excursion
6809 (goto-char start)
6810 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6811 (save-excursion
6812 (save-match-data
6813 (goto-char (match-beginning 0))
6814 (funcall function)))))))
6816 (defun org-hide-block-toggle-all ()
6817 "Toggle the visibility of all blocks in the current buffer."
6818 (org-block-map #'org-hide-block-toggle))
6820 (defun org-hide-block-all ()
6821 "Fold all blocks in the current buffer."
6822 (interactive)
6823 (org-show-block-all)
6824 (org-block-map #'org-hide-block-toggle-maybe))
6826 (defun org-show-block-all ()
6827 "Unfold all blocks in the current buffer."
6828 (interactive)
6829 (mapc 'delete-overlay org-hide-block-overlays)
6830 (setq org-hide-block-overlays nil))
6832 (defun org-hide-block-toggle-maybe ()
6833 "Toggle visibility of block at point."
6834 (interactive)
6835 (let ((case-fold-search t))
6836 (if (save-excursion
6837 (beginning-of-line 1)
6838 (looking-at org-block-regexp))
6839 (progn (org-hide-block-toggle)
6840 t) ;; to signal that we took action
6841 nil))) ;; to signal that we did not
6843 (defun org-hide-block-toggle (&optional force)
6844 "Toggle the visibility of the current block."
6845 (interactive)
6846 (save-excursion
6847 (beginning-of-line)
6848 (if (re-search-forward org-block-regexp nil t)
6849 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6850 (end (match-end 0)) ;; end of entire body
6852 (if (memq t (mapcar (lambda (overlay)
6853 (eq (overlay-get overlay 'invisible)
6854 'org-hide-block))
6855 (overlays-at start)))
6856 (if (or (not force) (eq force 'off))
6857 (mapc (lambda (ov)
6858 (when (member ov org-hide-block-overlays)
6859 (setq org-hide-block-overlays
6860 (delq ov org-hide-block-overlays)))
6861 (when (eq (overlay-get ov 'invisible)
6862 'org-hide-block)
6863 (delete-overlay ov)))
6864 (overlays-at start)))
6865 (setq ov (make-overlay start end))
6866 (overlay-put ov 'invisible 'org-hide-block)
6867 ;; make the block accessible to isearch
6868 (overlay-put
6869 ov 'isearch-open-invisible
6870 (lambda (ov)
6871 (when (member ov org-hide-block-overlays)
6872 (setq org-hide-block-overlays
6873 (delq ov org-hide-block-overlays)))
6874 (when (eq (overlay-get ov 'invisible)
6875 'org-hide-block)
6876 (delete-overlay ov))))
6877 (push ov org-hide-block-overlays)))
6878 (error "Not looking at a source block"))))
6880 ;; org-tab-after-check-for-cycling-hook
6881 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6882 ;; Remove overlays when changing major mode
6883 (add-hook 'org-mode-hook
6884 (lambda () (org-add-hook 'change-major-mode-hook
6885 'org-show-block-all 'append 'local)))
6887 ;;; Org-goto
6889 (defvar org-goto-window-configuration nil)
6890 (defvar org-goto-marker nil)
6891 (defvar org-goto-map
6892 (let ((map (make-sparse-keymap)))
6893 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6894 (while (setq cmd (pop cmds))
6895 (substitute-key-definition cmd cmd map global-map)))
6896 (suppress-keymap map)
6897 (org-defkey map "\C-m" 'org-goto-ret)
6898 (org-defkey map [(return)] 'org-goto-ret)
6899 (org-defkey map [(left)] 'org-goto-left)
6900 (org-defkey map [(right)] 'org-goto-right)
6901 (org-defkey map [(control ?g)] 'org-goto-quit)
6902 (org-defkey map "\C-i" 'org-cycle)
6903 (org-defkey map [(tab)] 'org-cycle)
6904 (org-defkey map [(down)] 'outline-next-visible-heading)
6905 (org-defkey map [(up)] 'outline-previous-visible-heading)
6906 (if org-goto-auto-isearch
6907 (if (fboundp 'define-key-after)
6908 (define-key-after map [t] 'org-goto-local-auto-isearch)
6909 nil)
6910 (org-defkey map "q" 'org-goto-quit)
6911 (org-defkey map "n" 'outline-next-visible-heading)
6912 (org-defkey map "p" 'outline-previous-visible-heading)
6913 (org-defkey map "f" 'outline-forward-same-level)
6914 (org-defkey map "b" 'outline-backward-same-level)
6915 (org-defkey map "u" 'outline-up-heading))
6916 (org-defkey map "/" 'org-occur)
6917 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6918 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6919 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6920 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6921 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6922 map))
6924 (defconst org-goto-help
6925 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6926 RET=jump to location [Q]uit and return to previous location
6927 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6929 (defvar org-goto-start-pos) ; dynamically scoped parameter
6931 ;; FIXME: Docstring does not mention both interfaces
6932 (defun org-goto (&optional alternative-interface)
6933 "Look up a different location in the current file, keeping current visibility.
6935 When you want look-up or go to a different location in a
6936 document, the fastest way is often to fold the entire buffer and
6937 then dive into the tree. This method has the disadvantage, that
6938 the previous location will be folded, which may not be what you
6939 want.
6941 This command works around this by showing a copy of the current
6942 buffer in an indirect buffer, in overview mode. You can dive
6943 into the tree in that copy, use org-occur and incremental search
6944 to find a location. When pressing RET or `Q', the command
6945 returns to the original buffer in which the visibility is still
6946 unchanged. After RET it will also jump to the location selected
6947 in the indirect buffer and expose the headline hierarchy above.
6949 With a prefix argument, use the alternative interface: e.g. if
6950 `org-goto-interface' is 'outline use 'outline-path-completion."
6951 (interactive "P")
6952 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6953 (org-refile-use-outline-path t)
6954 (org-refile-target-verify-function nil)
6955 (interface
6956 (if (not alternative-interface)
6957 org-goto-interface
6958 (if (eq org-goto-interface 'outline)
6959 'outline-path-completion
6960 'outline)))
6961 (org-goto-start-pos (point))
6962 (selected-point
6963 (if (eq interface 'outline)
6964 (car (org-get-location (current-buffer) org-goto-help))
6965 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6966 (org-refile-check-position pa)
6967 (nth 3 pa)))))
6968 (if selected-point
6969 (progn
6970 (org-mark-ring-push org-goto-start-pos)
6971 (goto-char selected-point)
6972 (if (or (outline-invisible-p) (org-invisible-p2))
6973 (org-show-context 'org-goto)))
6974 (message "Quit"))))
6976 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6977 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6978 (defvar org-goto-local-auto-isearch-map) ; defined below
6980 (defun org-get-location (buf help)
6981 "Let the user select a location in the Org-mode buffer BUF.
6982 This function uses a recursive edit. It returns the selected position
6983 or nil."
6984 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6985 (isearch-hide-immediately nil)
6986 (isearch-search-fun-function
6987 (lambda () 'org-goto-local-search-headings))
6988 (org-goto-selected-point org-goto-exit-command)
6989 (pop-up-frames nil)
6990 (special-display-buffer-names nil)
6991 (special-display-regexps nil)
6992 (special-display-function nil))
6993 (save-excursion
6994 (save-window-excursion
6995 (delete-other-windows)
6996 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6997 (org-pop-to-buffer-same-window
6998 (condition-case nil
6999 (make-indirect-buffer (current-buffer) "*org-goto*")
7000 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7001 (with-output-to-temp-buffer "*Help*"
7002 (princ help))
7003 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7004 (setq buffer-read-only nil)
7005 (let ((org-startup-truncated t)
7006 (org-startup-folded nil)
7007 (org-startup-align-all-tables nil))
7008 (org-mode)
7009 (org-overview))
7010 (setq buffer-read-only t)
7011 (if (and (boundp 'org-goto-start-pos)
7012 (integer-or-marker-p org-goto-start-pos))
7013 (let ((org-show-hierarchy-above t)
7014 (org-show-siblings t)
7015 (org-show-following-heading t))
7016 (goto-char org-goto-start-pos)
7017 (and (outline-invisible-p) (org-show-context)))
7018 (goto-char (point-min)))
7019 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7020 (message "Select location and press RET")
7021 (use-local-map org-goto-map)
7022 (recursive-edit)
7024 (kill-buffer "*org-goto*")
7025 (cons org-goto-selected-point org-goto-exit-command)))
7027 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7028 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7029 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7030 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7032 (defun org-goto-local-search-headings (string bound noerror)
7033 "Search and make sure that any matches are in headlines."
7034 (catch 'return
7035 (while (if isearch-forward
7036 (search-forward string bound noerror)
7037 (search-backward string bound noerror))
7038 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7039 (and (member :headline context)
7040 (not (member :tags context))))
7041 (throw 'return (point))))))
7043 (defun org-goto-local-auto-isearch ()
7044 "Start isearch."
7045 (interactive)
7046 (goto-char (point-min))
7047 (let ((keys (this-command-keys)))
7048 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7049 (isearch-mode t)
7050 (isearch-process-search-char (string-to-char keys)))))
7052 (defun org-goto-ret (&optional arg)
7053 "Finish `org-goto' by going to the new location."
7054 (interactive "P")
7055 (setq org-goto-selected-point (point)
7056 org-goto-exit-command 'return)
7057 (throw 'exit nil))
7059 (defun org-goto-left ()
7060 "Finish `org-goto' by going to the new location."
7061 (interactive)
7062 (if (org-at-heading-p)
7063 (progn
7064 (beginning-of-line 1)
7065 (setq org-goto-selected-point (point)
7066 org-goto-exit-command 'left)
7067 (throw 'exit nil))
7068 (error "Not on a heading")))
7070 (defun org-goto-right ()
7071 "Finish `org-goto' by going to the new location."
7072 (interactive)
7073 (if (org-at-heading-p)
7074 (progn
7075 (setq org-goto-selected-point (point)
7076 org-goto-exit-command 'right)
7077 (throw 'exit nil))
7078 (error "Not on a heading")))
7080 (defun org-goto-quit ()
7081 "Finish `org-goto' without cursor motion."
7082 (interactive)
7083 (setq org-goto-selected-point nil)
7084 (setq org-goto-exit-command 'quit)
7085 (throw 'exit nil))
7087 ;;; Indirect buffer display of subtrees
7089 (defvar org-indirect-dedicated-frame nil
7090 "This is the frame being used for indirect tree display.")
7091 (defvar org-last-indirect-buffer nil)
7093 (defun org-tree-to-indirect-buffer (&optional arg)
7094 "Create indirect buffer and narrow it to current subtree.
7095 With a numerical prefix ARG, go up to this level and then take that tree.
7096 If ARG is negative, go up that many levels.
7098 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7099 indirect buffer previously made with this command, to avoid proliferation of
7100 indirect buffers. However, when you call the command with a \
7101 \\[universal-argument] prefix, or
7102 when `org-indirect-buffer-display' is `new-frame', the last buffer
7103 is kept so that you can work with several indirect buffers at the same time.
7104 If `org-indirect-buffer-display' is `dedicated-frame', the \
7105 \\[universal-argument] prefix also
7106 requests that a new frame be made for the new buffer, so that the dedicated
7107 frame is not changed."
7108 (interactive "P")
7109 (let ((cbuf (current-buffer))
7110 (cwin (selected-window))
7111 (pos (point))
7112 beg end level heading ibuf)
7113 (save-excursion
7114 (org-back-to-heading t)
7115 (when (numberp arg)
7116 (setq level (org-outline-level))
7117 (if (< arg 0) (setq arg (+ level arg)))
7118 (while (> (setq level (org-outline-level)) arg)
7119 (org-up-heading-safe)))
7120 (setq beg (point)
7121 heading (org-get-heading))
7122 (org-end-of-subtree t t)
7123 (if (org-at-heading-p) (backward-char 1))
7124 (setq end (point)))
7125 (if (and (buffer-live-p org-last-indirect-buffer)
7126 (not (eq org-indirect-buffer-display 'new-frame))
7127 (not arg))
7128 (kill-buffer org-last-indirect-buffer))
7129 (setq ibuf (org-get-indirect-buffer cbuf)
7130 org-last-indirect-buffer ibuf)
7131 (cond
7132 ((or (eq org-indirect-buffer-display 'new-frame)
7133 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7134 (select-frame (make-frame))
7135 (delete-other-windows)
7136 (org-pop-to-buffer-same-window ibuf)
7137 (org-set-frame-title heading))
7138 ((eq org-indirect-buffer-display 'dedicated-frame)
7139 (raise-frame
7140 (select-frame (or (and org-indirect-dedicated-frame
7141 (frame-live-p org-indirect-dedicated-frame)
7142 org-indirect-dedicated-frame)
7143 (setq org-indirect-dedicated-frame (make-frame)))))
7144 (delete-other-windows)
7145 (org-pop-to-buffer-same-window ibuf)
7146 (org-set-frame-title (concat "Indirect: " heading)))
7147 ((eq org-indirect-buffer-display 'current-window)
7148 (org-pop-to-buffer-same-window ibuf))
7149 ((eq org-indirect-buffer-display 'other-window)
7150 (pop-to-buffer ibuf))
7151 (t (error "Invalid value")))
7152 (if (featurep 'xemacs)
7153 (save-excursion (org-mode) (turn-on-font-lock)))
7154 (narrow-to-region beg end)
7155 (show-all)
7156 (goto-char pos)
7157 (run-hook-with-args 'org-cycle-hook 'all)
7158 (and (window-live-p cwin) (select-window cwin))))
7160 (defun org-get-indirect-buffer (&optional buffer)
7161 (setq buffer (or buffer (current-buffer)))
7162 (let ((n 1) (base (buffer-name buffer)) bname)
7163 (while (buffer-live-p
7164 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7165 (setq n (1+ n)))
7166 (condition-case nil
7167 (make-indirect-buffer buffer bname 'clone)
7168 (error (make-indirect-buffer buffer bname)))))
7170 (defun org-set-frame-title (title)
7171 "Set the title of the current frame to the string TITLE."
7172 ;; FIXME: how to name a single frame in XEmacs???
7173 (unless (featurep 'xemacs)
7174 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7176 ;;;; Structure editing
7178 ;;; Inserting headlines
7180 (defun org-previous-line-empty-p ()
7181 (save-excursion
7182 (and (not (bobp))
7183 (or (beginning-of-line 0) t)
7184 (save-match-data
7185 (looking-at "[ \t]*$")))))
7187 (defun org-insert-heading (&optional force-heading invisible-ok)
7188 "Insert a new heading or item with same depth at point.
7189 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7190 If point is at the beginning of a headline, insert a sibling before the
7191 current headline. If point is not at the beginning, split the line,
7192 create the new headline with the text in the current line after point
7193 \(but see also the variable `org-M-RET-may-split-line').
7195 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7196 This is important for non-interactive uses of the command."
7197 (interactive "P")
7198 (if (or (= (buffer-size) 0)
7199 (and (not (save-excursion
7200 (and (ignore-errors (org-back-to-heading invisible-ok))
7201 (org-at-heading-p))))
7202 (or force-heading (not (org-in-item-p)))))
7203 (progn
7204 (insert "\n* ")
7205 (run-hooks 'org-insert-heading-hook))
7206 (when (or force-heading (not (org-insert-item)))
7207 (let* ((empty-line-p nil)
7208 (level nil)
7209 (on-heading (org-at-heading-p))
7210 (head (save-excursion
7211 (condition-case nil
7212 (progn
7213 (org-back-to-heading invisible-ok)
7214 (when (and (not on-heading)
7215 (featurep 'org-inlinetask)
7216 (integerp org-inlinetask-min-level)
7217 (>= (length (match-string 0))
7218 org-inlinetask-min-level))
7219 ;; Find a heading level before the inline task
7220 (while (and (setq level (org-up-heading-safe))
7221 (>= level org-inlinetask-min-level)))
7222 (if (org-at-heading-p)
7223 (org-back-to-heading invisible-ok)
7224 (error "This should not happen")))
7225 (setq empty-line-p (org-previous-line-empty-p))
7226 (match-string 0))
7227 (error "*"))))
7228 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7229 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7230 pos hide-previous previous-pos)
7231 (cond
7232 ((and (org-at-heading-p) (bolp)
7233 (or (bobp)
7234 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7235 ;; insert before the current line
7236 (open-line (if blank 2 1)))
7237 ((and (bolp)
7238 (not org-insert-heading-respect-content)
7239 (or (bobp)
7240 (save-excursion
7241 (backward-char 1) (not (outline-invisible-p)))))
7242 ;; insert right here
7243 nil)
7245 ;; somewhere in the line
7246 (save-excursion
7247 (setq previous-pos (point-at-bol))
7248 (end-of-line)
7249 (setq hide-previous (outline-invisible-p)))
7250 (and org-insert-heading-respect-content (org-show-subtree))
7251 (let ((split
7252 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7253 (save-excursion
7254 (let ((p (point)))
7255 (goto-char (point-at-bol))
7256 (and (looking-at org-complex-heading-regexp)
7257 (match-beginning 4)
7258 (> p (match-beginning 4)))))))
7259 tags pos)
7260 (cond
7261 (org-insert-heading-respect-content
7262 (org-end-of-subtree nil t)
7263 (when (featurep 'org-inlinetask)
7264 (while (and (not (eobp))
7265 (looking-at "\\(\\*+\\)[ \t]+")
7266 (>= (length (match-string 1))
7267 org-inlinetask-min-level))
7268 (org-end-of-subtree nil t)))
7269 (or (bolp) (newline))
7270 (or (org-previous-line-empty-p)
7271 (and blank (newline)))
7272 (open-line 1))
7273 ((org-at-heading-p)
7274 (when hide-previous
7275 (show-children)
7276 (org-show-entry))
7277 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7278 (setq tags (and (match-end 2) (match-string 2)))
7279 (and (match-end 1)
7280 (delete-region (match-beginning 1) (match-end 1)))
7281 (setq pos (point-at-bol))
7282 (or split (end-of-line 1))
7283 (delete-horizontal-space)
7284 (if (string-match "\\`\\*+\\'"
7285 (buffer-substring (point-at-bol) (point)))
7286 (insert " "))
7287 (newline (if blank 2 1))
7288 (when tags
7289 (save-excursion
7290 (goto-char pos)
7291 (end-of-line 1)
7292 (insert " " tags)
7293 (org-set-tags nil 'align))))
7295 (or split (end-of-line 1))
7296 (newline (if blank 2 1)))))))
7297 (insert head) (just-one-space)
7298 (setq pos (point))
7299 (end-of-line 1)
7300 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7301 (when (and org-insert-heading-respect-content hide-previous)
7302 (save-excursion
7303 (goto-char previous-pos)
7304 (hide-subtree)))
7305 (run-hooks 'org-insert-heading-hook)))))
7307 (defun org-get-heading (&optional no-tags no-todo)
7308 "Return the heading of the current entry, without the stars.
7309 When NO-TAGS is non-nil, don't include tags.
7310 When NO-TODO is non-nil, don't include TODO keywords."
7311 (save-excursion
7312 (org-back-to-heading t)
7313 (cond
7314 ((and no-tags no-todo)
7315 (looking-at org-complex-heading-regexp)
7316 (match-string 4))
7317 (no-tags
7318 (looking-at (concat org-outline-regexp
7319 "\\(.*?\\)"
7320 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7321 (match-string 1))
7322 (no-todo
7323 (looking-at org-todo-line-regexp)
7324 (match-string 3))
7325 (t (looking-at org-heading-regexp)
7326 (match-string 2)))))
7328 (defun org-heading-components ()
7329 "Return the components of the current heading.
7330 This is a list with the following elements:
7331 - the level as an integer
7332 - the reduced level, different if `org-odd-levels-only' is set.
7333 - the TODO keyword, or nil
7334 - the priority character, like ?A, or nil if no priority is given
7335 - the headline text itself, or the tags string if no headline text
7336 - the tags string, or nil."
7337 (save-excursion
7338 (org-back-to-heading t)
7339 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7340 (list (length (match-string 1))
7341 (org-reduced-level (length (match-string 1)))
7342 (org-match-string-no-properties 2)
7343 (and (match-end 3) (aref (match-string 3) 2))
7344 (org-match-string-no-properties 4)
7345 (org-match-string-no-properties 5)))))
7347 (defun org-get-entry ()
7348 "Get the entry text, after heading, entire subtree."
7349 (save-excursion
7350 (org-back-to-heading t)
7351 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7353 (defun org-insert-heading-after-current ()
7354 "Insert a new heading with same level as current, after current subtree."
7355 (interactive)
7356 (org-back-to-heading)
7357 (org-insert-heading)
7358 (org-move-subtree-down)
7359 (end-of-line 1))
7361 (defun org-insert-heading-respect-content ()
7362 (interactive)
7363 (let ((org-insert-heading-respect-content t))
7364 (org-insert-heading t)))
7366 (defun org-insert-todo-heading-respect-content (&optional force-state)
7367 (interactive "P")
7368 (let ((org-insert-heading-respect-content t))
7369 (org-insert-todo-heading force-state t)))
7371 (defun org-insert-todo-heading (arg &optional force-heading)
7372 "Insert a new heading with the same level and TODO state as current heading.
7373 If the heading has no TODO state, or if the state is DONE, use the first
7374 state (TODO by default). Also with prefix arg, force first state."
7375 (interactive "P")
7376 (when (or force-heading (not (org-insert-item 'checkbox)))
7377 (org-insert-heading force-heading)
7378 (save-excursion
7379 (org-back-to-heading)
7380 (outline-previous-heading)
7381 (looking-at org-todo-line-regexp))
7382 (let*
7383 ((new-mark-x
7384 (if (or arg
7385 (not (match-beginning 2))
7386 (member (match-string 2) org-done-keywords))
7387 (car org-todo-keywords-1)
7388 (match-string 2)))
7389 (new-mark
7391 (run-hook-with-args-until-success
7392 'org-todo-get-default-hook new-mark-x nil)
7393 new-mark-x)))
7394 (beginning-of-line 1)
7395 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7396 (if org-treat-insert-todo-heading-as-state-change
7397 (org-todo new-mark)
7398 (insert new-mark " "))))
7399 (when org-provide-todo-statistics
7400 (org-update-parent-todo-statistics))))
7402 (defun org-insert-subheading (arg)
7403 "Insert a new subheading and demote it.
7404 Works for outline headings and for plain lists alike."
7405 (interactive "P")
7406 (org-insert-heading arg)
7407 (cond
7408 ((org-at-heading-p) (org-do-demote))
7409 ((org-at-item-p) (org-indent-item))))
7411 (defun org-insert-todo-subheading (arg)
7412 "Insert a new subheading with TODO keyword or checkbox and demote it.
7413 Works for outline headings and for plain lists alike."
7414 (interactive "P")
7415 (org-insert-todo-heading arg)
7416 (cond
7417 ((org-at-heading-p) (org-do-demote))
7418 ((org-at-item-p) (org-indent-item))))
7420 ;;; Promotion and Demotion
7422 (defvar org-after-demote-entry-hook nil
7423 "Hook run after an entry has been demoted.
7424 The cursor will be at the beginning of the entry.
7425 When a subtree is being demoted, the hook will be called for each node.")
7427 (defvar org-after-promote-entry-hook nil
7428 "Hook run after an entry has been promoted.
7429 The cursor will be at the beginning of the entry.
7430 When a subtree is being promoted, the hook will be called for each node.")
7432 (defun org-promote-subtree ()
7433 "Promote the entire subtree.
7434 See also `org-promote'."
7435 (interactive)
7436 (save-excursion
7437 (org-with-limited-levels (org-map-tree 'org-promote)))
7438 (org-fix-position-after-promote))
7440 (defun org-demote-subtree ()
7441 "Demote the entire subtree. See `org-demote'.
7442 See also `org-promote'."
7443 (interactive)
7444 (save-excursion
7445 (org-with-limited-levels (org-map-tree 'org-demote)))
7446 (org-fix-position-after-promote))
7449 (defun org-do-promote ()
7450 "Promote the current heading higher up the tree.
7451 If the region is active in `transient-mark-mode', promote all headings
7452 in the region."
7453 (interactive)
7454 (save-excursion
7455 (if (org-region-active-p)
7456 (org-map-region 'org-promote (region-beginning) (region-end))
7457 (org-promote)))
7458 (org-fix-position-after-promote))
7460 (defun org-do-demote ()
7461 "Demote the current heading lower down the tree.
7462 If the region is active in `transient-mark-mode', demote all headings
7463 in the region."
7464 (interactive)
7465 (save-excursion
7466 (if (org-region-active-p)
7467 (org-map-region 'org-demote (region-beginning) (region-end))
7468 (org-demote)))
7469 (org-fix-position-after-promote))
7471 (defun org-fix-position-after-promote ()
7472 "Make sure that after pro/demotion cursor position is right."
7473 (let ((pos (point)))
7474 (when (save-excursion
7475 (beginning-of-line 1)
7476 (looking-at org-todo-line-regexp)
7477 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7478 (cond ((eobp) (insert " "))
7479 ((eolp) (insert " "))
7480 ((equal (char-after) ?\ ) (forward-char 1))))))
7482 (defun org-current-level ()
7483 "Return the level of the current entry, or nil if before the first headline.
7484 The level is the number of stars at the beginning of the headline."
7485 (save-excursion
7486 (org-with-limited-levels
7487 (if (ignore-errors (org-back-to-heading t))
7488 (funcall outline-level)))))
7490 (defun org-get-previous-line-level ()
7491 "Return the outline depth of the last headline before the current line.
7492 Returns 0 for the first headline in the buffer, and nil if before the
7493 first headline."
7494 (let ((current-level (org-current-level))
7495 (prev-level (when (> (line-number-at-pos) 1)
7496 (save-excursion
7497 (beginning-of-line 0)
7498 (org-current-level)))))
7499 (cond ((null current-level) nil) ; Before first headline
7500 ((null prev-level) 0) ; At first headline
7501 (prev-level))))
7503 (defun org-reduced-level (l)
7504 "Compute the effective level of a heading.
7505 This takes into account the setting of `org-odd-levels-only'."
7506 (cond
7507 ((zerop l) 0)
7508 (org-odd-levels-only (1+ (floor (/ l 2))))
7509 (t l)))
7511 (defun org-level-increment ()
7512 "Return the number of stars that will be added or removed at a
7513 time to headlines when structure editing, based on the value of
7514 `org-odd-levels-only'."
7515 (if org-odd-levels-only 2 1))
7517 (defun org-get-valid-level (level &optional change)
7518 "Rectify a level change under the influence of `org-odd-levels-only'
7519 LEVEL is a current level, CHANGE is by how much the level should be
7520 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7521 even level numbers will become the next higher odd number."
7522 (if org-odd-levels-only
7523 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7524 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7525 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7526 (max 1 (+ level (or change 0)))))
7528 (if (boundp 'define-obsolete-function-alias)
7529 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7530 (define-obsolete-function-alias 'org-get-legal-level
7531 'org-get-valid-level)
7532 (define-obsolete-function-alias 'org-get-legal-level
7533 'org-get-valid-level "23.1")))
7535 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7536 ;; ̀org-with-limited-levels'
7537 (defun org-promote ()
7538 "Promote the current heading higher up the tree.
7539 If the region is active in `transient-mark-mode', promote all headings
7540 in the region."
7541 (org-back-to-heading t)
7542 (let* ((level (save-match-data (funcall outline-level)))
7543 (after-change-functions (remove 'flyspell-after-change-function
7544 after-change-functions))
7545 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7546 (diff (abs (- level (length up-head) -1))))
7547 (cond ((and (= level 1) org-called-with-limited-levels
7548 org-allow-promoting-top-level-subtree)
7549 (replace-match "# " nil t))
7550 ((= level 1)
7551 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7552 (t (replace-match up-head nil t)))
7553 ;; Fixup tag positioning
7554 (unless (= level 1)
7555 (and org-auto-align-tags (org-set-tags nil t))
7556 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7557 (run-hooks 'org-after-promote-entry-hook)))
7559 (defun org-demote ()
7560 "Demote the current heading lower down the tree.
7561 If the region is active in `transient-mark-mode', demote all headings
7562 in the region."
7563 (org-back-to-heading t)
7564 (let* ((level (save-match-data (funcall outline-level)))
7565 (after-change-functions (remove 'flyspell-after-change-function
7566 after-change-functions))
7567 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7568 (diff (abs (- level (length down-head) -1))))
7569 (replace-match down-head nil t)
7570 ;; Fixup tag positioning
7571 (and org-auto-align-tags (org-set-tags nil t))
7572 (if org-adapt-indentation (org-fixup-indentation diff))
7573 (run-hooks 'org-after-demote-entry-hook)))
7575 (defun org-cycle-level ()
7576 "Cycle the level of an empty headline through possible states.
7577 This goes first to child, then to parent, level, then up the hierarchy.
7578 After top level, it switches back to sibling level."
7579 (interactive)
7580 (let ((org-adapt-indentation nil))
7581 (when (org-point-at-end-of-empty-headline)
7582 (setq this-command 'org-cycle-level) ; Only needed for caching
7583 (let ((cur-level (org-current-level))
7584 (prev-level (org-get-previous-line-level)))
7585 (cond
7586 ;; If first headline in file, promote to top-level.
7587 ((= prev-level 0)
7588 (loop repeat (/ (- cur-level 1) (org-level-increment))
7589 do (org-do-promote)))
7590 ;; If same level as prev, demote one.
7591 ((= prev-level cur-level)
7592 (org-do-demote))
7593 ;; If parent is top-level, promote to top level if not already.
7594 ((= prev-level 1)
7595 (loop repeat (/ (- cur-level 1) (org-level-increment))
7596 do (org-do-promote)))
7597 ;; If top-level, return to prev-level.
7598 ((= cur-level 1)
7599 (loop repeat (/ (- prev-level 1) (org-level-increment))
7600 do (org-do-demote)))
7601 ;; If less than prev-level, promote one.
7602 ((< cur-level prev-level)
7603 (org-do-promote))
7604 ;; If deeper than prev-level, promote until higher than
7605 ;; prev-level.
7606 ((> cur-level prev-level)
7607 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7608 do (org-do-promote))))
7609 t))))
7611 (defun org-map-tree (fun)
7612 "Call FUN for every heading underneath the current one."
7613 (org-back-to-heading)
7614 (let ((level (funcall outline-level)))
7615 (save-excursion
7616 (funcall fun)
7617 (while (and (progn
7618 (outline-next-heading)
7619 (> (funcall outline-level) level))
7620 (not (eobp)))
7621 (funcall fun)))))
7623 (defun org-map-region (fun beg end)
7624 "Call FUN for every heading between BEG and END."
7625 (let ((org-ignore-region t))
7626 (save-excursion
7627 (setq end (copy-marker end))
7628 (goto-char beg)
7629 (if (and (re-search-forward org-outline-regexp-bol nil t)
7630 (< (point) end))
7631 (funcall fun))
7632 (while (and (progn
7633 (outline-next-heading)
7634 (< (point) end))
7635 (not (eobp)))
7636 (funcall fun)))))
7638 (defvar org-property-end-re) ; silence byte-compiler
7639 (defun org-fixup-indentation (diff)
7640 "Change the indentation in the current entry by DIFF.
7641 However, if any line in the current entry has no indentation, or if it
7642 would end up with no indentation after the change, nothing at all is done."
7643 (save-excursion
7644 (let ((end (save-excursion (outline-next-heading)
7645 (point-marker)))
7646 (prohibit (if (> diff 0)
7647 "^\\S-"
7648 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7649 col)
7650 (unless (save-excursion (end-of-line 1)
7651 (re-search-forward prohibit end t))
7652 (while (and (< (point) end)
7653 (re-search-forward "^[ \t]+" end t))
7654 (goto-char (match-end 0))
7655 (setq col (current-column))
7656 (if (< diff 0) (replace-match ""))
7657 (org-indent-to-column (+ diff col))))
7658 (move-marker end nil))))
7660 (defun org-convert-to-odd-levels ()
7661 "Convert an org-mode file with all levels allowed to one with odd levels.
7662 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7663 level 5 etc."
7664 (interactive)
7665 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7666 (let ((outline-level 'org-outline-level)
7667 (org-odd-levels-only nil) n)
7668 (save-excursion
7669 (goto-char (point-min))
7670 (while (re-search-forward "^\\*\\*+ " nil t)
7671 (setq n (- (length (match-string 0)) 2))
7672 (while (>= (setq n (1- n)) 0)
7673 (org-demote))
7674 (end-of-line 1))))))
7676 (defun org-convert-to-oddeven-levels ()
7677 "Convert an org-mode file with only odd levels to one with odd/even levels.
7678 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7679 file contains a section with an even level, conversion would
7680 destroy the structure of the file. An error is signaled in this
7681 case."
7682 (interactive)
7683 (goto-char (point-min))
7684 ;; First check if there are no even levels
7685 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7686 (org-show-context t)
7687 (error "Not all levels are odd in this file. Conversion not possible"))
7688 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7689 (let ((outline-regexp org-outline-regexp)
7690 (outline-level 'org-outline-level)
7691 (org-odd-levels-only nil) n)
7692 (save-excursion
7693 (goto-char (point-min))
7694 (while (re-search-forward "^\\*\\*+ " nil t)
7695 (setq n (/ (1- (length (match-string 0))) 2))
7696 (while (>= (setq n (1- n)) 0)
7697 (org-promote))
7698 (end-of-line 1))))))
7700 (defun org-tr-level (n)
7701 "Make N odd if required."
7702 (if org-odd-levels-only (1+ (/ n 2)) n))
7704 ;;; Vertical tree motion, cutting and pasting of subtrees
7706 (defun org-move-subtree-up (&optional arg)
7707 "Move the current subtree up past ARG headlines of the same level."
7708 (interactive "p")
7709 (org-move-subtree-down (- (prefix-numeric-value arg))))
7711 (defun org-move-subtree-down (&optional arg)
7712 "Move the current subtree down past ARG headlines of the same level."
7713 (interactive "p")
7714 (setq arg (prefix-numeric-value arg))
7715 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7716 'org-get-last-sibling))
7717 (ins-point (make-marker))
7718 (cnt (abs arg))
7719 (col (current-column))
7720 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7721 ;; Select the tree
7722 (org-back-to-heading)
7723 (setq beg0 (point))
7724 (save-excursion
7725 (setq ne-beg (org-back-over-empty-lines))
7726 (setq beg (point)))
7727 (save-match-data
7728 (save-excursion (outline-end-of-heading)
7729 (setq folded (outline-invisible-p)))
7730 (outline-end-of-subtree))
7731 (outline-next-heading)
7732 (setq ne-end (org-back-over-empty-lines))
7733 (setq end (point))
7734 (goto-char beg0)
7735 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7736 ;; include less whitespace
7737 (save-excursion
7738 (goto-char beg)
7739 (forward-line (- ne-beg ne-end))
7740 (setq beg (point))))
7741 ;; Find insertion point, with error handling
7742 (while (> cnt 0)
7743 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7744 (progn (goto-char beg0)
7745 (error "Cannot move past superior level or buffer limit")))
7746 (setq cnt (1- cnt)))
7747 (if (> arg 0)
7748 ;; Moving forward - still need to move over subtree
7749 (progn (org-end-of-subtree t t)
7750 (save-excursion
7751 (org-back-over-empty-lines)
7752 (or (bolp) (newline)))))
7753 (setq ne-ins (org-back-over-empty-lines))
7754 (move-marker ins-point (point))
7755 (setq txt (buffer-substring beg end))
7756 (org-save-markers-in-region beg end)
7757 (delete-region beg end)
7758 (org-remove-empty-overlays-at beg)
7759 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7760 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7761 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7762 (let ((bbb (point)))
7763 (insert-before-markers txt)
7764 (org-reinstall-markers-in-region bbb)
7765 (move-marker ins-point bbb))
7766 (or (bolp) (insert "\n"))
7767 (setq ins-end (point))
7768 (goto-char ins-point)
7769 (org-skip-whitespace)
7770 (when (and (< arg 0)
7771 (org-first-sibling-p)
7772 (> ne-ins ne-beg))
7773 ;; Move whitespace back to beginning
7774 (save-excursion
7775 (goto-char ins-end)
7776 (let ((kill-whole-line t))
7777 (kill-line (- ne-ins ne-beg)) (point)))
7778 (insert (make-string (- ne-ins ne-beg) ?\n)))
7779 (move-marker ins-point nil)
7780 (if folded
7781 (hide-subtree)
7782 (org-show-entry)
7783 (show-children)
7784 (org-cycle-hide-drawers 'children))
7785 (org-clean-visibility-after-subtree-move)
7786 ;; move back to the initial column we were at
7787 (move-to-column col)))
7789 (defvar org-subtree-clip ""
7790 "Clipboard for cut and paste of subtrees.
7791 This is actually only a copy of the kill, because we use the normal kill
7792 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7794 (defvar org-subtree-clip-folded nil
7795 "Was the last copied subtree folded?
7796 This is used to fold the tree back after pasting.")
7798 (defun org-cut-subtree (&optional n)
7799 "Cut the current subtree into the clipboard.
7800 With prefix arg N, cut this many sequential subtrees.
7801 This is a short-hand for marking the subtree and then cutting it."
7802 (interactive "p")
7803 (org-copy-subtree n 'cut))
7805 (defun org-copy-subtree (&optional n cut force-store-markers)
7806 "Cut the current subtree into the clipboard.
7807 With prefix arg N, cut this many sequential subtrees.
7808 This is a short-hand for marking the subtree and then copying it.
7809 If CUT is non-nil, actually cut the subtree.
7810 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7811 of some markers in the region, even if CUT is non-nil. This is
7812 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7813 (interactive "p")
7814 (let (beg end folded (beg0 (point)))
7815 (if (org-called-interactively-p 'any)
7816 (org-back-to-heading nil) ; take what looks like a subtree
7817 (org-back-to-heading t)) ; take what is really there
7818 (org-back-over-empty-lines)
7819 (setq beg (point))
7820 (skip-chars-forward " \t\r\n")
7821 (save-match-data
7822 (save-excursion (outline-end-of-heading)
7823 (setq folded (outline-invisible-p)))
7824 (condition-case nil
7825 (org-forward-heading-same-level (1- n) t)
7826 (error nil))
7827 (org-end-of-subtree t t))
7828 (org-back-over-empty-lines)
7829 (setq end (point))
7830 (goto-char beg0)
7831 (when (> end beg)
7832 (setq org-subtree-clip-folded folded)
7833 (when (or cut force-store-markers)
7834 (org-save-markers-in-region beg end))
7835 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7836 (setq org-subtree-clip (current-kill 0))
7837 (message "%s: Subtree(s) with %d characters"
7838 (if cut "Cut" "Copied")
7839 (length org-subtree-clip)))))
7841 (defun org-paste-subtree (&optional level tree for-yank)
7842 "Paste the clipboard as a subtree, with modification of headline level.
7843 The entire subtree is promoted or demoted in order to match a new headline
7844 level.
7846 If the cursor is at the beginning of a headline, the same level as
7847 that headline is used to paste the tree
7849 If not, the new level is derived from the *visible* headings
7850 before and after the insertion point, and taken to be the inferior headline
7851 level of the two. So if the previous visible heading is level 3 and the
7852 next is level 4 (or vice versa), level 4 will be used for insertion.
7853 This makes sure that the subtree remains an independent subtree and does
7854 not swallow low level entries.
7856 You can also force a different level, either by using a numeric prefix
7857 argument, or by inserting the heading marker by hand. For example, if the
7858 cursor is after \"*****\", then the tree will be shifted to level 5.
7860 If optional TREE is given, use this text instead of the kill ring.
7862 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7863 move back over whitespace before inserting, and move point to the end of
7864 the inserted text when done."
7865 (interactive "P")
7866 (setq tree (or tree (and kill-ring (current-kill 0))))
7867 (unless (org-kill-is-subtree-p tree)
7868 (error "%s"
7869 (substitute-command-keys
7870 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7871 (org-with-limited-levels
7872 (let* ((visp (not (outline-invisible-p)))
7873 (txt tree)
7874 (^re_ "\\(\\*+\\)[ \t]*")
7875 (old-level (if (string-match org-outline-regexp-bol txt)
7876 (- (match-end 0) (match-beginning 0) 1)
7877 -1))
7878 (force-level (cond (level (prefix-numeric-value level))
7879 ((and (looking-at "[ \t]*$")
7880 (string-match
7881 "^\\*+$" (buffer-substring
7882 (point-at-bol) (point))))
7883 (- (match-end 1) (match-beginning 1)))
7884 ((and (bolp)
7885 (looking-at org-outline-regexp))
7886 (- (match-end 0) (point) 1))))
7887 (previous-level (save-excursion
7888 (condition-case nil
7889 (progn
7890 (outline-previous-visible-heading 1)
7891 (if (looking-at ^re_)
7892 (- (match-end 0) (match-beginning 0) 1)
7894 (error 1))))
7895 (next-level (save-excursion
7896 (condition-case nil
7897 (progn
7898 (or (looking-at org-outline-regexp)
7899 (outline-next-visible-heading 1))
7900 (if (looking-at ^re_)
7901 (- (match-end 0) (match-beginning 0) 1)
7903 (error 1))))
7904 (new-level (or force-level (max previous-level next-level)))
7905 (shift (if (or (= old-level -1)
7906 (= new-level -1)
7907 (= old-level new-level))
7909 (- new-level old-level)))
7910 (delta (if (> shift 0) -1 1))
7911 (func (if (> shift 0) 'org-demote 'org-promote))
7912 (org-odd-levels-only nil)
7913 beg end newend)
7914 ;; Remove the forced level indicator
7915 (if force-level
7916 (delete-region (point-at-bol) (point)))
7917 ;; Paste
7918 (beginning-of-line (if (bolp) 1 2))
7919 (unless for-yank (org-back-over-empty-lines))
7920 (setq beg (point))
7921 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7922 (insert-before-markers txt)
7923 (unless (string-match "\n\\'" txt) (insert "\n"))
7924 (setq newend (point))
7925 (org-reinstall-markers-in-region beg)
7926 (setq end (point))
7927 (goto-char beg)
7928 (skip-chars-forward " \t\n\r")
7929 (setq beg (point))
7930 (if (and (outline-invisible-p) visp)
7931 (save-excursion (outline-show-heading)))
7932 ;; Shift if necessary
7933 (unless (= shift 0)
7934 (save-restriction
7935 (narrow-to-region beg end)
7936 (while (not (= shift 0))
7937 (org-map-region func (point-min) (point-max))
7938 (setq shift (+ delta shift)))
7939 (goto-char (point-min))
7940 (setq newend (point-max))))
7941 (when (or (org-called-interactively-p 'interactive) for-yank)
7942 (message "Clipboard pasted as level %d subtree" new-level))
7943 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7944 kill-ring
7945 (eq org-subtree-clip (current-kill 0))
7946 org-subtree-clip-folded)
7947 ;; The tree was folded before it was killed/copied
7948 (hide-subtree))
7949 (and for-yank (goto-char newend)))))
7951 (defun org-kill-is-subtree-p (&optional txt)
7952 "Check if the current kill is an outline subtree, or a set of trees.
7953 Returns nil if kill does not start with a headline, or if the first
7954 headline level is not the largest headline level in the tree.
7955 So this will actually accept several entries of equal levels as well,
7956 which is OK for `org-paste-subtree'.
7957 If optional TXT is given, check this string instead of the current kill."
7958 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7959 (re (org-get-limited-outline-regexp))
7960 (^re (concat "^" re))
7961 (start-level (and kill
7962 (string-match
7963 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7964 kill)
7965 (- (match-end 2) (match-beginning 2) 1)))
7966 (start (1+ (or (match-beginning 2) -1))))
7967 (if (not start-level)
7968 (progn
7969 nil) ;; does not even start with a heading
7970 (catch 'exit
7971 (while (setq start (string-match ^re kill (1+ start)))
7972 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7973 (throw 'exit nil)))
7974 t))))
7976 (defvar org-markers-to-move nil
7977 "Markers that should be moved with a cut-and-paste operation.
7978 Those markers are stored together with their positions relative to
7979 the start of the region.")
7981 (defun org-save-markers-in-region (beg end)
7982 "Check markers in region.
7983 If these markers are between BEG and END, record their position relative
7984 to BEG, so that after moving the block of text, we can put the markers back
7985 into place.
7986 This function gets called just before an entry or tree gets cut from the
7987 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7988 called immediately, to move the markers with the entries."
7989 (setq org-markers-to-move nil)
7990 (when (featurep 'org-clock)
7991 (org-clock-save-markers-for-cut-and-paste beg end))
7992 (when (featurep 'org-agenda)
7993 (org-agenda-save-markers-for-cut-and-paste beg end)))
7995 (defun org-check-and-save-marker (marker beg end)
7996 "Check if MARKER is between BEG and END.
7997 If yes, remember the marker and the distance to BEG."
7998 (when (and (marker-buffer marker)
7999 (equal (marker-buffer marker) (current-buffer)))
8000 (if (and (>= marker beg) (< marker end))
8001 (push (cons marker (- marker beg)) org-markers-to-move))))
8003 (defun org-reinstall-markers-in-region (beg)
8004 "Move all remembered markers to their position relative to BEG."
8005 (mapc (lambda (x)
8006 (move-marker (car x) (+ beg (cdr x))))
8007 org-markers-to-move)
8008 (setq org-markers-to-move nil))
8010 (defun org-narrow-to-subtree ()
8011 "Narrow buffer to the current subtree."
8012 (interactive)
8013 (save-excursion
8014 (save-match-data
8015 (org-with-limited-levels
8016 (narrow-to-region
8017 (progn (org-back-to-heading t) (point))
8018 (progn (org-end-of-subtree t t)
8019 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8020 (point)))))))
8022 (defun org-narrow-to-block ()
8023 "Narrow buffer to the current block."
8024 (interactive)
8025 (let* ((case-fold-search t)
8026 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8027 "^[ \t]*#\\+end_.*")))
8028 (if blockp
8029 (narrow-to-region (car blockp) (cdr blockp))
8030 (error "Not in a block"))))
8032 (eval-when-compile
8033 (defvar org-property-drawer-re))
8035 (defvar org-property-start-re) ;; defined below
8036 (defun org-clone-subtree-with-time-shift (n &optional shift)
8037 "Clone the task (subtree) at point N times.
8038 The clones will be inserted as siblings.
8040 In interactive use, the user will be prompted for the number of
8041 clones to be produced, and for a time SHIFT, which may be a
8042 repeater as used in time stamps, for example `+3d'.
8044 When a valid repeater is given and the entry contains any time
8045 stamps, the clones will become a sequence in time, with time
8046 stamps in the subtree shifted for each clone produced. If SHIFT
8047 is nil or the empty string, time stamps will be left alone. The
8048 ID property of the original subtree is removed.
8050 If the original subtree did contain time stamps with a repeater,
8051 the following will happen:
8052 - the repeater will be removed in each clone
8053 - an additional clone will be produced, with the current, unshifted
8054 date(s) in the entry.
8055 - the original entry will be placed *after* all the clones, with
8056 repeater intact.
8057 - the start days in the repeater in the original entry will be shifted
8058 to past the last clone.
8059 In this way you can spell out a number of instances of a repeating task,
8060 and still retain the repeater to cover future instances of the task."
8061 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8062 (let (beg end template task idprop
8063 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8064 (drawer-re org-drawer-regexp))
8065 (if (not (and (integerp n) (> n 0)))
8066 (error "Invalid number of replications %s" n))
8067 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8068 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8069 shift)))
8070 (error "Invalid shift specification %s" shift))
8071 (when doshift
8072 (setq shift-n (string-to-number (match-string 1 shift))
8073 shift-what (cdr (assoc (match-string 2 shift)
8074 '(("d" . day) ("w" . week)
8075 ("m" . month) ("y" . year))))))
8076 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8077 (setq nmin 1 nmax n)
8078 (org-back-to-heading t)
8079 (setq beg (point))
8080 (setq idprop (org-entry-get nil "ID"))
8081 (org-end-of-subtree t t)
8082 (or (bolp) (insert "\n"))
8083 (setq end (point))
8084 (setq template (buffer-substring beg end))
8085 (when (and doshift
8086 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8087 (delete-region beg end)
8088 (setq end beg)
8089 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8090 (goto-char end)
8091 (loop for n from nmin to nmax do
8092 ;; prepare clone
8093 (with-temp-buffer
8094 (insert template)
8095 (org-mode)
8096 (goto-char (point-min))
8097 (org-show-subtree)
8098 (and idprop (if org-clone-delete-id
8099 (org-entry-delete nil "ID")
8100 (org-id-get-create t)))
8101 (unless (= n 0)
8102 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8103 (kill-whole-line))
8104 (goto-char (point-min))
8105 (while (re-search-forward drawer-re nil t)
8106 (mapc (lambda (d)
8107 (org-remove-empty-drawer-at d (point))) org-drawers)))
8108 (goto-char (point-min))
8109 (when doshift
8110 (while (re-search-forward org-ts-regexp-both nil t)
8111 (org-timestamp-change (* n shift-n) shift-what))
8112 (unless (= n n-no-remove)
8113 (goto-char (point-min))
8114 (while (re-search-forward org-ts-regexp nil t)
8115 (save-excursion
8116 (goto-char (match-beginning 0))
8117 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8118 (delete-region (match-beginning 1) (match-end 1)))))))
8119 (setq task (buffer-string)))
8120 (insert task))
8121 (goto-char beg)))
8123 ;;; Outline Sorting
8125 (defun org-sort (with-case)
8126 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8127 Optional argument WITH-CASE means sort case-sensitively."
8128 (interactive "P")
8129 (cond
8130 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8131 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8133 (org-call-with-arg 'org-sort-entries with-case))))
8135 (defun org-sort-remove-invisible (s)
8136 (remove-text-properties 0 (length s) org-rm-props s)
8137 (while (string-match org-bracket-link-regexp s)
8138 (setq s (replace-match (if (match-end 2)
8139 (match-string 3 s)
8140 (match-string 1 s)) t t s)))
8143 (defvar org-priority-regexp) ; defined later in the file
8145 (defvar org-after-sorting-entries-or-items-hook nil
8146 "Hook that is run after a bunch of entries or items have been sorted.
8147 When children are sorted, the cursor is in the parent line when this
8148 hook gets called. When a region or a plain list is sorted, the cursor
8149 will be in the first entry of the sorted region/list.")
8151 (defun org-sort-entries
8152 (&optional with-case sorting-type getkey-func compare-func property)
8153 "Sort entries on a certain level of an outline tree.
8154 If there is an active region, the entries in the region are sorted.
8155 Else, if the cursor is before the first entry, sort the top-level items.
8156 Else, the children of the entry at point are sorted.
8158 Sorting can be alphabetically, numerically, by date/time as given by
8159 a time stamp, by a property or by priority.
8161 The command prompts for the sorting type unless it has been given to the
8162 function through the SORTING-TYPE argument, which needs to be a character,
8163 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8164 precise meaning of each character:
8166 n Numerically, by converting the beginning of the entry/item to a number.
8167 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8168 t By date/time, either the first active time stamp in the entry, or, if
8169 none exist, by the first inactive one.
8170 s By the scheduled date/time.
8171 d By deadline date/time.
8172 c By creation time, which is assumed to be the first inactive time stamp
8173 at the beginning of a line.
8174 p By priority according to the cookie.
8175 r By the value of a property.
8177 Capital letters will reverse the sort order.
8179 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8180 called with point at the beginning of the record. It must return either
8181 a string or a number that should serve as the sorting key for that record.
8183 Comparing entries ignores case by default. However, with an optional argument
8184 WITH-CASE, the sorting considers case as well."
8185 (interactive "P")
8186 (let ((case-func (if with-case 'identity 'downcase))
8187 start beg end stars re re2
8188 txt what tmp)
8189 ;; Find beginning and end of region to sort
8190 (cond
8191 ((org-region-active-p)
8192 ;; we will sort the region
8193 (setq end (region-end)
8194 what "region")
8195 (goto-char (region-beginning))
8196 (if (not (org-at-heading-p)) (outline-next-heading))
8197 (setq start (point)))
8198 ((or (org-at-heading-p)
8199 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8200 ;; we will sort the children of the current headline
8201 (org-back-to-heading)
8202 (setq start (point)
8203 end (progn (org-end-of-subtree t t)
8204 (or (bolp) (insert "\n"))
8205 (org-back-over-empty-lines)
8206 (point))
8207 what "children")
8208 (goto-char start)
8209 (show-subtree)
8210 (outline-next-heading))
8212 ;; we will sort the top-level entries in this file
8213 (goto-char (point-min))
8214 (or (org-at-heading-p) (outline-next-heading))
8215 (setq start (point))
8216 (goto-char (point-max))
8217 (beginning-of-line 1)
8218 (when (looking-at ".*?\\S-")
8219 ;; File ends in a non-white line
8220 (end-of-line 1)
8221 (insert "\n"))
8222 (setq end (point-max))
8223 (setq what "top-level")
8224 (goto-char start)
8225 (show-all)))
8227 (setq beg (point))
8228 (if (>= beg end) (error "Nothing to sort"))
8230 (looking-at "\\(\\*+\\)")
8231 (setq stars (match-string 1)
8232 re (concat "^" (regexp-quote stars) " +")
8233 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8234 txt (buffer-substring beg end))
8235 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8236 (if (and (not (equal stars "*")) (string-match re2 txt))
8237 (error "Region to sort contains a level above the first entry"))
8239 (unless sorting-type
8240 (message
8241 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8242 [t]ime [s]cheduled [d]eadline [c]reated
8243 A/N/T/S/D/C/P/O/F means reversed:"
8244 what)
8245 (setq sorting-type (read-char-exclusive))
8247 (and (= (downcase sorting-type) ?f)
8248 (setq getkey-func
8249 (org-icompleting-read "Sort using function: "
8250 obarray 'fboundp t nil nil))
8251 (setq getkey-func (intern getkey-func)))
8253 (and (= (downcase sorting-type) ?r)
8254 (setq property
8255 (org-icompleting-read "Property: "
8256 (mapcar 'list (org-buffer-property-keys t))
8257 nil t))))
8259 (message "Sorting entries...")
8261 (save-restriction
8262 (narrow-to-region start end)
8263 (let ((dcst (downcase sorting-type))
8264 (case-fold-search nil)
8265 (now (current-time)))
8266 (sort-subr
8267 (/= dcst sorting-type)
8268 ;; This function moves to the beginning character of the "record" to
8269 ;; be sorted.
8270 (lambda nil
8271 (if (re-search-forward re nil t)
8272 (goto-char (match-beginning 0))
8273 (goto-char (point-max))))
8274 ;; This function moves to the last character of the "record" being
8275 ;; sorted.
8276 (lambda nil
8277 (save-match-data
8278 (condition-case nil
8279 (outline-forward-same-level 1)
8280 (error
8281 (goto-char (point-max))))))
8282 ;; This function returns the value that gets sorted against.
8283 (lambda nil
8284 (cond
8285 ((= dcst ?n)
8286 (if (looking-at org-complex-heading-regexp)
8287 (string-to-number (match-string 4))
8288 nil))
8289 ((= dcst ?a)
8290 (if (looking-at org-complex-heading-regexp)
8291 (funcall case-func (match-string 4))
8292 nil))
8293 ((= dcst ?t)
8294 (let ((end (save-excursion (outline-next-heading) (point))))
8295 (if (or (re-search-forward org-ts-regexp end t)
8296 (re-search-forward org-ts-regexp-both end t))
8297 (org-time-string-to-seconds (match-string 0))
8298 (org-float-time now))))
8299 ((= dcst ?c)
8300 (let ((end (save-excursion (outline-next-heading) (point))))
8301 (if (re-search-forward
8302 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8303 end t)
8304 (org-time-string-to-seconds (match-string 0))
8305 (org-float-time now))))
8306 ((= dcst ?s)
8307 (let ((end (save-excursion (outline-next-heading) (point))))
8308 (if (re-search-forward org-scheduled-time-regexp end t)
8309 (org-time-string-to-seconds (match-string 1))
8310 (org-float-time now))))
8311 ((= dcst ?d)
8312 (let ((end (save-excursion (outline-next-heading) (point))))
8313 (if (re-search-forward org-deadline-time-regexp end t)
8314 (org-time-string-to-seconds (match-string 1))
8315 (org-float-time now))))
8316 ((= dcst ?p)
8317 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8318 (string-to-char (match-string 2))
8319 org-default-priority))
8320 ((= dcst ?r)
8321 (or (org-entry-get nil property) ""))
8322 ((= dcst ?o)
8323 (if (looking-at org-complex-heading-regexp)
8324 (- 9999 (length (member (match-string 2)
8325 org-todo-keywords-1)))))
8326 ((= dcst ?f)
8327 (if getkey-func
8328 (progn
8329 (setq tmp (funcall getkey-func))
8330 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8331 tmp)
8332 (error "Invalid key function `%s'" getkey-func)))
8333 (t (error "Invalid sorting type `%c'" sorting-type))))
8335 (cond
8336 ((= dcst ?a) 'string<)
8337 ((= dcst ?f) compare-func)
8338 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8339 (run-hooks 'org-after-sorting-entries-or-items-hook)
8340 (message "Sorting entries...done")))
8342 (defun org-do-sort (table what &optional with-case sorting-type)
8343 "Sort TABLE of WHAT according to SORTING-TYPE.
8344 The user will be prompted for the SORTING-TYPE if the call to this
8345 function does not specify it. WHAT is only for the prompt, to indicate
8346 what is being sorted. The sorting key will be extracted from
8347 the car of the elements of the table.
8348 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8349 (unless sorting-type
8350 (message
8351 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8352 what)
8353 (setq sorting-type (read-char-exclusive)))
8354 (let ((dcst (downcase sorting-type))
8355 extractfun comparefun)
8356 ;; Define the appropriate functions
8357 (cond
8358 ((= dcst ?n)
8359 (setq extractfun 'string-to-number
8360 comparefun (if (= dcst sorting-type) '< '>)))
8361 ((= dcst ?a)
8362 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8363 (lambda(x) (downcase (org-sort-remove-invisible x))))
8364 comparefun (if (= dcst sorting-type)
8365 'string<
8366 (lambda (a b) (and (not (string< a b))
8367 (not (string= a b)))))))
8368 ((= dcst ?t)
8369 (setq extractfun
8370 (lambda (x)
8371 (if (or (string-match org-ts-regexp x)
8372 (string-match org-ts-regexp-both x))
8373 (org-float-time
8374 (org-time-string-to-time (match-string 0 x)))
8376 comparefun (if (= dcst sorting-type) '< '>)))
8377 (t (error "Invalid sorting type `%c'" sorting-type)))
8379 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8380 table)
8381 (lambda (a b) (funcall comparefun (car a) (car b))))))
8384 ;;; The orgstruct minor mode
8386 ;; Define a minor mode which can be used in other modes in order to
8387 ;; integrate the org-mode structure editing commands.
8389 ;; This is really a hack, because the org-mode structure commands use
8390 ;; keys which normally belong to the major mode. Here is how it
8391 ;; works: The minor mode defines all the keys necessary to operate the
8392 ;; structure commands, but wraps the commands into a function which
8393 ;; tests if the cursor is currently at a headline or a plain list
8394 ;; item. If that is the case, the structure command is used,
8395 ;; temporarily setting many Org-mode variables like regular
8396 ;; expressions for filling etc. However, when any of those keys is
8397 ;; used at a different location, function uses `key-binding' to look
8398 ;; up if the key has an associated command in another currently active
8399 ;; keymap (minor modes, major mode, global), and executes that
8400 ;; command. There might be problems if any of the keys is otherwise
8401 ;; used as a prefix key.
8403 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8404 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8405 ;; addresses this by checking explicitly for both bindings.
8407 (defvar orgstruct-mode-map (make-sparse-keymap)
8408 "Keymap for the minor `orgstruct-mode'.")
8410 (defvar org-local-vars nil
8411 "List of local variables, for use by `orgstruct-mode'.")
8413 ;;;###autoload
8414 (define-minor-mode orgstruct-mode
8415 "Toggle the minor mode `orgstruct-mode'.
8416 This mode is for using Org-mode structure commands in other
8417 modes. The following keys behave as if Org-mode were active, if
8418 the cursor is on a headline, or on a plain list item (both as
8419 defined by Org-mode).
8421 M-up Move entry/item up
8422 M-down Move entry/item down
8423 M-left Promote
8424 M-right Demote
8425 M-S-up Move entry/item up
8426 M-S-down Move entry/item down
8427 M-S-left Promote subtree
8428 M-S-right Demote subtree
8429 M-q Fill paragraph and items like in Org-mode
8430 C-c ^ Sort entries
8431 C-c - Cycle list bullet
8432 TAB Cycle item visibility
8433 M-RET Insert new heading/item
8434 S-M-RET Insert new TODO heading / Checkbox item
8435 C-c C-c Set tags / toggle checkbox"
8436 nil " OrgStruct" nil
8437 (org-load-modules-maybe)
8438 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8440 ;;;###autoload
8441 (defun turn-on-orgstruct ()
8442 "Unconditionally turn on `orgstruct-mode'."
8443 (orgstruct-mode 1))
8445 (defvar org-fb-vars nil)
8446 (make-variable-buffer-local 'org-fb-vars)
8447 (defun orgstruct++-mode (&optional arg)
8448 "Toggle `orgstruct-mode', the enhanced version of it.
8449 In addition to setting orgstruct-mode, this also exports all
8450 indentation and autofilling variables from org-mode into the
8451 buffer. It will also recognize item context in multiline items."
8452 (interactive "P")
8453 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8454 (if (< arg 1)
8455 (progn (orgstruct-mode -1)
8456 (mapc (lambda(v)
8457 (org-set-local (car v)
8458 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8459 org-fb-vars))
8460 (orgstruct-mode 1)
8461 (setq org-fb-vars nil)
8462 (let (var val)
8463 (mapc
8464 (lambda (x)
8465 (when (string-match
8466 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8467 (symbol-name (car x)))
8468 (setq var (car x) val (nth 1 x))
8469 (push (list var `(quote ,(eval var))) org-fb-vars)
8470 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8471 org-local-vars)
8472 (org-set-local 'orgstruct-is-++ t))))
8474 (defvar orgstruct-is-++ nil
8475 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8476 (make-variable-buffer-local 'orgstruct-is-++)
8478 ;;;###autoload
8479 (defun turn-on-orgstruct++ ()
8480 "Unconditionally turn on `orgstruct++-mode'."
8481 (orgstruct++-mode 1))
8483 (defun orgstruct-error ()
8484 "Error when there is no default binding for a structure key."
8485 (interactive)
8486 (error "This key has no function outside structure elements"))
8488 (defun orgstruct-setup ()
8489 "Setup orgstruct keymaps."
8490 (let ((nfunc 0)
8491 (bindings
8492 (list
8493 '([(meta up)] org-metaup)
8494 '([(meta down)] org-metadown)
8495 '([(meta left)] org-metaleft)
8496 '([(meta right)] org-metaright)
8497 '([(meta shift up)] org-shiftmetaup)
8498 '([(meta shift down)] org-shiftmetadown)
8499 '([(meta shift left)] org-shiftmetaleft)
8500 '([(meta shift right)] org-shiftmetaright)
8501 '([?\e (up)] org-metaup)
8502 '([?\e (down)] org-metadown)
8503 '([?\e (left)] org-metaleft)
8504 '([?\e (right)] org-metaright)
8505 '([?\e (shift up)] org-shiftmetaup)
8506 '([?\e (shift down)] org-shiftmetadown)
8507 '([?\e (shift left)] org-shiftmetaleft)
8508 '([?\e (shift right)] org-shiftmetaright)
8509 '([(shift up)] org-shiftup)
8510 '([(shift down)] org-shiftdown)
8511 '([(shift left)] org-shiftleft)
8512 '([(shift right)] org-shiftright)
8513 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8514 '("\M-q" fill-paragraph)
8515 '("\C-c^" org-sort)
8516 '("\C-c-" org-cycle-list-bullet)))
8517 elt key fun cmd)
8518 (while (setq elt (pop bindings))
8519 (setq nfunc (1+ nfunc))
8520 (setq key (org-key (car elt))
8521 fun (nth 1 elt)
8522 cmd (orgstruct-make-binding fun nfunc key))
8523 (org-defkey orgstruct-mode-map key cmd))
8525 ;; Prevent an error for users who forgot to make autoloads
8526 (require 'org-element)
8528 ;; Special treatment needed for TAB and RET
8529 (org-defkey orgstruct-mode-map [(tab)]
8530 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8531 (org-defkey orgstruct-mode-map "\C-i"
8532 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8534 (org-defkey orgstruct-mode-map "\M-\C-m"
8535 (orgstruct-make-binding 'org-insert-heading 105
8536 "\M-\C-m" [(meta return)]))
8537 (org-defkey orgstruct-mode-map [(meta return)]
8538 (orgstruct-make-binding 'org-insert-heading 106
8539 [(meta return)] "\M-\C-m"))
8541 (org-defkey orgstruct-mode-map [(shift meta return)]
8542 (orgstruct-make-binding 'org-insert-todo-heading 107
8543 [(meta return)] "\M-\C-m"))
8545 (org-defkey orgstruct-mode-map "\e\C-m"
8546 (orgstruct-make-binding 'org-insert-heading 108
8547 "\e\C-m" [?\e (return)]))
8548 (org-defkey orgstruct-mode-map [?\e (return)]
8549 (orgstruct-make-binding 'org-insert-heading 109
8550 [?\e (return)] "\e\C-m"))
8551 (org-defkey orgstruct-mode-map [?\e (shift return)]
8552 (orgstruct-make-binding 'org-insert-todo-heading 110
8553 [?\e (return)] "\e\C-m"))
8555 (unless org-local-vars
8556 (setq org-local-vars (org-get-local-variables)))
8560 (defun orgstruct-make-binding (fun n &rest keys)
8561 "Create a function for binding in the structure minor mode.
8562 FUN is the command to call inside a table. N is used to create a unique
8563 command name. KEYS are keys that should be checked in for a command
8564 to execute outside of tables."
8565 (eval
8566 (list 'defun
8567 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8568 '(arg)
8569 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8570 "Outside of structure, run the binding of `"
8571 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8572 "'.")
8573 '(interactive "p")
8574 (list 'if
8575 `(org-context-p 'headline 'item
8576 (and orgstruct-is-++
8577 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8578 'item-body))
8579 (list 'org-run-like-in-org-mode (list 'quote fun))
8580 (list 'let '(orgstruct-mode)
8581 (list 'call-interactively
8582 (append '(or)
8583 (mapcar (lambda (k)
8584 (list 'key-binding k))
8585 keys)
8586 '('orgstruct-error))))))))
8588 (defun org-contextualize-keys (alist contexts)
8589 "Return valid elements in ALIST depending on CONTEXTS.
8591 `org-agenda-custom-commands' or `org-capture-templates' are the
8592 values used for ALIST, and `org-agenda-custom-commands-contexts'
8593 or `org-capture-templates-contexts' are the associated contexts
8594 definitions."
8595 (let ((contexts
8596 ;; normalize contexts
8597 (mapcar
8598 (lambda(c) (cond ((listp (cadr c))
8599 (list (car c) (car c) (cadr c)))
8600 ((string= "" (cadr c))
8601 (list (car c) (car c) (caddr c)))
8602 (t c))) contexts))
8603 (a alist) c r s)
8604 ;; loop over all commands or templates
8605 (while (setq c (pop a))
8606 (let (vrules repl)
8607 (cond
8608 ((not (assoc (car c) contexts))
8609 (push c r))
8610 ((and (assoc (car c) contexts)
8611 (setq vrules (org-contextualize-validate-key
8612 (car c) contexts)))
8613 (mapc (lambda (vr)
8614 (when (not (equal (car vr) (cadr vr)))
8615 (setq repl vr))) vrules)
8616 (if (not repl) (push c r)
8617 (push (cadr repl) s)
8618 (push
8619 (cons (car c)
8620 (cdr (or (assoc (cadr repl) alist)
8621 (error "Undefined key `%s' as contextual replacement for `%s'"
8622 (cadr repl) (car c)))))
8623 r))))))
8624 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8625 (delq
8627 (delete-dups
8628 (mapcar (lambda (x)
8629 (let ((tpl (car x)))
8630 (when (not (delq
8632 (mapcar (lambda(y)
8633 (equal y tpl)) s))) x)))
8634 (reverse r))))))
8636 (defun org-contextualize-validate-key (key contexts)
8637 "Check CONTEXTS for agenda or capture KEY."
8638 (let (r rr res)
8639 (while (setq r (pop contexts))
8640 (mapc
8641 (lambda (rr)
8642 (when
8643 (and (equal key (car r))
8644 (if (functionp rr) (funcall rr)
8645 (or (and (eq (car rr) 'in-file)
8646 (buffer-file-name)
8647 (string-match (cdr rr) (buffer-file-name)))
8648 (and (eq (car rr) 'in-mode)
8649 (string-match (cdr rr) (symbol-name major-mode)))
8650 (when (and (eq (car rr) 'not-in-file)
8651 (buffer-file-name))
8652 (not (string-match (cdr rr) (buffer-file-name))))
8653 (when (eq (car rr) 'not-in-mode)
8654 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8655 (push r res)))
8656 (car (last r))))
8657 (delete-dups (delq nil res))))
8659 (defun org-context-p (&rest contexts)
8660 "Check if local context is any of CONTEXTS.
8661 Possible values in the list of contexts are `table', `headline', and `item'."
8662 (let ((pos (point)))
8663 (goto-char (point-at-bol))
8664 (prog1 (or (and (memq 'table contexts)
8665 (looking-at "[ \t]*|"))
8666 (and (memq 'headline contexts)
8667 (looking-at org-outline-regexp))
8668 (and (memq 'item contexts)
8669 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8670 (and (memq 'item-body contexts)
8671 (org-in-item-p)))
8672 (goto-char pos))))
8674 (defun org-get-local-variables ()
8675 "Return a list of all local variables in an Org mode buffer."
8676 (let (varlist)
8677 (with-current-buffer (get-buffer-create "*Org tmp*")
8678 (erase-buffer)
8679 (org-mode)
8680 (setq varlist (buffer-local-variables)))
8681 (kill-buffer "*Org tmp*")
8682 (delq nil
8683 (mapcar
8684 (lambda (x)
8685 (setq x
8686 (if (symbolp x)
8687 (list x)
8688 (list (car x) (list 'quote (cdr x)))))
8689 (if (string-match
8690 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8691 (symbol-name (car x)))
8692 x nil))
8693 varlist))))
8695 (defun org-clone-local-variables (from-buffer &optional regexp)
8696 "Clone local variables from FROM-BUFFER.
8697 Optional argument REGEXP selects variables to clone."
8698 (mapc
8699 (lambda (pair)
8700 (and (symbolp (car pair))
8701 (or (null regexp)
8702 (string-match regexp (symbol-name (car pair))))
8703 (set (make-local-variable (car pair))
8704 (cdr pair))))
8705 (buffer-local-variables from-buffer)))
8707 ;;;###autoload
8708 (defun org-run-like-in-org-mode (cmd)
8709 "Run a command, pretending that the current buffer is in Org-mode.
8710 This will temporarily bind local variables that are typically bound in
8711 Org-mode to the values they have in Org-mode, and then interactively
8712 call CMD."
8713 (org-load-modules-maybe)
8714 (unless org-local-vars
8715 (setq org-local-vars (org-get-local-variables)))
8716 (eval (list 'let org-local-vars
8717 (list 'call-interactively (list 'quote cmd)))))
8719 ;;;; Archiving
8721 (defun org-get-category (&optional pos force-refresh)
8722 "Get the category applying to position POS."
8723 (save-match-data
8724 (if force-refresh (org-refresh-category-properties))
8725 (let ((pos (or pos (point))))
8726 (or (get-text-property pos 'org-category)
8727 (progn (org-refresh-category-properties)
8728 (get-text-property pos 'org-category))))))
8730 (defun org-refresh-category-properties ()
8731 "Refresh category text properties in the buffer."
8732 (let ((case-fold-search t)
8733 (inhibit-read-only t)
8734 (def-cat (cond
8735 ((null org-category)
8736 (if buffer-file-name
8737 (file-name-sans-extension
8738 (file-name-nondirectory buffer-file-name))
8739 "???"))
8740 ((symbolp org-category) (symbol-name org-category))
8741 (t org-category)))
8742 beg end cat pos optionp)
8743 (org-unmodified
8744 (save-excursion
8745 (save-restriction
8746 (widen)
8747 (goto-char (point-min))
8748 (put-text-property (point) (point-max) 'org-category def-cat)
8749 (while (re-search-forward
8750 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8751 (setq pos (match-end 0)
8752 optionp (equal (char-after (match-beginning 0)) ?#)
8753 cat (org-trim (match-string 2)))
8754 (if optionp
8755 (setq beg (point-at-bol) end (point-max))
8756 (org-back-to-heading t)
8757 (setq beg (point) end (org-end-of-subtree t t)))
8758 (put-text-property beg end 'org-category cat)
8759 (put-text-property beg end 'org-category-position beg)
8760 (goto-char pos)))))))
8763 ;;;; Link Stuff
8765 ;;; Link abbreviations
8767 (defun org-link-expand-abbrev (link)
8768 "Apply replacements as defined in `org-link-abbrev-alist'."
8769 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8770 (let* ((key (match-string 1 link))
8771 (as (or (assoc key org-link-abbrev-alist-local)
8772 (assoc key org-link-abbrev-alist)))
8773 (tag (and (match-end 2) (match-string 3 link)))
8774 rpl)
8775 (if (not as)
8776 link
8777 (setq rpl (cdr as))
8778 (cond
8779 ((symbolp rpl) (funcall rpl tag))
8780 ((string-match "%(\\([^)]+\\))" rpl)
8781 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8782 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8783 ((string-match "%h" rpl)
8784 (replace-match (url-hexify-string (or tag "")) t t rpl))
8785 (t (concat rpl tag)))))
8786 link))
8788 ;;; Storing and inserting links
8790 (defvar org-insert-link-history nil
8791 "Minibuffer history for links inserted with `org-insert-link'.")
8793 (defvar org-stored-links nil
8794 "Contains the links stored with `org-store-link'.")
8796 (defvar org-store-link-plist nil
8797 "Plist with info about the most recently link created with `org-store-link'.")
8799 (defvar org-link-protocols nil
8800 "Link protocols added to Org-mode using `org-add-link-type'.")
8802 (defvar org-store-link-functions nil
8803 "List of functions that are called to create and store a link.
8804 Each function will be called in turn until one returns a non-nil
8805 value. Each function should check if it is responsible for creating
8806 this link (for example by looking at the major mode).
8807 If not, it must exit and return nil.
8808 If yes, it should return a non-nil value after a calling
8809 `org-store-link-props' with a list of properties and values.
8810 Special properties are:
8812 :type The link prefix, like \"http\". This must be given.
8813 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8814 This is obligatory as well.
8815 :description Optional default description for the second pair
8816 of brackets in an Org-mode link. The user can still change
8817 this when inserting this link into an Org-mode buffer.
8819 In addition to these, any additional properties can be specified
8820 and then used in capture templates.")
8822 (defun org-add-link-type (type &optional follow export)
8823 "Add TYPE to the list of `org-link-types'.
8824 Re-compute all regular expressions depending on `org-link-types'
8826 FOLLOW and EXPORT are two functions.
8828 FOLLOW should take the link path as the single argument and do whatever
8829 is necessary to follow the link, for example find a file or display
8830 a mail message.
8832 EXPORT should format the link path for export to one of the export formats.
8833 It should be a function accepting three arguments:
8835 path the path of the link, the text after the prefix (like \"http:\")
8836 desc the description of the link, if any, or a description added by
8837 org-export-normalize-links if there is none
8838 format the export format, a symbol like `html' or `latex' or `ascii'..
8840 The function may use the FORMAT information to return different values
8841 depending on the format. The return value will be put literally into
8842 the exported file. If the return value is nil, this means Org should
8843 do what it normally does with links which do not have EXPORT defined.
8845 Org-mode has a built-in default for exporting links. If you are happy with
8846 this default, there is no need to define an export function for the link
8847 type. For a simple example of an export function, see `org-bbdb.el'."
8848 (add-to-list 'org-link-types type t)
8849 (org-make-link-regexps)
8850 (if (assoc type org-link-protocols)
8851 (setcdr (assoc type org-link-protocols) (list follow export))
8852 (push (list type follow export) org-link-protocols)))
8854 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8855 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8857 ;;;###autoload
8858 (defun org-store-link (arg)
8859 "\\<org-mode-map>Store an org-link to the current location.
8860 This link is added to `org-stored-links' and can later be inserted
8861 into an org-buffer with \\[org-insert-link].
8863 For some link types, a prefix arg is interpreted:
8864 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8865 For file links, arg negates `org-context-in-file-links'."
8866 (interactive "P")
8867 (org-load-modules-maybe)
8868 (setq org-store-link-plist nil) ; reset
8869 (org-with-limited-levels
8870 (let (link cpltxt desc description search txt custom-id agenda-link)
8871 (cond
8873 ((run-hook-with-args-until-success 'org-store-link-functions)
8874 (setq link (plist-get org-store-link-plist :link)
8875 desc (or (plist-get org-store-link-plist :description) link)))
8877 ((org-src-edit-buffer-p)
8878 (let (label gc)
8879 (while (or (not label)
8880 (save-excursion
8881 (save-restriction
8882 (widen)
8883 (goto-char (point-min))
8884 (re-search-forward
8885 (regexp-quote (format org-coderef-label-format label))
8886 nil t))))
8887 (when label (message "Label exists already") (sit-for 2))
8888 (setq label (read-string "Code line label: " label)))
8889 (end-of-line 1)
8890 (setq link (format org-coderef-label-format label))
8891 (setq gc (- 79 (length link)))
8892 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8893 (insert link)
8894 (setq link (concat "(" label ")") desc nil)))
8896 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8897 ;; We are in the agenda, link to referenced location
8898 (let ((m (or (get-text-property (point) 'org-hd-marker)
8899 (get-text-property (point) 'org-marker))))
8900 (when m
8901 (org-with-point-at m
8902 (setq agenda-link
8903 (if (org-called-interactively-p 'any)
8904 (call-interactively 'org-store-link)
8905 (org-store-link nil)))))))
8907 ((eq major-mode 'calendar-mode)
8908 (let ((cd (calendar-cursor-to-date)))
8909 (setq link
8910 (format-time-string
8911 (car org-time-stamp-formats)
8912 (apply 'encode-time
8913 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8914 nil nil nil))))
8915 (org-store-link-props :type "calendar" :date cd)))
8917 ((eq major-mode 'help-mode)
8918 (setq link (concat "help:" (save-excursion
8919 (goto-char (point-min))
8920 (looking-at "^[^ ]+")
8921 (match-string 0))))
8922 (org-store-link-props :type "help"))
8924 ((eq major-mode 'w3-mode)
8925 (setq cpltxt (if (and (buffer-name)
8926 (not (string-match "Untitled" (buffer-name))))
8927 (buffer-name)
8928 (url-view-url t))
8929 link (url-view-url t))
8930 (org-store-link-props :type "w3" :url (url-view-url t)))
8932 ((eq major-mode 'w3m-mode)
8933 (setq cpltxt (or w3m-current-title w3m-current-url)
8934 link w3m-current-url)
8935 (org-store-link-props :type "w3m" :url (url-view-url t)))
8937 ((setq search (run-hook-with-args-until-success
8938 'org-create-file-search-functions))
8939 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8940 "::" search))
8941 (setq cpltxt (or description link)))
8943 ((eq major-mode 'image-mode)
8944 (setq cpltxt (concat "file:"
8945 (abbreviate-file-name buffer-file-name))
8946 link cpltxt)
8947 (org-store-link-props :type "image" :file buffer-file-name))
8949 ((eq major-mode 'dired-mode)
8950 ;; link to the file in the current line
8951 (let ((file (dired-get-filename nil t)))
8952 (setq file (if file
8953 (abbreviate-file-name
8954 (expand-file-name (dired-get-filename nil t)))
8955 ;; otherwise, no file so use current directory.
8956 default-directory))
8957 (setq cpltxt (concat "file:" file)
8958 link cpltxt)))
8960 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8961 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8962 (cond
8963 ((org-in-regexp "<<\\(.*?\\)>>")
8964 (setq cpltxt
8965 (concat "file:"
8966 (abbreviate-file-name
8967 (buffer-file-name (buffer-base-buffer)))
8968 "::" (match-string 1))
8969 link cpltxt))
8970 ((and (featurep 'org-id)
8971 (or (eq org-link-to-org-use-id t)
8972 (and (org-called-interactively-p 'any)
8973 (or (eq org-link-to-org-use-id 'create-if-interactive)
8974 (and (eq org-link-to-org-use-id
8975 'create-if-interactive-and-no-custom-id)
8976 (not custom-id))))
8977 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8978 ;; We can make a link using the ID.
8979 (setq link (condition-case nil
8980 (prog1 (org-id-store-link)
8981 (setq desc (plist-get org-store-link-plist :description)))
8982 (error
8983 ;; probably before first headline, link to file only
8984 (concat "file:"
8985 (abbreviate-file-name
8986 (buffer-file-name (buffer-base-buffer))))))))
8988 ;; Just link to current headline
8989 (setq cpltxt (concat "file:"
8990 (abbreviate-file-name
8991 (buffer-file-name (buffer-base-buffer)))))
8992 ;; Add a context search string
8993 (when (org-xor org-context-in-file-links arg)
8994 (setq txt (cond
8995 ((org-at-heading-p) nil)
8996 ((org-region-active-p)
8997 (buffer-substring (region-beginning) (region-end)))))
8998 (when (or (null txt) (string-match "\\S-" txt))
8999 (setq cpltxt
9000 (concat cpltxt "::"
9001 (condition-case nil
9002 (org-make-org-heading-search-string txt)
9003 (error "")))
9004 desc (or (nth 4 (ignore-errors
9005 (org-heading-components))) "NONE"))))
9006 (if (string-match "::\\'" cpltxt)
9007 (setq cpltxt (substring cpltxt 0 -2)))
9008 (setq link cpltxt))))
9010 ((buffer-file-name (buffer-base-buffer))
9011 ;; Just link to this file here.
9012 (setq cpltxt (concat "file:"
9013 (abbreviate-file-name
9014 (buffer-file-name (buffer-base-buffer)))))
9015 ;; Add a context string
9016 (when (org-xor org-context-in-file-links arg)
9017 (setq txt (if (org-region-active-p)
9018 (buffer-substring (region-beginning) (region-end))
9019 (buffer-substring (point-at-bol) (point-at-eol))))
9020 ;; Only use search option if there is some text.
9021 (when (string-match "\\S-" txt)
9022 (setq cpltxt
9023 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9024 desc "NONE")))
9025 (setq link cpltxt))
9027 ((org-called-interactively-p 'interactive)
9028 (error "Cannot link to a buffer which is not visiting a file"))
9030 (t (setq link nil)))
9032 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9033 (setq link (or link cpltxt)
9034 desc (or desc cpltxt))
9035 (if (equal desc "NONE") (setq desc nil))
9037 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9038 (progn
9039 (setq org-stored-links
9040 (cons (list link desc) org-stored-links))
9041 (message "Stored: %s" (or desc link))
9042 (when custom-id
9043 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9044 "::#" custom-id))
9045 (setq org-stored-links
9046 (cons (list link desc) org-stored-links))))
9047 (or agenda-link (and link (org-make-link-string link desc)))))))
9049 (defun org-store-link-props (&rest plist)
9050 "Store link properties, extract names and addresses."
9051 (let (x adr)
9052 (when (setq x (plist-get plist :from))
9053 (setq adr (mail-extract-address-components x))
9054 (setq plist (plist-put plist :fromname (car adr)))
9055 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9056 (when (setq x (plist-get plist :to))
9057 (setq adr (mail-extract-address-components x))
9058 (setq plist (plist-put plist :toname (car adr)))
9059 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9060 (let ((from (plist-get plist :from))
9061 (to (plist-get plist :to)))
9062 (when (and from to org-from-is-user-regexp)
9063 (setq plist
9064 (plist-put plist :fromto
9065 (if (string-match org-from-is-user-regexp from)
9066 (concat "to %t")
9067 (concat "from %f"))))))
9068 (setq org-store-link-plist plist))
9070 (defun org-add-link-props (&rest plist)
9071 "Add these properties to the link property list."
9072 (let (key value)
9073 (while plist
9074 (setq key (pop plist) value (pop plist))
9075 (setq org-store-link-plist
9076 (plist-put org-store-link-plist key value)))))
9078 (defun org-email-link-description (&optional fmt)
9079 "Return the description part of an email link.
9080 This takes information from `org-store-link-plist' and formats it
9081 according to FMT (default from `org-email-link-description-format')."
9082 (setq fmt (or fmt org-email-link-description-format))
9083 (let* ((p org-store-link-plist)
9084 (to (plist-get p :toaddress))
9085 (from (plist-get p :fromaddress))
9086 (table
9087 (list
9088 (cons "%c" (plist-get p :fromto))
9089 (cons "%F" (plist-get p :from))
9090 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9091 (cons "%T" (plist-get p :to))
9092 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9093 (cons "%s" (plist-get p :subject))
9094 (cons "%d" (plist-get p :date))
9095 (cons "%m" (plist-get p :message-id)))))
9096 (when (string-match "%c" fmt)
9097 ;; Check if the user wrote this message
9098 (if (and org-from-is-user-regexp from to
9099 (save-match-data (string-match org-from-is-user-regexp from)))
9100 (setq fmt (replace-match "to %t" t t fmt))
9101 (setq fmt (replace-match "from %f" t t fmt))))
9102 (org-replace-escapes fmt table)))
9104 (defun org-make-org-heading-search-string (&optional string heading)
9105 "Make search string for STRING or current headline."
9106 (interactive)
9107 (let ((s (or string (org-get-heading)))
9108 (lines org-context-in-file-links))
9109 (unless (and string (not heading))
9110 ;; We are using a headline, clean up garbage in there.
9111 (if (string-match org-todo-regexp s)
9112 (setq s (replace-match "" t t s)))
9113 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9114 (setq s (replace-match "" t t s)))
9115 (setq s (org-trim s))
9116 (if (string-match (concat "^\\(" org-quote-string "\\|"
9117 org-comment-string "\\)") s)
9118 (setq s (replace-match "" t t s)))
9119 (while (string-match org-ts-regexp s)
9120 (setq s (replace-match "" t t s))))
9121 (or string (setq s (concat "*" s))) ; Add * for headlines
9122 (when (and string (integerp lines) (> lines 0))
9123 (let ((slines (org-split-string s "\n")))
9124 (when (< lines (length slines))
9125 (setq s (mapconcat
9126 'identity
9127 (reverse (nthcdr (- (length slines) lines)
9128 (reverse slines))) "\n")))))
9129 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9131 (defun org-make-link-string (link &optional description)
9132 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9133 (unless (string-match "\\S-" link)
9134 (error "Empty link"))
9135 (when (and description
9136 (stringp description)
9137 (not (string-match "\\S-" description)))
9138 (setq description nil))
9139 (when (stringp description)
9140 ;; Remove brackets from the description, they are fatal.
9141 (while (string-match "\\[" description)
9142 (setq description (replace-match "{" t t description)))
9143 (while (string-match "\\]" description)
9144 (setq description (replace-match "}" t t description))))
9145 (when (equal link description)
9146 ;; No description needed, it is identical
9147 (setq description nil))
9148 (when (and (not description)
9149 (not (string-match (org-image-file-name-regexp) link))
9150 (not (equal link (org-link-escape link))))
9151 (setq description (org-extract-attributes link)))
9152 (setq link
9153 (cond ((string-match (org-image-file-name-regexp) link) link)
9154 ((string-match org-link-types-re link)
9155 (concat (match-string 1 link)
9156 (org-link-escape (substring link (match-end 1)))))
9157 (t (org-link-escape link))))
9158 (concat "[[" link "]"
9159 (if description (concat "[" description "]") "")
9160 "]"))
9162 (defconst org-link-escape-chars
9163 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9164 "List of characters that should be escaped in link.
9165 This is the list that is used for internal purposes.")
9167 (defconst org-link-escape-chars-browser
9168 '(?\ )
9169 "List of escapes for characters that are problematic in links.
9170 This is the list that is used before handing over to the browser.")
9172 (defun org-link-escape (text &optional table merge)
9173 "Return percent escaped representation of TEXT.
9174 TEXT is a string with the text to escape.
9175 Optional argument TABLE is a list with characters that should be
9176 escaped. When nil, `org-link-escape-chars' is used.
9177 If optional argument MERGE is set, merge TABLE into
9178 `org-link-escape-chars'."
9179 (cond
9180 ((and table merge)
9181 (mapc (lambda (defchr)
9182 (unless (member defchr table)
9183 (setq table (cons defchr table)))) org-link-escape-chars))
9184 ((null table)
9185 (setq table org-link-escape-chars)))
9186 (mapconcat
9187 (lambda (char)
9188 (if (or (member char table)
9189 (and (or (< char 32) (= char 37) (> char 126))
9190 org-url-hexify-p))
9191 (mapconcat (lambda (sequence-element)
9192 (format "%%%.2X" sequence-element))
9193 (or (encode-coding-char char 'utf-8)
9194 (error "Unable to percent escape character: %s"
9195 (char-to-string char))) "")
9196 (char-to-string char))) text ""))
9198 (defun org-link-unescape (str)
9199 "Unhex hexified Unicode strings as returned from the JavaScript function
9200 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9201 (unless (and (null str) (string= "" str))
9202 (let ((pos 0) (case-fold-search t) unhexed)
9203 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9204 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9205 (setq str (replace-match unhexed t t str))
9206 (setq pos (+ pos (length unhexed))))))
9207 str)
9209 (defun org-link-unescape-compound (hex)
9210 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9211 Note: this function also decodes single byte encodings like
9212 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9213 (save-match-data
9214 (let* ((bytes (cdr (split-string hex "%")))
9215 (ret "")
9216 (eat 0)
9217 (sum 0))
9218 (while bytes
9219 (let* ((val (string-to-number (pop bytes) 16))
9220 (shift-xor
9221 (if (= 0 eat)
9222 (cond
9223 ((>= val 252) (cons 6 252))
9224 ((>= val 248) (cons 5 248))
9225 ((>= val 240) (cons 4 240))
9226 ((>= val 224) (cons 3 224))
9227 ((>= val 192) (cons 2 192))
9228 (t (cons 0 0)))
9229 (cons 6 128))))
9230 (if (>= val 192) (setq eat (car shift-xor)))
9231 (setq val (logxor val (cdr shift-xor)))
9232 (setq sum (+ (lsh sum (car shift-xor)) val))
9233 (if (> eat 0) (setq eat (- eat 1)))
9234 (cond
9235 ((= 0 eat) ;multi byte
9236 (setq ret (concat ret (org-char-to-string sum)))
9237 (setq sum 0))
9238 ((not bytes) ; single byte(s)
9239 (setq ret (org-link-unescape-single-byte-sequence hex))))
9240 )) ;; end (while bytes
9241 ret )))
9243 (defun org-link-unescape-single-byte-sequence (hex)
9244 "Unhexify hex-encoded single byte character sequences."
9245 (mapconcat (lambda (byte)
9246 (char-to-string (string-to-number byte 16)))
9247 (cdr (split-string hex "%")) ""))
9249 (defun org-xor (a b)
9250 "Exclusive or."
9251 (if a (not b) b))
9253 (defun org-fixup-message-id-for-http (s)
9254 "Replace special characters in a message id, so it can be used in an http query."
9255 (when (string-match "%" s)
9256 (setq s (mapconcat (lambda (c)
9257 (if (eq c ?%)
9258 "%25"
9259 (char-to-string c)))
9260 s "")))
9261 (while (string-match "<" s)
9262 (setq s (replace-match "%3C" t t s)))
9263 (while (string-match ">" s)
9264 (setq s (replace-match "%3E" t t s)))
9265 (while (string-match "@" s)
9266 (setq s (replace-match "%40" t t s)))
9269 (defun org-link-prettify (link)
9270 "Return a human-readable representation of LINK.
9271 The car of LINK must be a raw link the cdr of LINK must be either
9272 a link description or nil."
9273 (let ((desc (or (cadr link) "<no description>")))
9274 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9275 "<" (car link) ">")))
9277 ;;;###autoload
9278 (defun org-insert-link-global ()
9279 "Insert a link like Org-mode does.
9280 This command can be called in any mode to insert a link in Org-mode syntax."
9281 (interactive)
9282 (org-load-modules-maybe)
9283 (org-run-like-in-org-mode 'org-insert-link))
9285 (defun org-insert-all-links (&optional keep)
9286 "Insert all links in `org-stored-links'."
9287 (interactive "P")
9288 (let ((links (copy-sequence org-stored-links)) l)
9289 (while (setq l (if keep (pop links) (pop org-stored-links)))
9290 (insert "- ")
9291 (org-insert-link nil (car l) (cadr l))
9292 (insert "\n"))))
9294 (defun org-link-fontify-links-to-this-file ()
9295 "Fontify links to the current file in `org-stored-links'."
9296 (let ((f (buffer-file-name)) a b)
9297 (setq a (mapcar (lambda(l)
9298 (let ((ll (car l)))
9299 (when (and (string-match "^file:\\(.+\\)::" ll)
9300 (equal f (expand-file-name (match-string 1 ll))))
9301 ll)))
9302 org-stored-links))
9303 (when (featurep 'org-id)
9304 (setq b (mapcar (lambda(l)
9305 (let ((ll (car l)))
9306 (when (and (string-match "^id:\\(.+\\)$" ll)
9307 (equal f (expand-file-name
9308 (or (org-id-find-id-file
9309 (match-string 1 ll)) ""))))
9310 ll)))
9311 org-stored-links)))
9312 (mapcar (lambda(l)
9313 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9314 (delq nil (append a b)))))
9316 (defvar org-link-links-in-this-file nil)
9317 (defun org-insert-link (&optional complete-file link-location default-description)
9318 "Insert a link. At the prompt, enter the link.
9320 Completion can be used to insert any of the link protocol prefixes like
9321 http or ftp in use.
9323 The history can be used to select a link previously stored with
9324 `org-store-link'. When the empty string is entered (i.e. if you just
9325 press RET at the prompt), the link defaults to the most recently
9326 stored link. As SPC triggers completion in the minibuffer, you need to
9327 use M-SPC or C-q SPC to force the insertion of a space character.
9329 You will also be prompted for a description, and if one is given, it will
9330 be displayed in the buffer instead of the link.
9332 If there is already a link at point, this command will allow you to edit link
9333 and description parts.
9335 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9336 be selected using completion. The path to the file will be relative to the
9337 current directory if the file is in the current directory or a subdirectory.
9338 Otherwise, the link will be the absolute path as completed in the minibuffer
9339 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9340 option `org-link-file-path-type'.
9342 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9343 the current directory or below.
9345 With three \\[universal-argument] prefixes, negate the meaning of
9346 `org-keep-stored-link-after-insertion'.
9348 If `org-make-link-description-function' is non-nil, this function will be
9349 called with the link target, and the result will be the default
9350 link description.
9352 If the LINK-LOCATION parameter is non-nil, this value will be
9353 used as the link location instead of reading one interactively.
9355 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9356 be used as the default description."
9357 (interactive "P")
9358 (let* ((wcf (current-window-configuration))
9359 (region (if (org-region-active-p)
9360 (buffer-substring (region-beginning) (region-end))))
9361 (remove (and region (list (region-beginning) (region-end))))
9362 (desc region)
9363 tmphist ; byte-compile incorrectly complains about this
9364 (link link-location)
9365 (abbrevs org-link-abbrev-alist-local)
9366 entry file all-prefixes auto-desc)
9367 (cond
9368 (link-location) ; specified by arg, just use it.
9369 ((org-in-regexp org-bracket-link-regexp 1)
9370 ;; We do have a link at point, and we are going to edit it.
9371 (setq remove (list (match-beginning 0) (match-end 0)))
9372 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9373 (setq link (read-string "Link: "
9374 (org-link-unescape
9375 (org-match-string-no-properties 1)))))
9376 ((or (org-in-regexp org-angle-link-re)
9377 (org-in-regexp org-plain-link-re))
9378 ;; Convert to bracket link
9379 (setq remove (list (match-beginning 0) (match-end 0))
9380 link (read-string "Link: "
9381 (org-remove-angle-brackets (match-string 0)))))
9382 ((member complete-file '((4) (16)))
9383 ;; Completing read for file names.
9384 (setq link (org-file-complete-link complete-file)))
9386 ;; Read link, with completion for stored links.
9387 (org-link-fontify-links-to-this-file)
9388 (org-switch-to-buffer-other-window "*Org Links*")
9389 (with-current-buffer "*Org Links*"
9390 (erase-buffer)
9391 (insert "Insert a link.
9392 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9393 (when org-stored-links
9394 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9395 (insert (mapconcat 'org-link-prettify
9396 (reverse org-stored-links) "\n")))
9397 (goto-char (point-min)))
9398 (let ((cw (selected-window)))
9399 (select-window (get-buffer-window "*Org Links*" 'visible))
9400 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9401 (unless (pos-visible-in-window-p (point-max))
9402 (org-fit-window-to-buffer))
9403 (and (window-live-p cw) (select-window cw)))
9404 ;; Fake a link history, containing the stored links.
9405 (setq tmphist (append (mapcar 'car org-stored-links)
9406 org-insert-link-history))
9407 (setq all-prefixes (append (mapcar 'car abbrevs)
9408 (mapcar 'car org-link-abbrev-alist)
9409 org-link-types))
9410 (unwind-protect
9411 (progn
9412 (setq link
9413 (let ((org-completion-use-ido nil)
9414 (org-completion-use-iswitchb nil))
9415 (org-completing-read
9416 "Link: "
9417 (append
9418 (mapcar (lambda (x) (list (concat x ":")))
9419 all-prefixes)
9420 (mapcar 'car org-stored-links)
9421 (mapcar 'cadr org-stored-links))
9422 nil nil nil
9423 'tmphist
9424 (caar org-stored-links))))
9425 (if (not (string-match "\\S-" link))
9426 (error "No link selected"))
9427 (mapc (lambda(l)
9428 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9429 org-stored-links)
9430 (if (or (member link all-prefixes)
9431 (and (equal ":" (substring link -1))
9432 (member (substring link 0 -1) all-prefixes)
9433 (setq link (substring link 0 -1))))
9434 (setq link (org-link-try-special-completion link))))
9435 (set-window-configuration wcf)
9436 (kill-buffer "*Org Links*"))
9437 (setq entry (assoc link org-stored-links))
9438 (or entry (push link org-insert-link-history))
9439 (setq desc (or desc (nth 1 entry)))))
9441 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9442 (not org-keep-stored-link-after-insertion))
9443 (setq org-stored-links (delq (assoc link org-stored-links)
9444 org-stored-links)))
9446 (if (string-match org-plain-link-re link)
9447 ;; URL-like link, normalize the use of angular brackets.
9448 (setq link (org-remove-angle-brackets link)))
9450 ;; Check if we are linking to the current file with a search option
9451 ;; If yes, simplify the link by using only the search option.
9452 (when (and buffer-file-name
9453 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9454 (let* ((path (match-string 1 link))
9455 (case-fold-search nil)
9456 (search (match-string 2 link)))
9457 (save-match-data
9458 (if (equal (file-truename buffer-file-name) (file-truename path))
9459 ;; We are linking to this same file, with a search option
9460 (setq link search)))))
9462 ;; Check if we can/should use a relative path. If yes, simplify the link
9463 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9464 (let* ((type (match-string 1 link))
9465 (path (match-string 2 link))
9466 (origpath path)
9467 (case-fold-search nil))
9468 (cond
9469 ((or (eq org-link-file-path-type 'absolute)
9470 (equal complete-file '(16)))
9471 (setq path (abbreviate-file-name (expand-file-name path))))
9472 ((eq org-link-file-path-type 'noabbrev)
9473 (setq path (expand-file-name path)))
9474 ((eq org-link-file-path-type 'relative)
9475 (setq path (file-relative-name path)))
9477 (save-match-data
9478 (if (string-match (concat "^" (regexp-quote
9479 (expand-file-name
9480 (file-name-as-directory
9481 default-directory))))
9482 (expand-file-name path))
9483 ;; We are linking a file with relative path name.
9484 (setq path (substring (expand-file-name path)
9485 (match-end 0)))
9486 (setq path (abbreviate-file-name (expand-file-name path)))))))
9487 (setq link (concat type path))
9488 (if (equal desc origpath)
9489 (setq desc path))))
9491 (if org-make-link-description-function
9492 (setq desc (funcall org-make-link-description-function link desc))
9493 (if default-description (setq desc default-description)
9494 (setq desc (or (and auto-desc desc)
9495 (read-string "Description: " desc)))))
9497 (unless (string-match "\\S-" desc) (setq desc nil))
9498 (if remove (apply 'delete-region remove))
9499 (insert (org-make-link-string link desc))))
9501 (defun org-link-try-special-completion (type)
9502 "If there is completion support for link type TYPE, offer it."
9503 (let ((fun (intern (concat "org-" type "-complete-link"))))
9504 (if (functionp fun)
9505 (funcall fun)
9506 (read-string "Link (no completion support): " (concat type ":")))))
9508 (defun org-file-complete-link (&optional arg)
9509 "Create a file link using completion."
9510 (let (file link)
9511 (setq file (read-file-name "File: "))
9512 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9513 (pwd1 (file-name-as-directory (abbreviate-file-name
9514 (expand-file-name ".")))))
9515 (cond
9516 ((equal arg '(16))
9517 (setq link (concat
9518 "file:"
9519 (abbreviate-file-name (expand-file-name file)))))
9520 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9521 (setq link (concat "file:" (match-string 1 file))))
9522 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9523 (expand-file-name file))
9524 (setq link (concat
9525 "file:" (match-string 1 (expand-file-name file)))))
9526 (t (setq link (concat "file:" file)))))
9527 link))
9529 (defun org-completing-read (&rest args)
9530 "Completing-read with SPACE being a normal character."
9531 (let ((enable-recursive-minibuffers t)
9532 (minibuffer-local-completion-map
9533 (copy-keymap minibuffer-local-completion-map)))
9534 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9535 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9536 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9537 (apply 'org-icompleting-read args)))
9539 (defun org-completing-read-no-i (&rest args)
9540 (let (org-completion-use-ido org-completion-use-iswitchb)
9541 (apply 'org-completing-read args)))
9543 (defun org-iswitchb-completing-read (prompt choices &rest args)
9544 "Use iswitch as a completing-read replacement to choose from choices.
9545 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9546 from."
9547 (let* ((iswitchb-use-virtual-buffers nil)
9548 (iswitchb-make-buflist-hook
9549 (lambda ()
9550 (setq iswitchb-temp-buflist choices))))
9551 (iswitchb-read-buffer prompt)))
9553 (defun org-icompleting-read (&rest args)
9554 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9555 (org-without-partial-completion
9556 (if (and org-completion-use-ido
9557 (fboundp 'ido-completing-read)
9558 (boundp 'ido-mode) ido-mode
9559 (listp (second args)))
9560 (let ((ido-enter-matching-directory nil))
9561 (apply 'ido-completing-read (concat (car args))
9562 (if (consp (car (nth 1 args)))
9563 (mapcar 'car (nth 1 args))
9564 (nth 1 args))
9565 (cddr args)))
9566 (if (and org-completion-use-iswitchb
9567 (boundp 'iswitchb-mode) iswitchb-mode
9568 (listp (second args)))
9569 (apply 'org-iswitchb-completing-read (concat (car args))
9570 (if (consp (car (nth 1 args)))
9571 (mapcar 'car (nth 1 args))
9572 (nth 1 args))
9573 (cddr args))
9574 (apply 'completing-read args)))))
9576 (defun org-extract-attributes (s)
9577 "Extract the attributes cookie from a string and set as text property."
9578 (let (a attr (start 0) key value)
9579 (save-match-data
9580 (when (string-match "{{\\([^}]+\\)}}$" s)
9581 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9582 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9583 (setq key (match-string 1 a) value (match-string 2 a)
9584 start (match-end 0)
9585 attr (plist-put attr (intern key) value))))
9586 (org-add-props s nil 'org-attr attr))
9589 (defun org-extract-attributes-from-string (tag)
9590 (let (key value attr)
9591 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9592 (setq key (match-string 1 tag) value (match-string 2 tag)
9593 tag (replace-match "" t t tag)
9594 attr (plist-put attr (intern key) value)))
9595 (cons tag attr)))
9597 (defun org-attributes-to-string (plist)
9598 "Format a property list into an HTML attribute list."
9599 (let ((s "") key value)
9600 (while plist
9601 (setq key (pop plist) value (pop plist))
9602 (and value
9603 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9606 ;;; Opening/following a link
9608 (defvar org-link-search-failed nil)
9610 (defvar org-open-link-functions nil
9611 "Hook for functions finding a plain text link.
9612 These functions must take a single argument, the link content.
9613 They will be called for links that look like [[link text][description]]
9614 when LINK TEXT does not have a protocol like \"http:\" and does not look
9615 like a filename (e.g. \"./blue.png\").
9617 These functions will be called *before* Org attempts to resolve the
9618 link by doing text searches in the current buffer - so if you want a
9619 link \"[[target]]\" to still find \"<<target>>\", your function should
9620 handle this as a special case.
9622 When the function does handle the link, it must return a non-nil value.
9623 If it decides that it is not responsible for this link, it must return
9624 nil to indicate that that Org-mode can continue with other options
9625 like exact and fuzzy text search.")
9627 (defun org-next-link ()
9628 "Move forward to the next link.
9629 If the link is in hidden text, expose it."
9630 (interactive)
9631 (when (and org-link-search-failed (eq this-command last-command))
9632 (goto-char (point-min))
9633 (message "Link search wrapped back to beginning of buffer"))
9634 (setq org-link-search-failed nil)
9635 (let* ((pos (point))
9636 (ct (org-context))
9637 (a (assoc :link ct)))
9638 (if a (goto-char (nth 2 a)))
9639 (if (re-search-forward org-any-link-re nil t)
9640 (progn
9641 (goto-char (match-beginning 0))
9642 (if (outline-invisible-p) (org-show-context)))
9643 (goto-char pos)
9644 (setq org-link-search-failed t)
9645 (error "No further link found"))))
9647 (defun org-previous-link ()
9648 "Move backward to the previous link.
9649 If the link is in hidden text, expose it."
9650 (interactive)
9651 (when (and org-link-search-failed (eq this-command last-command))
9652 (goto-char (point-max))
9653 (message "Link search wrapped back to end of buffer"))
9654 (setq org-link-search-failed nil)
9655 (let* ((pos (point))
9656 (ct (org-context))
9657 (a (assoc :link ct)))
9658 (if a (goto-char (nth 1 a)))
9659 (if (re-search-backward org-any-link-re nil t)
9660 (progn
9661 (goto-char (match-beginning 0))
9662 (if (outline-invisible-p) (org-show-context)))
9663 (goto-char pos)
9664 (setq org-link-search-failed t)
9665 (error "No further link found"))))
9667 (defun org-translate-link (s)
9668 "Translate a link string if a translation function has been defined."
9669 (if (and org-link-translation-function
9670 (fboundp org-link-translation-function)
9671 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9672 (progn
9673 (setq s (funcall org-link-translation-function
9674 (match-string 1 s) (match-string 2 s)))
9675 (concat (car s) ":" (cdr s)))
9678 (defun org-translate-link-from-planner (type path)
9679 "Translate a link from Emacs Planner syntax so that Org can follow it.
9680 This is still an experimental function, your mileage may vary."
9681 (cond
9682 ((member type '("http" "https" "news" "ftp"))
9683 ;; standard Internet links are the same.
9684 nil)
9685 ((and (equal type "irc") (string-match "^//" path))
9686 ;; Planner has two / at the beginning of an irc link, we have 1.
9687 ;; We should have zero, actually....
9688 (setq path (substring path 1)))
9689 ((and (equal type "lisp") (string-match "^/" path))
9690 ;; Planner has a slash, we do not.
9691 (setq type "elisp" path (substring path 1)))
9692 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9693 ;; A typical message link. Planner has the id after the final slash,
9694 ;; we separate it with a hash mark
9695 (setq path (concat (match-string 1 path) "#"
9696 (org-remove-angle-brackets (match-string 2 path)))))
9698 (cons type path))
9700 (defun org-find-file-at-mouse (ev)
9701 "Open file link or URL at mouse."
9702 (interactive "e")
9703 (mouse-set-point ev)
9704 (org-open-at-point 'in-emacs))
9706 (defun org-open-at-mouse (ev)
9707 "Open file link or URL at mouse.
9708 See the docstring of `org-open-file' for details."
9709 (interactive "e")
9710 (mouse-set-point ev)
9711 (if (eq major-mode 'org-agenda-mode)
9712 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9713 (org-open-at-point))
9715 (defvar org-window-config-before-follow-link nil
9716 "The window configuration before following a link.
9717 This is saved in case the need arises to restore it.")
9719 (defvar org-open-link-marker (make-marker)
9720 "Marker pointing to the location where `org-open-at-point; was called.")
9722 ;;;###autoload
9723 (defun org-open-at-point-global ()
9724 "Follow a link like Org-mode does.
9725 This command can be called in any mode to follow a link that has
9726 Org-mode syntax."
9727 (interactive)
9728 (org-run-like-in-org-mode 'org-open-at-point))
9730 ;;;###autoload
9731 (defun org-open-link-from-string (s &optional arg reference-buffer)
9732 "Open a link in the string S, as if it was in Org-mode."
9733 (interactive "sLink: \nP")
9734 (let ((reference-buffer (or reference-buffer (current-buffer))))
9735 (with-temp-buffer
9736 (let ((org-inhibit-startup (not reference-buffer)))
9737 (org-mode)
9738 (insert s)
9739 (goto-char (point-min))
9740 (when reference-buffer
9741 (setq org-link-abbrev-alist-local
9742 (with-current-buffer reference-buffer
9743 org-link-abbrev-alist-local)))
9744 (org-open-at-point arg reference-buffer)))))
9746 (defvar org-open-at-point-functions nil
9747 "Hook that is run when following a link at point.
9749 Functions in this hook must return t if they identify and follow
9750 a link at point. If they don't find anything interesting at point,
9751 they must return nil.")
9753 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9754 (defun org-open-at-point (&optional arg reference-buffer)
9755 "Open link at or after point.
9756 If there is no link at point, this function will search forward up to
9757 the end of the current line.
9758 Normally, files will be opened by an appropriate application. If the
9759 optional prefix argument ARG is non-nil, Emacs will visit the file.
9760 With a double prefix argument, try to open outside of Emacs, in the
9761 application the system uses for this file type."
9762 (interactive "P")
9763 ;; if in a code block, then open the block's results
9764 (unless (call-interactively #'org-babel-open-src-block-result)
9765 (org-load-modules-maybe)
9766 (move-marker org-open-link-marker (point))
9767 (setq org-window-config-before-follow-link (current-window-configuration))
9768 (org-remove-occur-highlights nil nil t)
9769 (cond
9770 ((and (org-at-heading-p)
9771 (not (org-at-timestamp-p t))
9772 (not (org-in-regexp
9773 (concat org-plain-link-re "\\|"
9774 org-bracket-link-regexp "\\|"
9775 org-angle-link-re "\\|"
9776 "[ \t]:[^ \t\n]+:[ \t]*$")))
9777 (not (get-text-property (point) 'org-linked-text)))
9778 (or (org-offer-links-in-entry arg)
9779 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9780 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9781 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9782 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9783 (not (org-in-regexp org-bracket-link-regexp)))
9784 (org-footnote-action))
9786 (let (type path link line search (pos (point)))
9787 (catch 'match
9788 (save-excursion
9789 (skip-chars-forward "^]\n\r")
9790 (when (org-in-regexp org-bracket-link-regexp 1)
9791 (setq link (org-extract-attributes
9792 (org-link-unescape (org-match-string-no-properties 1))))
9793 (while (string-match " *\n *" link)
9794 (setq link (replace-match " " t t link)))
9795 (setq link (org-link-expand-abbrev link))
9796 (cond
9797 ((or (file-name-absolute-p link)
9798 (string-match "^\\.\\.?/" link))
9799 (setq type "file" path link))
9800 ((string-match org-link-re-with-space3 link)
9801 (setq type (match-string 1 link) path (match-string 2 link)))
9802 ((string-match "^help:+\\(.+\\)" link)
9803 (setq type "help" path (match-string 1 link)))
9804 (t (setq type "thisfile" path link)))
9805 (throw 'match t)))
9807 (when (get-text-property (point) 'org-linked-text)
9808 (setq type "thisfile"
9809 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9810 (1+ (point)) (point))
9811 path (buffer-substring
9812 (or (previous-single-property-change pos 'org-linked-text)
9813 (point-min))
9814 (or (next-single-property-change pos 'org-linked-text)
9815 (point-max))))
9816 (throw 'match t))
9818 (save-excursion
9819 (when (or (org-in-regexp org-angle-link-re)
9820 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9821 (save-match-data (not (looking-back "\\[\\[")))))
9822 (setq type (match-string 1)
9823 path (org-link-unescape (match-string 2)))
9824 (throw 'match t)))
9825 (save-excursion
9826 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9827 (setq type "tags"
9828 path (match-string 1))
9829 (while (string-match ":" path)
9830 (setq path (replace-match "+" t t path)))
9831 (throw 'match t)))
9832 (when (org-in-regexp "<\\([^><\n]+\\)>")
9833 (setq type "tree-match"
9834 path (match-string 1))
9835 (throw 'match t)))
9836 (unless path
9837 (error "No link found"))
9839 ;; switch back to reference buffer
9840 ;; needed when if called in a temporary buffer through
9841 ;; org-open-link-from-string
9842 (with-current-buffer (or reference-buffer (current-buffer))
9844 ;; Remove any trailing spaces in path
9845 (if (string-match " +\\'" path)
9846 (setq path (replace-match "" t t path)))
9847 (if (and org-link-translation-function
9848 (fboundp org-link-translation-function))
9849 ;; Check if we need to translate the link
9850 (let ((tmp (funcall org-link-translation-function type path)))
9851 (setq type (car tmp) path (cdr tmp))))
9853 (cond
9855 ((assoc type org-link-protocols)
9856 (funcall (nth 1 (assoc type org-link-protocols)) path))
9858 ((equal type "help")
9859 (let ((f-or-v (intern path)))
9860 (cond ((fboundp f-or-v)
9861 (describe-function f-or-v))
9862 ((boundp f-or-v)
9863 (describe-variable f-or-v))
9864 (t (error "Not a known function or variable")))))
9866 ((equal type "mailto")
9867 (let ((cmd (car org-link-mailto-program))
9868 (args (cdr org-link-mailto-program)) args1
9869 (address path) (subject "") a)
9870 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9871 (setq address (match-string 1 path)
9872 subject (org-link-escape (match-string 2 path))))
9873 (while args
9874 (cond
9875 ((not (stringp (car args))) (push (pop args) args1))
9876 (t (setq a (pop args))
9877 (if (string-match "%a" a)
9878 (setq a (replace-match address t t a)))
9879 (if (string-match "%s" a)
9880 (setq a (replace-match subject t t a)))
9881 (push a args1))))
9882 (apply cmd (nreverse args1))))
9884 ((member type '("http" "https" "ftp" "news"))
9885 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9886 (org-link-escape
9887 path org-link-escape-chars-browser)
9888 path))))
9890 ((string= type "doi")
9891 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9892 (org-link-escape
9893 path org-link-escape-chars-browser)
9894 path))))
9896 ((member type '("message"))
9897 (browse-url (concat type ":" path)))
9899 ((string= type "tags")
9900 (org-tags-view arg path))
9902 ((string= type "tree-match")
9903 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9905 ((string= type "file")
9906 (if (string-match "::\\([0-9]+\\)\\'" path)
9907 (setq line (string-to-number (match-string 1 path))
9908 path (substring path 0 (match-beginning 0)))
9909 (if (string-match "::\\(.+\\)\\'" path)
9910 (setq search (match-string 1 path)
9911 path (substring path 0 (match-beginning 0)))))
9912 (if (string-match "[*?{]" (file-name-nondirectory path))
9913 (dired path)
9914 (org-open-file path arg line search)))
9916 ((string= type "shell")
9917 (let ((buf (generate-new-buffer "*Org Shell Output"))
9918 (cmd path))
9919 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9920 (string-match org-confirm-shell-link-not-regexp cmd))
9921 (not org-confirm-shell-link-function)
9922 (funcall org-confirm-shell-link-function
9923 (format "Execute \"%s\" in shell? "
9924 (org-add-props cmd nil
9925 'face 'org-warning))))
9926 (progn
9927 (message "Executing %s" cmd)
9928 (shell-command cmd buf)
9929 (if (featurep 'midnight)
9930 (setq clean-buffer-list-kill-buffer-names
9931 (cons buf clean-buffer-list-kill-buffer-names))))
9932 (error "Abort"))))
9934 ((string= type "elisp")
9935 (let ((cmd path))
9936 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9937 (string-match org-confirm-elisp-link-not-regexp cmd))
9938 (not org-confirm-elisp-link-function)
9939 (funcall org-confirm-elisp-link-function
9940 (format "Execute \"%s\" as elisp? "
9941 (org-add-props cmd nil
9942 'face 'org-warning))))
9943 (message "%s => %s" cmd
9944 (if (equal (string-to-char cmd) ?\()
9945 (eval (read cmd))
9946 (call-interactively (read cmd))))
9947 (error "Abort"))))
9949 ((and (string= type "thisfile")
9950 (run-hook-with-args-until-success
9951 'org-open-link-functions path)))
9953 ((string= type "thisfile")
9954 (if arg
9955 (switch-to-buffer-other-window
9956 (org-get-buffer-for-internal-link (current-buffer)))
9957 (org-mark-ring-push))
9958 (let ((cmd `(org-link-search
9959 ,path
9960 ,(cond ((equal arg '(4)) ''occur)
9961 ((equal arg '(16)) ''org-occur))
9962 ,pos)))
9963 (condition-case nil (let ((org-link-search-inhibit-query t))
9964 (eval cmd))
9965 (error (progn (widen) (eval cmd))))))
9967 (t (browse-url-at-point)))))))
9968 (move-marker org-open-link-marker nil)
9969 (run-hook-with-args 'org-follow-link-hook)))
9971 (defun org-offer-links-in-entry (&optional nth zero)
9972 "Offer links in the current entry and follow the selected link.
9973 If there is only one link, follow it immediately as well.
9974 If NTH is an integer, immediately pick the NTH link found.
9975 If ZERO is a string, check also this string for a link, and if
9976 there is one, offer it as link number zero."
9977 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9978 "\\(" org-angle-link-re "\\)\\|"
9979 "\\(" org-plain-link-re "\\)"))
9980 (cnt ?0)
9981 (in-emacs (if (integerp nth) nil nth))
9982 have-zero end links link c)
9983 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9984 (push (match-string 0 zero) links)
9985 (setq cnt (1- cnt) have-zero t))
9986 (save-excursion
9987 (org-back-to-heading t)
9988 (setq end (save-excursion (outline-next-heading) (point)))
9989 (while (re-search-forward re end t)
9990 (push (match-string 0) links))
9991 (setq links (org-uniquify (reverse links))))
9993 (cond
9994 ((null links)
9995 (message "No links"))
9996 ((equal (length links) 1)
9997 (setq link (list (car links))))
9998 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9999 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10000 (t ; we have to select a link
10001 (save-excursion
10002 (save-window-excursion
10003 (delete-other-windows)
10004 (with-output-to-temp-buffer "*Select Link*"
10005 (mapc (lambda (l)
10006 (if (not (string-match org-bracket-link-regexp l))
10007 (princ (format "[%c] %s\n" (incf cnt)
10008 (org-remove-angle-brackets l)))
10009 (if (match-end 3)
10010 (princ (format "[%c] %s (%s)\n" (incf cnt)
10011 (match-string 3 l) (match-string 1 l)))
10012 (princ (format "[%c] %s\n" (incf cnt)
10013 (match-string 1 l))))))
10014 links))
10015 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10016 (message "Select link to open, RET to open all:")
10017 (setq c (read-char-exclusive))
10018 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10019 (when (equal c ?q) (error "Abort"))
10020 (if (equal c ?\C-m)
10021 (setq link links)
10022 (setq nth (- c ?0))
10023 (if have-zero (setq nth (1+ nth)))
10024 (unless (and (integerp nth) (>= (length links) nth))
10025 (error "Invalid link selection"))
10026 (setq link (list (nth (1- nth) links))))))
10027 (if link
10028 (let ((buf (current-buffer)))
10029 (dolist (l link)
10030 (org-open-link-from-string l in-emacs buf))
10032 nil)))
10034 ;; Add special file links that specify the way of opening
10036 (org-add-link-type "file+sys" 'org-open-file-with-system)
10037 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10038 (defun org-open-file-with-system (path)
10039 "Open file at PATH using the system way of opening it."
10040 (org-open-file path 'system))
10041 (defun org-open-file-with-emacs (path)
10042 "Open file at PATH in Emacs."
10043 (org-open-file path 'emacs))
10044 (defun org-remove-file-link-modifiers ()
10045 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10046 (goto-char (point-min))
10047 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10048 (org-if-unprotected
10049 (replace-match "file:" t t))))
10050 (eval-after-load "org-exp"
10051 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10052 'org-remove-file-link-modifiers))
10054 ;;;; Time estimates
10056 (defun org-get-effort (&optional pom)
10057 "Get the effort estimate for the current entry."
10058 (org-entry-get pom org-effort-property))
10060 ;;; File search
10062 (defvar org-create-file-search-functions nil
10063 "List of functions to construct the right search string for a file link.
10064 These functions are called in turn with point at the location to
10065 which the link should point.
10067 A function in the hook should first test if it would like to
10068 handle this file type, for example by checking the `major-mode'
10069 or the file extension. If it decides not to handle this file, it
10070 should just return nil to give other functions a chance. If it
10071 does handle the file, it must return the search string to be used
10072 when following the link. The search string will be part of the
10073 file link, given after a double colon, and `org-open-at-point'
10074 will automatically search for it. If special measures must be
10075 taken to make the search successful, another function should be
10076 added to the companion hook `org-execute-file-search-functions',
10077 which see.
10079 A function in this hook may also use `setq' to set the variable
10080 `description' to provide a suggestion for the descriptive text to
10081 be used for this link when it gets inserted into an Org-mode
10082 buffer with \\[org-insert-link].")
10084 (defvar org-execute-file-search-functions nil
10085 "List of functions to execute a file search triggered by a link.
10087 Functions added to this hook must accept a single argument, the
10088 search string that was part of the file link, the part after the
10089 double colon. The function must first check if it would like to
10090 handle this search, for example by checking the `major-mode' or
10091 the file extension. If it decides not to handle this search, it
10092 should just return nil to give other functions a chance. If it
10093 does handle the search, it must return a non-nil value to keep
10094 other functions from trying.
10096 Each function can access the current prefix argument through the
10097 variable `current-prefix-argument'. Note that a single prefix is
10098 used to force opening a link in Emacs, so it may be good to only
10099 use a numeric or double prefix to guide the search function.
10101 In case this is needed, a function in this hook can also restore
10102 the window configuration before `org-open-at-point' was called using:
10104 (set-window-configuration org-window-config-before-follow-link)")
10106 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10107 (defun org-link-search (s &optional type avoid-pos stealth)
10108 "Search for a link search option.
10109 If S is surrounded by forward slashes, it is interpreted as a
10110 regular expression. In org-mode files, this will create an `org-occur'
10111 sparse tree. In ordinary files, `occur' will be used to list matches.
10112 If the current buffer is in `dired-mode', grep will be used to search
10113 in all files. If AVOID-POS is given, ignore matches near that position.
10115 When optional argument STEALTH is non-nil, do not modify
10116 visibility around point, thus ignoring
10117 `org-show-hierarchy-above', `org-show-following-heading' and
10118 `org-show-siblings' variables."
10119 (let ((case-fold-search t)
10120 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10121 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10122 (append '(("") (" ") ("\t") ("\n"))
10123 org-emphasis-alist)
10124 "\\|") "\\)"))
10125 (pos (point))
10126 (pre nil) (post nil)
10127 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10128 (cond
10129 ;; First check if there are any special search functions
10130 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10131 ;; Now try the builtin stuff
10132 ((and (equal (string-to-char s0) ?#)
10133 (> (length s0) 1)
10134 (save-excursion
10135 (goto-char (point-min))
10136 (and
10137 (re-search-forward
10138 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10139 (setq type 'dedicated
10140 pos (match-beginning 0))))
10141 ;; There is an exact target for this
10142 (goto-char pos)
10143 (org-back-to-heading t)))
10144 ((save-excursion
10145 (goto-char (point-min))
10146 (and
10147 (re-search-forward
10148 (concat "<<" (regexp-quote s0) ">>") nil t)
10149 (setq type 'dedicated
10150 pos (match-beginning 0))))
10151 ;; There is an exact target for this
10152 (goto-char pos))
10153 ((save-excursion
10154 (goto-char (point-min))
10155 (and
10156 (re-search-forward
10157 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10158 (setq type 'dedicated pos (match-beginning 0))))
10159 ;; Found an invisible target.
10160 (goto-char pos))
10161 ((save-excursion
10162 (goto-char (point-min))
10163 (and
10164 (re-search-forward
10165 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10166 (setq type 'dedicated pos (match-beginning 0))))
10167 ;; Found an element with a matching #+name affiliated keyword.
10168 (goto-char pos))
10169 ((and (string-match "^(\\(.*\\))$" s0)
10170 (save-excursion
10171 (goto-char (point-min))
10172 (and
10173 (re-search-forward
10174 (concat "[^[]" (regexp-quote
10175 (format org-coderef-label-format
10176 (match-string 1 s0))))
10177 nil t)
10178 (setq type 'dedicated
10179 pos (1+ (match-beginning 0))))))
10180 ;; There is a coderef target for this
10181 (goto-char pos))
10182 ((string-match "^/\\(.*\\)/$" s)
10183 ;; A regular expression
10184 (cond
10185 ((derived-mode-p 'org-mode)
10186 (org-occur (match-string 1 s)))
10187 ;;((eq major-mode 'dired-mode)
10188 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10189 (t (org-do-occur (match-string 1 s)))))
10190 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10191 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10192 (goto-char (point-min))
10193 (cond
10194 ((let (case-fold-search)
10195 (re-search-forward (format org-complex-heading-regexp-format
10196 (regexp-quote s))
10197 nil t))
10198 ;; OK, found a match
10199 (setq type 'dedicated)
10200 (goto-char (match-beginning 0)))
10201 ((and (not org-link-search-inhibit-query)
10202 (eq org-link-search-must-match-exact-headline 'query-to-create)
10203 (y-or-n-p "No match - create this as a new heading? "))
10204 (goto-char (point-max))
10205 (or (bolp) (newline))
10206 (insert "* " s "\n")
10207 (beginning-of-line 0))
10209 (goto-char pos)
10210 (error "No match"))))
10212 ;; A normal search string
10213 (when (equal (string-to-char s) ?*)
10214 ;; Anchor on headlines, post may include tags.
10215 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10216 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10217 s (substring s 1)))
10218 (remove-text-properties
10219 0 (length s)
10220 '(face nil mouse-face nil keymap nil fontified nil) s)
10221 ;; Make a series of regular expressions to find a match
10222 (setq words (org-split-string s "[ \n\r\t]+")
10224 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10225 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10226 "\\)" markers)
10227 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10228 re2a (concat "[ \t\r\n]" re2a_)
10229 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10230 re4 (concat "[^a-zA-Z_]" re4_)
10232 re1 (concat pre re2 post)
10233 re3 (concat pre (if pre re4_ re4) post)
10234 re5 (concat pre ".*" re4)
10235 re2 (concat pre re2)
10236 re2a (concat pre (if pre re2a_ re2a))
10237 re4 (concat pre (if pre re4_ re4))
10238 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10239 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10240 re5 "\\)"
10242 (cond
10243 ((eq type 'org-occur) (org-occur reall))
10244 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10245 (t (goto-char (point-min))
10246 (setq type 'fuzzy)
10247 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10248 (org-search-not-self 1 re1 nil t)
10249 (org-search-not-self 1 re2 nil t)
10250 (org-search-not-self 1 re2a nil t)
10251 (org-search-not-self 1 re3 nil t)
10252 (org-search-not-self 1 re4 nil t)
10253 (org-search-not-self 1 re5 nil t)
10255 (goto-char (match-beginning 1))
10256 (goto-char pos)
10257 (error "No match"))))))
10258 (and (derived-mode-p 'org-mode)
10259 (not stealth)
10260 (org-show-context 'link-search))
10261 type))
10263 (defun org-search-not-self (group &rest args)
10264 "Execute `re-search-forward', but only accept matches that do not
10265 enclose the position of `org-open-link-marker'."
10266 (let ((m org-open-link-marker))
10267 (catch 'exit
10268 (while (apply 're-search-forward args)
10269 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10270 (goto-char (match-end group))
10271 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10272 (> (match-beginning 0) (marker-position m))
10273 (< (match-end 0) (marker-position m)))
10274 (save-match-data
10275 (or (not (org-in-regexp
10276 org-bracket-link-analytic-regexp 1))
10277 (not (match-end 4)) ; no description
10278 (and (<= (match-beginning 4) (point))
10279 (>= (match-end 4) (point))))))
10280 (throw 'exit (point))))))))
10282 (defun org-get-buffer-for-internal-link (buffer)
10283 "Return a buffer to be used for displaying the link target of internal links."
10284 (cond
10285 ((not org-display-internal-link-with-indirect-buffer)
10286 buffer)
10287 ((string-match "(Clone)$" (buffer-name buffer))
10288 (message "Buffer is already a clone, not making another one")
10289 ;; we also do not modify visibility in this case
10290 buffer)
10291 (t ; make a new indirect buffer for displaying the link
10292 (let* ((bn (buffer-name buffer))
10293 (ibn (concat bn "(Clone)"))
10294 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10295 (with-current-buffer ib (org-overview))
10296 ib))))
10298 (defun org-do-occur (regexp &optional cleanup)
10299 "Call the Emacs command `occur'.
10300 If CLEANUP is non-nil, remove the printout of the regular expression
10301 in the *Occur* buffer. This is useful if the regex is long and not useful
10302 to read."
10303 (occur regexp)
10304 (when cleanup
10305 (let ((cwin (selected-window)) win beg end)
10306 (when (setq win (get-buffer-window "*Occur*"))
10307 (select-window win))
10308 (goto-char (point-min))
10309 (when (re-search-forward "match[a-z]+" nil t)
10310 (setq beg (match-end 0))
10311 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10312 (setq end (1- (match-beginning 0)))))
10313 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10314 (goto-char (point-min))
10315 (select-window cwin))))
10317 ;;; The mark ring for links jumps
10319 (defvar org-mark-ring nil
10320 "Mark ring for positions before jumps in Org-mode.")
10321 (defvar org-mark-ring-last-goto nil
10322 "Last position in the mark ring used to go back.")
10323 ;; Fill and close the ring
10324 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10325 (loop for i from 1 to org-mark-ring-length do
10326 (push (make-marker) org-mark-ring))
10327 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10328 org-mark-ring)
10330 (defun org-mark-ring-push (&optional pos buffer)
10331 "Put the current position or POS into the mark ring and rotate it."
10332 (interactive)
10333 (setq pos (or pos (point)))
10334 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10335 (move-marker (car org-mark-ring)
10336 (or pos (point))
10337 (or buffer (current-buffer)))
10338 (message "%s"
10339 (substitute-command-keys
10340 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10342 (defun org-mark-ring-goto (&optional n)
10343 "Jump to the previous position in the mark ring.
10344 With prefix arg N, jump back that many stored positions. When
10345 called several times in succession, walk through the entire ring.
10346 Org-mode commands jumping to a different position in the current file,
10347 or to another Org-mode file, automatically push the old position
10348 onto the ring."
10349 (interactive "p")
10350 (let (p m)
10351 (if (eq last-command this-command)
10352 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10353 (setq p org-mark-ring))
10354 (setq org-mark-ring-last-goto p)
10355 (setq m (car p))
10356 (org-pop-to-buffer-same-window (marker-buffer m))
10357 (goto-char m)
10358 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10360 (defun org-remove-angle-brackets (s)
10361 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10362 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10364 (defun org-add-angle-brackets (s)
10365 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10366 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10368 (defun org-remove-double-quotes (s)
10369 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10370 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10373 ;;; Following specific links
10375 (defun org-follow-timestamp-link ()
10376 (cond
10377 ((org-at-date-range-p t)
10378 (let ((org-agenda-start-on-weekday)
10379 (t1 (match-string 1))
10380 (t2 (match-string 2)))
10381 (setq t1 (time-to-days (org-time-string-to-time t1))
10382 t2 (time-to-days (org-time-string-to-time t2)))
10383 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10384 ((org-at-timestamp-p t)
10385 (org-agenda-list nil (time-to-days (org-time-string-to-time
10386 (substring (match-string 1) 0 10)))
10388 (t (error "This should not happen"))))
10391 ;;; Following file links
10392 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10393 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10394 (declare-function mailcap-mime-info
10395 "mailcap" (string &optional request no-decode))
10396 (defvar org-wait nil)
10397 (defun org-open-file (path &optional in-emacs line search)
10398 "Open the file at PATH.
10399 First, this expands any special file name abbreviations. Then the
10400 configuration variable `org-file-apps' is checked if it contains an
10401 entry for this file type, and if yes, the corresponding command is launched.
10403 If no application is found, Emacs simply visits the file.
10405 With optional prefix argument IN-EMACS, Emacs will visit the file.
10406 With a double \\[universal-argument] \\[universal-argument] \
10407 prefix arg, Org tries to avoid opening in Emacs
10408 and to use an external application to visit the file.
10410 Optional LINE specifies a line to go to, optional SEARCH a string
10411 to search for. If LINE or SEARCH is given, the file will be
10412 opened in Emacs, unless an entry from org-file-apps that makes
10413 use of groups in a regexp matches.
10415 If you want to change the way frames are used when following a
10416 link, please customize `org-link-frame-setup'.
10418 If the file does not exist, an error is thrown."
10419 (let* ((file (if (equal path "")
10420 buffer-file-name
10421 (substitute-in-file-name (expand-file-name path))))
10422 (file-apps (append org-file-apps (org-default-apps)))
10423 (apps (org-remove-if
10424 'org-file-apps-entry-match-against-dlink-p file-apps))
10425 (apps-dlink (org-remove-if-not
10426 'org-file-apps-entry-match-against-dlink-p file-apps))
10427 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10428 (dirp (if remp nil (file-directory-p file)))
10429 (file (if (and dirp org-open-directory-means-index-dot-org)
10430 (concat (file-name-as-directory file) "index.org")
10431 file))
10432 (a-m-a-p (assq 'auto-mode apps))
10433 (dfile (downcase file))
10434 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10435 (link (cond ((and (eq line nil)
10436 (eq search nil))
10437 file)
10438 (line
10439 (concat file "::" (number-to-string line)))
10440 (search
10441 (concat file "::" search))))
10442 (dlink (downcase link))
10443 (old-buffer (current-buffer))
10444 (old-pos (point))
10445 (old-mode major-mode)
10446 ext cmd link-match-data)
10447 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10448 (setq ext (match-string 1 dfile))
10449 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10450 (setq ext (match-string 1 dfile))))
10451 (cond
10452 ((member in-emacs '((16) system))
10453 (setq cmd (cdr (assoc 'system apps))))
10454 (in-emacs (setq cmd 'emacs))
10456 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10457 (and dirp (cdr (assoc 'directory apps)))
10458 ; first, try matching against apps-dlink
10459 ; if we get a match here, store the match data for later
10460 (let ((match (assoc-default dlink apps-dlink
10461 'string-match)))
10462 (if match
10463 (progn (setq link-match-data (match-data))
10464 match)
10465 (progn (setq in-emacs (or in-emacs line search))
10466 nil))) ; if we have no match in apps-dlink,
10467 ; always open the file in emacs if line or search
10468 ; is given (for backwards compatibility)
10469 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10470 'string-match)
10471 (cdr (assoc ext apps))
10472 (cdr (assoc t apps))))))
10473 (when (eq cmd 'system)
10474 (setq cmd (cdr (assoc 'system apps))))
10475 (when (eq cmd 'default)
10476 (setq cmd (cdr (assoc t apps))))
10477 (when (eq cmd 'mailcap)
10478 (require 'mailcap)
10479 (mailcap-parse-mailcaps)
10480 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10481 (command (mailcap-mime-info mime-type)))
10482 (if (stringp command)
10483 (setq cmd command)
10484 (setq cmd 'emacs))))
10485 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10486 (not (file-exists-p file))
10487 (not org-open-non-existing-files))
10488 (error "No such file: %s" file))
10489 (cond
10490 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10491 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10492 (while (string-match "['\"]%s['\"]" cmd)
10493 (setq cmd (replace-match "%s" t t cmd)))
10494 (while (string-match "%s" cmd)
10495 (setq cmd (replace-match
10496 (save-match-data
10497 (shell-quote-argument
10498 (convert-standard-filename file)))
10499 t t cmd)))
10501 ;; Replace "%1", "%2" etc. in command with group matches from regex
10502 (save-match-data
10503 (let ((match-index 1)
10504 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10505 (set-match-data link-match-data)
10506 (while (<= match-index number-of-groups)
10507 (let ((regex (concat "%" (number-to-string match-index)))
10508 (replace-with (match-string match-index dlink)))
10509 (while (string-match regex cmd)
10510 (setq cmd (replace-match replace-with t t cmd))))
10511 (setq match-index (+ match-index 1)))))
10513 (save-window-excursion
10514 (start-process-shell-command cmd nil cmd)
10515 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10517 ((or (stringp cmd)
10518 (eq cmd 'emacs))
10519 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10520 (widen)
10521 (if line (org-goto-line line)
10522 (if search (org-link-search search))))
10523 ((consp cmd)
10524 (let ((file (convert-standard-filename file)))
10525 (save-match-data
10526 (set-match-data link-match-data)
10527 (eval cmd))))
10528 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10529 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10530 (or (not (equal old-buffer (current-buffer)))
10531 (not (equal old-pos (point))))
10532 (org-mark-ring-push old-pos old-buffer))))
10534 (defun org-file-apps-entry-match-against-dlink-p (entry)
10535 "This function returns non-nil if `entry' uses a regular
10536 expression which should be matched against the whole link by
10537 org-open-file.
10539 It assumes that is the case when the entry uses a regular
10540 expression which has at least one grouping construct and the
10541 action is either a lisp form or a command string containing
10542 '%1', i.e. using at least one subexpression match as a
10543 parameter."
10544 (let ((selector (car entry))
10545 (action (cdr entry)))
10546 (if (stringp selector)
10547 (and (> (regexp-opt-depth selector) 0)
10548 (or (and (stringp action)
10549 (string-match "%[0-9]" action))
10550 (consp action)))
10551 nil)))
10553 (defun org-default-apps ()
10554 "Return the default applications for this operating system."
10555 (cond
10556 ((eq system-type 'darwin)
10557 org-file-apps-defaults-macosx)
10558 ((eq system-type 'windows-nt)
10559 org-file-apps-defaults-windowsnt)
10560 (t org-file-apps-defaults-gnu)))
10562 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10563 "Convert extensions to regular expressions in the cars of LIST.
10564 Also, weed out any non-string entries, because the return value is used
10565 only for regexp matching.
10566 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10567 point to the symbol `emacs', indicating that the file should
10568 be opened in Emacs."
10569 (append
10570 (delq nil
10571 (mapcar (lambda (x)
10572 (if (not (stringp (car x)))
10574 (if (string-match "\\W" (car x))
10576 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10577 list))
10578 (if add-auto-mode
10579 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10581 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10582 (defun org-file-remote-p (file)
10583 "Test whether FILE specifies a location on a remote system.
10584 Return non-nil if the location is indeed remote.
10586 For example, the filename \"/user@host:/foo\" specifies a location
10587 on the system \"/user@host:\"."
10588 (cond ((fboundp 'file-remote-p)
10589 (file-remote-p file))
10590 ((fboundp 'tramp-handle-file-remote-p)
10591 (tramp-handle-file-remote-p file))
10592 ((and (boundp 'ange-ftp-name-format)
10593 (string-match (car ange-ftp-name-format) file))
10594 t)))
10597 ;;;; Refiling
10599 (defun org-get-org-file ()
10600 "Read a filename, with default directory `org-directory'."
10601 (let ((default (or org-default-notes-file remember-data-file)))
10602 (read-file-name (format "File name [%s]: " default)
10603 (file-name-as-directory org-directory)
10604 default)))
10606 (defun org-notes-order-reversed-p ()
10607 "Check if the current file should receive notes in reversed order."
10608 (cond
10609 ((not org-reverse-note-order) nil)
10610 ((eq t org-reverse-note-order) t)
10611 ((not (listp org-reverse-note-order)) nil)
10612 (t (catch 'exit
10613 (let ((all org-reverse-note-order)
10614 entry)
10615 (while (setq entry (pop all))
10616 (if (string-match (car entry) buffer-file-name)
10617 (throw 'exit (cdr entry))))
10618 nil)))))
10620 (defvar org-refile-target-table nil
10621 "The list of refile targets, created by `org-refile'.")
10623 (defvar org-agenda-new-buffers nil
10624 "Buffers created to visit agenda files.")
10626 (defvar org-refile-cache nil
10627 "Cache for refile targets.")
10629 (defvar org-refile-markers nil
10630 "All the markers used for caching refile locations.")
10632 (defun org-refile-marker (pos)
10633 "Get a new refile marker, but only if caching is in use."
10634 (if (not org-refile-use-cache)
10636 (let ((m (make-marker)))
10637 (move-marker m pos)
10638 (push m org-refile-markers)
10639 m)))
10641 (defun org-refile-cache-clear ()
10642 "Clear the refile cache and disable all the markers."
10643 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10644 (setq org-refile-markers nil)
10645 (setq org-refile-cache nil)
10646 (message "Refile cache has been cleared"))
10648 (defun org-refile-cache-check-set (set)
10649 "Check if all the markers in the cache still have live buffers."
10650 (let (marker)
10651 (catch 'exit
10652 (while (and set (setq marker (nth 3 (pop set))))
10653 ;; if org-refile-use-outline-path is 'file, marker may be nil
10654 (when (and marker (null (marker-buffer marker)))
10655 (message "not found") (sit-for 3)
10656 (throw 'exit nil)))
10657 t)))
10659 (defun org-refile-cache-put (set &rest identifiers)
10660 "Push the refile targets SET into the cache, under IDENTIFIERS."
10661 (let* ((key (sha1 (prin1-to-string identifiers)))
10662 (entry (assoc key org-refile-cache)))
10663 (if entry
10664 (setcdr entry set)
10665 (push (cons key set) org-refile-cache))))
10667 (defun org-refile-cache-get (&rest identifiers)
10668 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10669 (cond
10670 ((not org-refile-cache) nil)
10671 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10673 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10674 org-refile-cache))))
10675 (and set (org-refile-cache-check-set set) set)))))
10677 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10678 "Produce a table with refile targets."
10679 (let ((case-fold-search nil)
10680 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10681 (entries (or org-refile-targets '((nil . (:level . 1)))))
10682 targets tgs txt re files f desc descre fast-path-p level pos0)
10683 (message "Getting targets...")
10684 (with-current-buffer (or default-buffer (current-buffer))
10685 (while (setq entry (pop entries))
10686 (setq files (car entry) desc (cdr entry))
10687 (setq fast-path-p nil)
10688 (cond
10689 ((null files) (setq files (list (current-buffer))))
10690 ((eq files 'org-agenda-files)
10691 (setq files (org-agenda-files 'unrestricted)))
10692 ((and (symbolp files) (fboundp files))
10693 (setq files (funcall files)))
10694 ((and (symbolp files) (boundp files))
10695 (setq files (symbol-value files))))
10696 (if (stringp files) (setq files (list files)))
10697 (cond
10698 ((eq (car desc) :tag)
10699 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10700 ((eq (car desc) :todo)
10701 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10702 ((eq (car desc) :regexp)
10703 (setq descre (cdr desc)))
10704 ((eq (car desc) :level)
10705 (setq descre (concat "^\\*\\{" (number-to-string
10706 (if org-odd-levels-only
10707 (1- (* 2 (cdr desc)))
10708 (cdr desc)))
10709 "\\}[ \t]")))
10710 ((eq (car desc) :maxlevel)
10711 (setq fast-path-p t)
10712 (setq descre (concat "^\\*\\{1," (number-to-string
10713 (if org-odd-levels-only
10714 (1- (* 2 (cdr desc)))
10715 (cdr desc)))
10716 "\\}[ \t]")))
10717 (t (error "Bad refiling target description %s" desc)))
10718 (while (setq f (pop files))
10719 (with-current-buffer
10720 (if (bufferp f) f (org-get-agenda-file-buffer f))
10722 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10723 (progn
10724 (if (bufferp f) (setq f (buffer-file-name
10725 (buffer-base-buffer f))))
10726 (setq f (and f (expand-file-name f)))
10727 (if (eq org-refile-use-outline-path 'file)
10728 (push (list (file-name-nondirectory f) f nil nil) tgs))
10729 (save-excursion
10730 (save-restriction
10731 (widen)
10732 (goto-char (point-min))
10733 (while (re-search-forward descre nil t)
10734 (goto-char (setq pos0 (point-at-bol)))
10735 (catch 'next
10736 (when org-refile-target-verify-function
10737 (save-match-data
10738 (or (funcall org-refile-target-verify-function)
10739 (throw 'next t))))
10740 (when (and (looking-at org-complex-heading-regexp)
10741 (not (member (match-string 4) excluded-entries))
10742 (match-string 4))
10743 (setq level (org-reduced-level
10744 (- (match-end 1) (match-beginning 1)))
10745 txt (org-link-display-format (match-string 4))
10746 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10747 re (format org-complex-heading-regexp-format
10748 (regexp-quote (match-string 4))))
10749 (when org-refile-use-outline-path
10750 (setq txt (mapconcat
10751 'org-protect-slash
10752 (append
10753 (if (eq org-refile-use-outline-path
10754 'file)
10755 (list (file-name-nondirectory
10756 (buffer-file-name
10757 (buffer-base-buffer))))
10758 (if (eq org-refile-use-outline-path
10759 'full-file-path)
10760 (list (buffer-file-name
10761 (buffer-base-buffer)))))
10762 (org-get-outline-path fast-path-p
10763 level txt)
10764 (list txt))
10765 "/")))
10766 (push (list txt f re (org-refile-marker (point)))
10767 tgs)))
10768 (when (= (point) pos0)
10769 ;; verification function has not moved point
10770 (goto-char (point-at-eol))))))))
10771 (when org-refile-use-cache
10772 (org-refile-cache-put tgs (buffer-file-name) descre))
10773 (setq targets (append tgs targets))
10774 ))))
10775 (message "Getting targets...done")
10776 (nreverse targets)))
10778 (defun org-protect-slash (s)
10779 (while (string-match "/" s)
10780 (setq s (replace-match "\\" t t s)))
10783 (defvar org-olpa (make-vector 20 nil))
10785 (defun org-get-outline-path (&optional fastp level heading)
10786 "Return the outline path to the current entry, as a list.
10788 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10789 routine which makes outline path derivations for an entire file,
10790 avoiding backtracing. Refile target collection makes use of that."
10791 (if fastp
10792 (progn
10793 (if (> level 19)
10794 (error "Outline path failure, more than 19 levels"))
10795 (loop for i from level upto 19 do
10796 (aset org-olpa i nil))
10797 (prog1
10798 (delq nil (append org-olpa nil))
10799 (aset org-olpa level heading)))
10800 (let (rtn case-fold-search)
10801 (save-excursion
10802 (save-restriction
10803 (widen)
10804 (while (org-up-heading-safe)
10805 (when (looking-at org-complex-heading-regexp)
10806 (push (org-match-string-no-properties 4) rtn)))
10807 rtn)))))
10809 (defun org-format-outline-path (path &optional width prefix)
10810 "Format the outline path PATH for display.
10811 Width is the maximum number of characters that is available.
10812 Prefix is a prefix to be included in the returned string,
10813 such as the file name."
10814 (setq width (or width 79))
10815 (if prefix (setq width (- width (length prefix))))
10816 (if (not path)
10817 (or prefix "")
10818 (let* ((nsteps (length path))
10819 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10820 (maxwidth (if (<= total-width width)
10821 10000 ;; everything fits
10822 ;; we need to shorten the level headings
10823 (/ (- width nsteps) nsteps)))
10824 (org-odd-levels-only nil)
10825 (n 0)
10826 (total (1+ (length prefix))))
10827 (setq maxwidth (max maxwidth 10))
10828 (concat prefix
10829 (mapconcat
10830 (lambda (h)
10831 (setq n (1+ n))
10832 (if (and (= n nsteps) (< maxwidth 10000))
10833 (setq maxwidth (- total-width total)))
10834 (if (< (length h) maxwidth)
10835 (progn (setq total (+ total (length h) 1)) h)
10836 (setq h (substring h 0 (- maxwidth 2))
10837 total (+ total maxwidth 1))
10838 (if (string-match "[ \t]+\\'" h)
10839 (setq h (substring h 0 (match-beginning 0))))
10840 (setq h (concat h "..")))
10841 (org-add-props h nil 'face
10842 (nth (% (1- n) org-n-level-faces)
10843 org-level-faces))
10845 path "/")))))
10847 (defun org-display-outline-path (&optional file current)
10848 "Display the current outline path in the echo area."
10849 (interactive "P")
10850 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10851 (case-fold-search nil)
10852 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10853 (if current (setq path (append path
10854 (save-excursion
10855 (org-back-to-heading t)
10856 (if (looking-at org-complex-heading-regexp)
10857 (list (match-string 4)))))))
10858 (message "%s"
10859 (org-format-outline-path
10860 path
10861 (1- (frame-width))
10862 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10864 (defvar org-refile-history nil
10865 "History for refiling operations.")
10867 (defvar org-after-refile-insert-hook nil
10868 "Hook run after `org-refile' has inserted its stuff at the new location.
10869 Note that this is still *before* the stuff will be removed from
10870 the *old* location.")
10872 (defvar org-capture-last-stored-marker)
10873 (defun org-refile (&optional goto default-buffer rfloc)
10874 "Move the entry or entries at point to another heading.
10875 The list of target headings is compiled using the information in
10876 `org-refile-targets', which see.
10878 At the target location, the entry is filed as a subitem of the target
10879 heading. Depending on `org-reverse-note-order', the new subitem will
10880 either be the first or the last subitem.
10882 If there is an active region, all entries in that region will be moved.
10883 However, the region must fulfill the requirement that the first heading
10884 is the first one sets the top-level of the moved text - at most siblings
10885 below it are allowed.
10887 With prefix arg GOTO, the command will only visit the target location
10888 and not actually move anything.
10890 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10891 go to the location where the last refiling operation has put the subtree.
10892 With a prefix argument of `2', refile to the running clock.
10894 RFLOC can be a refile location obtained in a different way.
10896 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10898 If you are using target caching (see `org-refile-use-cache'),
10899 you have to clear the target cache in order to find new targets.
10900 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10901 prefix argument (`C-u C-u C-u C-c C-w')."
10903 (interactive "P")
10904 (if (member goto '(0 (64)))
10905 (org-refile-cache-clear)
10906 (let* ((cbuf (current-buffer))
10907 (regionp (org-region-active-p))
10908 (region-start (and regionp (region-beginning)))
10909 (region-end (and regionp (region-end)))
10910 (region-length (and regionp (- region-end region-start)))
10911 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10912 pos it nbuf file re level reversed)
10913 (setq last-command nil)
10914 (when regionp
10915 (goto-char region-start)
10916 (or (bolp) (goto-char (point-at-bol)))
10917 (setq region-start (point))
10918 (unless (or (org-kill-is-subtree-p
10919 (buffer-substring region-start region-end))
10920 (prog1 org-refile-active-region-within-subtree
10921 (org-toggle-heading)))
10922 (error "The region is not a (sequence of) subtree(s)")))
10923 (if (equal goto '(16))
10924 (org-refile-goto-last-stored)
10925 (when (or
10926 (and (equal goto 2)
10927 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10928 (prog1
10929 (setq it (list (or org-clock-heading "running clock")
10930 (buffer-file-name
10931 (marker-buffer org-clock-hd-marker))
10933 (marker-position org-clock-hd-marker)))
10934 (setq goto nil)))
10935 (setq it (or rfloc
10936 (let (heading-text)
10937 (save-excursion
10938 (unless goto
10939 (org-back-to-heading t)
10940 (setq heading-text
10941 (nth 4 (org-heading-components))))
10942 (org-refile-get-location
10943 (cond (goto "Goto")
10944 (regionp "Refile region to")
10945 (t (concat "Refile subtree \""
10946 heading-text "\" to")))
10947 default-buffer
10948 (and (not (equal '(4) goto))
10949 org-refile-allow-creating-parent-nodes)
10950 goto))))))
10951 (setq file (nth 1 it)
10952 re (nth 2 it)
10953 pos (nth 3 it))
10954 (if (and (not goto)
10956 (equal (buffer-file-name) file)
10957 (if regionp
10958 (and (>= pos region-start)
10959 (<= pos region-end))
10960 (and (>= pos (point))
10961 (< pos (save-excursion
10962 (org-end-of-subtree t t))))))
10963 (error "Cannot refile to position inside the tree or region"))
10965 (setq nbuf (or (find-buffer-visiting file)
10966 (find-file-noselect file)))
10967 (if goto
10968 (progn
10969 (org-pop-to-buffer-same-window nbuf)
10970 (goto-char pos)
10971 (org-show-context 'org-goto))
10972 (if regionp
10973 (progn
10974 (org-kill-new (buffer-substring region-start region-end))
10975 (org-save-markers-in-region region-start region-end))
10976 (org-copy-subtree 1 nil t))
10977 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10978 (find-file-noselect file)))
10979 (setq reversed (org-notes-order-reversed-p))
10980 (save-excursion
10981 (save-restriction
10982 (widen)
10983 (if pos
10984 (progn
10985 (goto-char pos)
10986 (looking-at org-outline-regexp)
10987 (setq level (org-get-valid-level (funcall outline-level) 1))
10988 (goto-char
10989 (if reversed
10990 (or (outline-next-heading) (point-max))
10991 (or (save-excursion (org-get-next-sibling))
10992 (org-end-of-subtree t t)
10993 (point-max)))))
10994 (setq level 1)
10995 (if (not reversed)
10996 (goto-char (point-max))
10997 (goto-char (point-min))
10998 (or (outline-next-heading) (goto-char (point-max)))))
10999 (if (not (bolp)) (newline))
11000 (org-paste-subtree level)
11001 (when org-log-refile
11002 (org-add-log-setup 'refile nil nil 'findpos
11003 org-log-refile)
11004 (unless (eq org-log-refile 'note)
11005 (save-excursion (org-add-log-note))))
11006 (and org-auto-align-tags
11007 (let ((org-loop-over-headlines-in-active-region nil))
11008 (org-set-tags nil t)))
11009 (bookmark-set "org-refile-last-stored")
11010 ;; If we are refiling for capture, make sure that the
11011 ;; last-capture pointers point here
11012 (when (org-bound-and-true-p org-refile-for-capture)
11013 (bookmark-set "org-capture-last-stored-marker")
11014 (move-marker org-capture-last-stored-marker (point)))
11015 (if (fboundp 'deactivate-mark) (deactivate-mark))
11016 (run-hooks 'org-after-refile-insert-hook))))
11017 (if regionp
11018 (delete-region (point) (+ (point) region-length))
11019 (org-cut-subtree))
11020 (when (featurep 'org-inlinetask)
11021 (org-inlinetask-remove-END-maybe))
11022 (setq org-markers-to-move nil)
11023 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11025 (defun org-refile-goto-last-stored ()
11026 "Go to the location where the last refile was stored."
11027 (interactive)
11028 (bookmark-jump "org-refile-last-stored")
11029 (message "This is the location of the last refile"))
11031 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11032 no-exclude)
11033 "Prompt the user for a refile location, using PROMPT.
11034 PROMPT should not be suffixed with a colon and a space, because
11035 this function appends the default value from
11036 `org-refile-history' automatically, if that is not empty.
11037 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11038 this is used for the GOTO interface."
11039 (let ((org-refile-targets org-refile-targets)
11040 (org-refile-use-outline-path org-refile-use-outline-path)
11041 excluded-entries)
11042 (when (and (derived-mode-p 'org-mode)
11043 (not org-refile-use-cache)
11044 (not no-exclude))
11045 (org-map-tree
11046 (lambda()
11047 (setq excluded-entries
11048 (append excluded-entries (list (org-get-heading t t)))))))
11049 (setq org-refile-target-table
11050 (org-refile-get-targets default-buffer excluded-entries)))
11051 (unless org-refile-target-table
11052 (error "No refile targets"))
11053 (let* ((prompt (concat prompt
11054 (and (car org-refile-history)
11055 (concat " (default " (car org-refile-history) ")"))
11056 ": "))
11057 (cbuf (current-buffer))
11058 (partial-completion-mode nil)
11059 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11060 (cfunc (if (and org-refile-use-outline-path
11061 org-outline-path-complete-in-steps)
11062 'org-olpath-completing-read
11063 'org-icompleting-read))
11064 (extra (if org-refile-use-outline-path "/" ""))
11065 (filename (and cfn (expand-file-name cfn)))
11066 (tbl (mapcar
11067 (lambda (x)
11068 (if (and (not (member org-refile-use-outline-path
11069 '(file full-file-path)))
11070 (not (equal filename (nth 1 x))))
11071 (cons (concat (car x) extra " ("
11072 (file-name-nondirectory (nth 1 x)) ")")
11073 (cdr x))
11074 (cons (concat (car x) extra) (cdr x))))
11075 org-refile-target-table))
11076 (completion-ignore-case t)
11077 pa answ parent-target child parent old-hist)
11078 (setq old-hist org-refile-history)
11079 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11080 nil 'org-refile-history (car org-refile-history)))
11081 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11082 (org-refile-check-position pa)
11083 (if pa
11084 (progn
11085 (when (or (not org-refile-history)
11086 (not (eq old-hist org-refile-history))
11087 (not (equal (car pa) (car org-refile-history))))
11088 (setq org-refile-history
11089 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11090 org-refile-history
11091 (cdr org-refile-history))))
11092 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11093 (pop org-refile-history)))
11095 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11096 (progn
11097 (setq parent (match-string 1 answ)
11098 child (match-string 2 answ))
11099 (setq parent-target (or (assoc parent tbl)
11100 (assoc (concat parent "/") tbl)))
11101 (when (and parent-target
11102 (or (eq new-nodes t)
11103 (and (eq new-nodes 'confirm)
11104 (y-or-n-p (format "Create new node \"%s\"? "
11105 child)))))
11106 (org-refile-new-child parent-target child)))
11107 (error "Invalid target location")))))
11109 (declare-function org-string-nw-p "org-macs.el" (s))
11110 (defun org-refile-check-position (refile-pointer)
11111 "Check if the refile pointer matches the readline to which it points."
11112 (let* ((file (nth 1 refile-pointer))
11113 (re (nth 2 refile-pointer))
11114 (pos (nth 3 refile-pointer))
11115 buffer)
11116 (when (org-string-nw-p re)
11117 (setq buffer (if (markerp pos)
11118 (marker-buffer pos)
11119 (or (find-buffer-visiting file)
11120 (find-file-noselect file))))
11121 (with-current-buffer buffer
11122 (save-excursion
11123 (save-restriction
11124 (widen)
11125 (goto-char pos)
11126 (beginning-of-line 1)
11127 (unless (org-looking-at-p re)
11128 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11130 (defun org-refile-new-child (parent-target child)
11131 "Use refile target PARENT-TARGET to add new CHILD below it."
11132 (unless parent-target
11133 (error "Cannot find parent for new node"))
11134 (let ((file (nth 1 parent-target))
11135 (pos (nth 3 parent-target))
11136 level)
11137 (with-current-buffer (or (find-buffer-visiting file)
11138 (find-file-noselect file))
11139 (save-excursion
11140 (save-restriction
11141 (widen)
11142 (if pos
11143 (goto-char pos)
11144 (goto-char (point-max))
11145 (if (not (bolp)) (newline)))
11146 (when (looking-at org-outline-regexp)
11147 (setq level (funcall outline-level))
11148 (org-end-of-subtree t t))
11149 (org-back-over-empty-lines)
11150 (insert "\n" (make-string
11151 (if pos (org-get-valid-level level 1) 1) ?*)
11152 " " child "\n")
11153 (beginning-of-line 0)
11154 (list (concat (car parent-target) "/" child) file "" (point)))))))
11156 (defun org-olpath-completing-read (prompt collection &rest args)
11157 "Read an outline path like a file name."
11158 (let ((thetable collection)
11159 (org-completion-use-ido nil) ; does not work with ido.
11160 (org-completion-use-iswitchb nil)) ; or iswitchb
11161 (apply
11162 'org-icompleting-read prompt
11163 (lambda (string predicate &optional flag)
11164 (let (rtn r f (l (length string)))
11165 (cond
11166 ((eq flag nil)
11167 ;; try completion
11168 (try-completion string thetable))
11169 ((eq flag t)
11170 ;; all-completions
11171 (setq rtn (all-completions string thetable predicate))
11172 (mapcar
11173 (lambda (x)
11174 (setq r (substring x l))
11175 (if (string-match " ([^)]*)$" x)
11176 (setq f (match-string 0 x))
11177 (setq f ""))
11178 (if (string-match "/" r)
11179 (concat string (substring r 0 (match-end 0)) f)
11181 rtn))
11182 ((eq flag 'lambda)
11183 ;; exact match?
11184 (assoc string thetable)))))
11185 args)))
11187 ;;;; Dynamic blocks
11189 (defun org-find-dblock (name)
11190 "Find the first dynamic block with name NAME in the buffer.
11191 If not found, stay at current position and return nil."
11192 (let ((case-fold-search t) pos)
11193 (save-excursion
11194 (goto-char (point-min))
11195 (setq pos (and (re-search-forward
11196 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11197 (match-beginning 0))))
11198 (if pos (goto-char pos))
11199 pos))
11201 (defconst org-dblock-start-re
11202 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11203 "Matches the start line of a dynamic block, with parameters.")
11205 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11206 "Matches the end of a dynamic block.")
11208 (defun org-create-dblock (plist)
11209 "Create a dynamic block section, with parameters taken from PLIST.
11210 PLIST must contain a :name entry which is used as name of the block."
11211 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11212 (end-of-line 1)
11213 (newline))
11214 (let ((col (current-column))
11215 (name (plist-get plist :name)))
11216 (insert "#+BEGIN: " name)
11217 (while plist
11218 (if (eq (car plist) :name)
11219 (setq plist (cddr plist))
11220 (insert " " (prin1-to-string (pop plist)))))
11221 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11222 (beginning-of-line -2)))
11224 (defun org-prepare-dblock ()
11225 "Prepare dynamic block for refresh.
11226 This empties the block, puts the cursor at the insert position and returns
11227 the property list including an extra property :name with the block name."
11228 (unless (looking-at org-dblock-start-re)
11229 (error "Not at a dynamic block"))
11230 (let* ((begdel (1+ (match-end 0)))
11231 (name (org-no-properties (match-string 1)))
11232 (params (append (list :name name)
11233 (read (concat "(" (match-string 3) ")")))))
11234 (save-excursion
11235 (beginning-of-line 1)
11236 (skip-chars-forward " \t")
11237 (setq params (plist-put params :indentation-column (current-column))))
11238 (unless (re-search-forward org-dblock-end-re nil t)
11239 (error "Dynamic block not terminated"))
11240 (setq params
11241 (append params
11242 (list :content (buffer-substring
11243 begdel (match-beginning 0)))))
11244 (delete-region begdel (match-beginning 0))
11245 (goto-char begdel)
11246 (open-line 1)
11247 params))
11249 (defun org-map-dblocks (&optional command)
11250 "Apply COMMAND to all dynamic blocks in the current buffer.
11251 If COMMAND is not given, use `org-update-dblock'."
11252 (let ((cmd (or command 'org-update-dblock)))
11253 (save-excursion
11254 (goto-char (point-min))
11255 (while (re-search-forward org-dblock-start-re nil t)
11256 (goto-char (match-beginning 0))
11257 (save-excursion
11258 (condition-case nil
11259 (funcall cmd)
11260 (error (message "Error during update of dynamic block"))))
11261 (unless (re-search-forward org-dblock-end-re nil t)
11262 (error "Dynamic block not terminated"))))))
11264 (defun org-dblock-update (&optional arg)
11265 "User command for updating dynamic blocks.
11266 Update the dynamic block at point. With prefix ARG, update all dynamic
11267 blocks in the buffer."
11268 (interactive "P")
11269 (if arg
11270 (org-update-all-dblocks)
11271 (or (looking-at org-dblock-start-re)
11272 (org-beginning-of-dblock))
11273 (org-update-dblock)))
11275 (defun org-update-dblock ()
11276 "Update the dynamic block at point.
11277 This means to empty the block, parse for parameters and then call
11278 the correct writing function."
11279 (interactive)
11280 (save-window-excursion
11281 (let* ((pos (point))
11282 (line (org-current-line))
11283 (params (org-prepare-dblock))
11284 (name (plist-get params :name))
11285 (indent (plist-get params :indentation-column))
11286 (cmd (intern (concat "org-dblock-write:" name))))
11287 (message "Updating dynamic block `%s' at line %d..." name line)
11288 (funcall cmd params)
11289 (message "Updating dynamic block `%s' at line %d...done" name line)
11290 (goto-char pos)
11291 (when (and indent (> indent 0))
11292 (setq indent (make-string indent ?\ ))
11293 (save-excursion
11294 (org-beginning-of-dblock)
11295 (forward-line 1)
11296 (while (not (looking-at org-dblock-end-re))
11297 (insert indent)
11298 (beginning-of-line 2))
11299 (when (looking-at org-dblock-end-re)
11300 (and (looking-at "[ \t]+")
11301 (replace-match ""))
11302 (insert indent)))))))
11304 (defun org-beginning-of-dblock ()
11305 "Find the beginning of the dynamic block at point.
11306 Error if there is no such block at point."
11307 (let ((pos (point))
11308 beg)
11309 (end-of-line 1)
11310 (if (and (re-search-backward org-dblock-start-re nil t)
11311 (setq beg (match-beginning 0))
11312 (re-search-forward org-dblock-end-re nil t)
11313 (> (match-end 0) pos))
11314 (goto-char beg)
11315 (goto-char pos)
11316 (error "Not in a dynamic block"))))
11318 ;;;###autoload
11319 (defun org-update-all-dblocks ()
11320 "Update all dynamic blocks in the buffer.
11321 This function can be used in a hook."
11322 (interactive)
11323 (when (derived-mode-p 'org-mode)
11324 (org-map-dblocks 'org-update-dblock)))
11327 ;;;; Completion
11329 (defconst org-additional-option-like-keywords
11330 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11331 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11332 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11333 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11334 "BEGIN:" "END:"
11335 "ORGTBL" "TBLFM:" "TBLNAME:"
11336 "BEGIN_EXAMPLE" "END_EXAMPLE"
11337 "BEGIN_VERBATIM" "END_VERBATIM"
11338 "BEGIN_QUOTE" "END_QUOTE"
11339 "BEGIN_VERSE" "END_VERSE"
11340 "BEGIN_CENTER" "END_CENTER"
11341 "BEGIN_SRC" "END_SRC"
11342 "BEGIN_RESULT" "END_RESULT"
11343 "BEGIN_lstlisting" "END_lstlisting"
11344 "NAME:" "RESULTS:"
11345 "HEADER:" "HEADERS:"
11346 "COLUMNS:" "PROPERTY:"
11347 "CAPTION:" "LABEL:"
11348 "SETUPFILE:"
11349 "INCLUDE:"
11350 "BIND:"
11351 "MACRO:"))
11353 (defconst org-options-keywords
11354 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11355 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11356 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11357 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11358 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11359 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11360 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11362 (defconst org-additional-option-like-keywords-for-flyspell
11363 (delete-dups
11364 (split-string
11365 (mapconcat (lambda(k)
11366 (replace-regexp-in-string
11367 "_\\|:" " "
11368 (concat k " " (downcase k) " " (upcase k))))
11369 (append org-options-keywords org-additional-option-like-keywords)
11370 " ")
11371 " +" t)))
11373 (defcustom org-structure-template-alist
11375 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11376 "<src lang=\"?\">\n\n</src>")
11377 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11378 "<example>\n?\n</example>")
11379 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11380 "<quote>\n?\n</quote>")
11381 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11382 "<verse>\n?\n</verse>")
11383 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11384 "<center>\n?\n</center>")
11385 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11386 "<literal style=\"latex\">\n?\n</literal>")
11387 ("L" "#+LaTeX: "
11388 "<literal style=\"latex\">?</literal>")
11389 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11390 "<literal style=\"html\">\n?\n</literal>")
11391 ("H" "#+HTML: "
11392 "<literal style=\"html\">?</literal>")
11393 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11394 ("A" "#+ASCII: ")
11395 ("i" "#+INDEX: ?"
11396 "#+INDEX: ?")
11397 ("I" "#+INCLUDE: %file ?"
11398 "<include file=%file markup=\"?\">")
11400 "Structure completion elements.
11401 This is a list of abbreviation keys and values. The value gets inserted
11402 if you type `<' followed by the key and then press the completion key,
11403 usually `M-TAB'. %file will be replaced by a file name after prompting
11404 for the file using completion. The cursor will be placed at the position
11405 of the `?` in the template.
11406 There are two templates for each key, the first uses the original Org syntax,
11407 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11408 the default when the /org-mtags.el/ module has been loaded. See also the
11409 variable `org-mtags-prefer-muse-templates'."
11410 :group 'org-completion
11411 :type '(repeat
11412 (string :tag "Key")
11413 (string :tag "Template")
11414 (string :tag "Muse Template")))
11416 (defun org-try-structure-completion ()
11417 "Try to complete a structure template before point.
11418 This looks for strings like \"<e\" on an otherwise empty line and
11419 expands them."
11420 (let ((l (buffer-substring (point-at-bol) (point)))
11422 (when (and (looking-at "[ \t]*$")
11423 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11424 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11425 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11426 (match-beginning 1)) a)
11427 t)))
11429 (defun org-complete-expand-structure-template (start cell)
11430 "Expand a structure template."
11431 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11432 (rpl (nth (if musep 2 1) cell))
11433 (ind ""))
11434 (delete-region start (point))
11435 (when (string-match "\\`#\\+" rpl)
11436 (cond
11437 ((bolp))
11438 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11439 (setq ind (buffer-substring (point-at-bol) (point))))
11440 (t (newline))))
11441 (setq start (point))
11442 (if (string-match "%file" rpl)
11443 (setq rpl (replace-match
11444 (concat
11445 "\""
11446 (save-match-data
11447 (abbreviate-file-name (read-file-name "Include file: ")))
11448 "\"")
11449 t t rpl)))
11450 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11451 (concat "\n" ind)))
11452 (insert rpl)
11453 (if (re-search-backward "\\?" start t) (delete-char 1))))
11455 ;;;; TODO, DEADLINE, Comments
11457 (defun org-toggle-comment ()
11458 "Change the COMMENT state of an entry."
11459 (interactive)
11460 (save-excursion
11461 (org-back-to-heading)
11462 (let (case-fold-search)
11463 (cond
11464 ((looking-at (format org-heading-keyword-regexp-format
11465 org-comment-string))
11466 (goto-char (match-end 1))
11467 (looking-at (concat " +" org-comment-string))
11468 (replace-match "" t t)
11469 (when (eolp) (insert " ")))
11470 ((looking-at org-outline-regexp)
11471 (goto-char (match-end 0))
11472 (insert org-comment-string " "))))))
11474 (defvar org-last-todo-state-is-todo nil
11475 "This is non-nil when the last TODO state change led to a TODO state.
11476 If the last change removed the TODO tag or switched to DONE, then
11477 this is nil.")
11479 (defvar org-setting-tags nil) ; dynamically skipped
11481 (defvar org-todo-setup-filter-hook nil
11482 "Hook for functions that pre-filter todo specs.
11483 Each function takes a todo spec and returns either nil or the spec
11484 transformed into canonical form." )
11486 (defvar org-todo-get-default-hook nil
11487 "Hook for functions that get a default item for todo.
11488 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11489 nil or a string to be used for the todo mark." )
11491 (defvar org-agenda-headline-snapshot-before-repeat)
11493 (defun org-current-effective-time ()
11494 "Return current time adjusted for `org-extend-today-until' variable."
11495 (let* ((ct (org-current-time))
11496 (dct (decode-time ct))
11497 (ct1
11498 (if (and org-use-effective-time
11499 (< (nth 2 dct) org-extend-today-until))
11500 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11501 ct)))
11502 ct1))
11504 (defun org-todo-yesterday (&optional arg)
11505 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11506 (interactive "P")
11507 (if (eq major-mode 'org-agenda-mode)
11508 (apply 'org-agenda-todo-yesterday arg)
11509 (let* ((hour (third (decode-time
11510 (org-current-time))))
11511 (org-extend-today-until (1+ hour)))
11512 (org-todo arg))))
11514 (defun org-todo (&optional arg)
11515 "Change the TODO state of an item.
11516 The state of an item is given by a keyword at the start of the heading,
11517 like
11518 *** TODO Write paper
11519 *** DONE Call mom
11521 The different keywords are specified in the variable `org-todo-keywords'.
11522 By default the available states are \"TODO\" and \"DONE\".
11523 So for this example: when the item starts with TODO, it is changed to DONE.
11524 When it starts with DONE, the DONE is removed. And when neither TODO nor
11525 DONE are present, add TODO at the beginning of the heading.
11527 With \\[universal-argument] prefix arg, use completion to determine the new \
11528 state.
11529 With numeric prefix arg, switch to that state.
11530 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11531 keywords (nextset).
11532 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11533 With a numeric prefix arg of 0, inhibit note taking for the change.
11535 For calling through lisp, arg is also interpreted in the following way:
11536 'none -> empty state
11537 \"\"(empty string) -> switch to empty state
11538 'done -> switch to DONE
11539 'nextset -> switch to the next set of keywords
11540 'previousset -> switch to the previous set of keywords
11541 \"WAITING\" -> switch to the specified keyword, but only if it
11542 really is a member of `org-todo-keywords'."
11543 (interactive "P")
11544 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11545 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11546 'region-start-level 'region))
11547 org-loop-over-headlines-in-active-region)
11548 (org-map-entries
11549 `(org-todo ,arg)
11550 org-loop-over-headlines-in-active-region
11551 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11552 (if (equal arg '(16)) (setq arg 'nextset))
11553 (let ((org-blocker-hook org-blocker-hook)
11554 (case-fold-search nil))
11555 (when (equal arg '(64))
11556 (setq arg nil org-blocker-hook nil))
11557 (when (and org-blocker-hook
11558 (or org-inhibit-blocking
11559 (org-entry-get nil "NOBLOCKING")))
11560 (setq org-blocker-hook nil))
11561 (save-excursion
11562 (catch 'exit
11563 (org-back-to-heading t)
11564 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11565 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11566 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11567 (let* ((match-data (match-data))
11568 (startpos (point-at-bol))
11569 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11570 (org-log-done org-log-done)
11571 (org-log-repeat org-log-repeat)
11572 (org-todo-log-states org-todo-log-states)
11573 (org-inhibit-logging
11574 (if (equal arg 0)
11575 (progn (setq arg nil) 'note) org-inhibit-logging))
11576 (this (match-string 1))
11577 (hl-pos (match-beginning 0))
11578 (head (org-get-todo-sequence-head this))
11579 (ass (assoc head org-todo-kwd-alist))
11580 (interpret (nth 1 ass))
11581 (done-word (nth 3 ass))
11582 (final-done-word (nth 4 ass))
11583 (org-last-state (or this ""))
11584 (completion-ignore-case t)
11585 (member (member this org-todo-keywords-1))
11586 (tail (cdr member))
11587 (org-state (cond
11588 ((and org-todo-key-trigger
11589 (or (and (equal arg '(4))
11590 (eq org-use-fast-todo-selection 'prefix))
11591 (and (not arg) org-use-fast-todo-selection
11592 (not (eq org-use-fast-todo-selection
11593 'prefix)))))
11594 ;; Use fast selection
11595 (org-fast-todo-selection))
11596 ((and (equal arg '(4))
11597 (or (not org-use-fast-todo-selection)
11598 (not org-todo-key-trigger)))
11599 ;; Read a state with completion
11600 (org-icompleting-read
11601 "State: " (mapcar (lambda(x) (list x))
11602 org-todo-keywords-1)
11603 nil t))
11604 ((eq arg 'right)
11605 (if this
11606 (if tail (car tail) nil)
11607 (car org-todo-keywords-1)))
11608 ((eq arg 'left)
11609 (if (equal member org-todo-keywords-1)
11611 (if this
11612 (nth (- (length org-todo-keywords-1)
11613 (length tail) 2)
11614 org-todo-keywords-1)
11615 (org-last org-todo-keywords-1))))
11616 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11617 (setq arg nil))) ; hack to fall back to cycling
11618 (arg
11619 ;; user or caller requests a specific state
11620 (cond
11621 ((equal arg "") nil)
11622 ((eq arg 'none) nil)
11623 ((eq arg 'done) (or done-word (car org-done-keywords)))
11624 ((eq arg 'nextset)
11625 (or (car (cdr (member head org-todo-heads)))
11626 (car org-todo-heads)))
11627 ((eq arg 'previousset)
11628 (let ((org-todo-heads (reverse org-todo-heads)))
11629 (or (car (cdr (member head org-todo-heads)))
11630 (car org-todo-heads))))
11631 ((car (member arg org-todo-keywords-1)))
11632 ((stringp arg)
11633 (error "State `%s' not valid in this file" arg))
11634 ((nth (1- (prefix-numeric-value arg))
11635 org-todo-keywords-1))))
11636 ((null member) (or head (car org-todo-keywords-1)))
11637 ((equal this final-done-word) nil) ;; -> make empty
11638 ((null tail) nil) ;; -> first entry
11639 ((memq interpret '(type priority))
11640 (if (eq this-command last-command)
11641 (car tail)
11642 (if (> (length tail) 0)
11643 (or done-word (car org-done-keywords))
11644 nil)))
11646 (car tail))))
11647 (org-state (or
11648 (run-hook-with-args-until-success
11649 'org-todo-get-default-hook org-state org-last-state)
11650 org-state))
11651 (next (if org-state (concat " " org-state " ") " "))
11652 (change-plist (list :type 'todo-state-change :from this :to org-state
11653 :position startpos))
11654 dolog now-done-p)
11655 (when org-blocker-hook
11656 (setq org-last-todo-state-is-todo
11657 (not (member this org-done-keywords)))
11658 (unless (save-excursion
11659 (save-match-data
11660 (org-with-wide-buffer
11661 (run-hook-with-args-until-failure
11662 'org-blocker-hook change-plist))))
11663 (if (org-called-interactively-p 'interactive)
11664 (error "TODO state change from %s to %s blocked" this org-state)
11665 ;; fail silently
11666 (message "TODO state change from %s to %s blocked" this org-state)
11667 (throw 'exit nil))))
11668 (store-match-data match-data)
11669 (replace-match next t t)
11670 (unless (pos-visible-in-window-p hl-pos)
11671 (message "TODO state changed to %s" (org-trim next)))
11672 (unless head
11673 (setq head (org-get-todo-sequence-head org-state)
11674 ass (assoc head org-todo-kwd-alist)
11675 interpret (nth 1 ass)
11676 done-word (nth 3 ass)
11677 final-done-word (nth 4 ass)))
11678 (when (memq arg '(nextset previousset))
11679 (message "Keyword-Set %d/%d: %s"
11680 (- (length org-todo-sets) -1
11681 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11682 (length org-todo-sets)
11683 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11684 (setq org-last-todo-state-is-todo
11685 (not (member org-state org-done-keywords)))
11686 (setq now-done-p (and (member org-state org-done-keywords)
11687 (not (member this org-done-keywords))))
11688 (and logging (org-local-logging logging))
11689 (when (and (or org-todo-log-states org-log-done)
11690 (not (eq org-inhibit-logging t))
11691 (not (memq arg '(nextset previousset))))
11692 ;; we need to look at recording a time and note
11693 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11694 (nth 2 (assoc this org-todo-log-states))))
11695 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11696 (setq dolog 'time))
11697 (when (and org-state
11698 (member org-state org-not-done-keywords)
11699 (not (member this org-not-done-keywords)))
11700 ;; This is now a todo state and was not one before
11701 ;; If there was a CLOSED time stamp, get rid of it.
11702 (org-add-planning-info nil nil 'closed))
11703 (when (and now-done-p org-log-done)
11704 ;; It is now done, and it was not done before
11705 (org-add-planning-info 'closed (org-current-effective-time))
11706 (if (and (not dolog) (eq 'note org-log-done))
11707 (org-add-log-setup 'done org-state this 'findpos 'note)))
11708 (when (and org-state dolog)
11709 ;; This is a non-nil state, and we need to log it
11710 (org-add-log-setup 'state org-state this 'findpos dolog)))
11711 ;; Fixup tag positioning
11712 (org-todo-trigger-tag-changes org-state)
11713 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11714 (when org-provide-todo-statistics
11715 (org-update-parent-todo-statistics))
11716 (run-hooks 'org-after-todo-state-change-hook)
11717 (if (and arg (not (member org-state org-done-keywords)))
11718 (setq head (org-get-todo-sequence-head org-state)))
11719 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11720 ;; Do we need to trigger a repeat?
11721 (when now-done-p
11722 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11723 ;; This is for the agenda, take a snapshot of the headline.
11724 (save-match-data
11725 (setq org-agenda-headline-snapshot-before-repeat
11726 (org-get-heading))))
11727 (org-auto-repeat-maybe org-state))
11728 ;; Fixup cursor location if close to the keyword
11729 (if (and (outline-on-heading-p)
11730 (not (bolp))
11731 (save-excursion (beginning-of-line 1)
11732 (looking-at org-todo-line-regexp))
11733 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11734 (progn
11735 (goto-char (or (match-end 2) (match-end 1)))
11736 (and (looking-at " ") (just-one-space))))
11737 (when org-trigger-hook
11738 (save-excursion
11739 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11741 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11742 "Block turning an entry into a TODO, using the hierarchy.
11743 This checks whether the current task should be blocked from state
11744 changes. Such blocking occurs when:
11746 1. The task has children which are not all in a completed state.
11748 2. A task has a parent with the property :ORDERED:, and there
11749 are siblings prior to the current task with incomplete
11750 status.
11752 3. The parent of the task is blocked because it has siblings that should
11753 be done first, or is child of a block grandparent TODO entry."
11755 (if (not org-enforce-todo-dependencies)
11756 t ; if locally turned off don't block
11757 (catch 'dont-block
11758 ;; If this is not a todo state change, or if this entry is already DONE,
11759 ;; do not block
11760 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11761 (member (plist-get change-plist :from)
11762 (cons 'done org-done-keywords))
11763 (member (plist-get change-plist :to)
11764 (cons 'todo org-not-done-keywords))
11765 (not (plist-get change-plist :to)))
11766 (throw 'dont-block t))
11767 ;; If this task has children, and any are undone, it's blocked
11768 (save-excursion
11769 (org-back-to-heading t)
11770 (let ((this-level (funcall outline-level)))
11771 (outline-next-heading)
11772 (let ((child-level (funcall outline-level)))
11773 (while (and (not (eobp))
11774 (> child-level this-level))
11775 ;; this todo has children, check whether they are all
11776 ;; completed
11777 (if (and (not (org-entry-is-done-p))
11778 (org-entry-is-todo-p))
11779 (throw 'dont-block nil))
11780 (outline-next-heading)
11781 (setq child-level (funcall outline-level))))))
11782 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11783 ;; any previous siblings are undone, it's blocked
11784 (save-excursion
11785 (org-back-to-heading t)
11786 (let* ((pos (point))
11787 (parent-pos (and (org-up-heading-safe) (point))))
11788 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11789 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11790 (forward-line 1)
11791 (re-search-forward org-not-done-heading-regexp pos t))
11792 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11793 ;; Search further up the hierarchy, to see if an ancestor is blocked
11794 (while t
11795 (goto-char parent-pos)
11796 (if (not (looking-at org-not-done-heading-regexp))
11797 (throw 'dont-block t)) ; do not block, parent is not a TODO
11798 (setq pos (point))
11799 (setq parent-pos (and (org-up-heading-safe) (point)))
11800 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11801 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11802 (forward-line 1)
11803 (re-search-forward org-not-done-heading-regexp pos t))
11804 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11806 (defcustom org-track-ordered-property-with-tag nil
11807 "Should the ORDERED property also be shown as a tag?
11808 The ORDERED property decides if an entry should require subtasks to be
11809 completed in sequence. Since a property is not very visible, setting
11810 this option means that toggling the ORDERED property with the command
11811 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11812 not relevant for the behavior, but it makes things more visible.
11814 Note that toggling the tag with tags commands will not change the property
11815 and therefore not influence behavior!
11817 This can be t, meaning the tag ORDERED should be used, It can also be a
11818 string to select a different tag for this task."
11819 :group 'org-todo
11820 :type '(choice
11821 (const :tag "No tracking" nil)
11822 (const :tag "Track with ORDERED tag" t)
11823 (string :tag "Use other tag")))
11825 (defun org-toggle-ordered-property ()
11826 "Toggle the ORDERED property of the current entry.
11827 For better visibility, you can track the value of this property with a tag.
11828 See variable `org-track-ordered-property-with-tag'."
11829 (interactive)
11830 (let* ((t1 org-track-ordered-property-with-tag)
11831 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11832 (save-excursion
11833 (org-back-to-heading)
11834 (if (org-entry-get nil "ORDERED")
11835 (progn
11836 (org-delete-property "ORDERED")
11837 (and tag (org-toggle-tag tag 'off))
11838 (message "Subtasks can be completed in arbitrary order"))
11839 (org-entry-put nil "ORDERED" "t")
11840 (and tag (org-toggle-tag tag 'on))
11841 (message "Subtasks must be completed in sequence")))))
11843 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11844 (defun org-block-todo-from-checkboxes (change-plist)
11845 "Block turning an entry into a TODO, using checkboxes.
11846 This checks whether the current task should be blocked from state
11847 changes because there are unchecked boxes in this entry."
11848 (if (not org-enforce-todo-checkbox-dependencies)
11849 t ; if locally turned off don't block
11850 (catch 'dont-block
11851 ;; If this is not a todo state change, or if this entry is already DONE,
11852 ;; do not block
11853 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11854 (member (plist-get change-plist :from)
11855 (cons 'done org-done-keywords))
11856 (member (plist-get change-plist :to)
11857 (cons 'todo org-not-done-keywords))
11858 (not (plist-get change-plist :to)))
11859 (throw 'dont-block t))
11860 ;; If this task has checkboxes that are not checked, it's blocked
11861 (save-excursion
11862 (org-back-to-heading t)
11863 (let ((beg (point)) end)
11864 (outline-next-heading)
11865 (setq end (point))
11866 (goto-char beg)
11867 (if (org-list-search-forward
11868 (concat (org-item-beginning-re)
11869 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11870 "\\[[- ]\\]")
11871 end t)
11872 (progn
11873 (if (boundp 'org-blocked-by-checkboxes)
11874 (setq org-blocked-by-checkboxes t))
11875 (throw 'dont-block nil)))))
11876 t))) ; do not block
11878 (defun org-entry-blocked-p ()
11879 "Is the current entry blocked?"
11880 (if (org-entry-get nil "NOBLOCKING")
11881 nil ;; Never block this entry
11882 (not
11883 (run-hook-with-args-until-failure
11884 'org-blocker-hook
11885 (list :type 'todo-state-change
11886 :position (point)
11887 :from 'todo
11888 :to 'done)))))
11890 (defun org-update-statistics-cookies (all)
11891 "Update the statistics cookie, either from TODO or from checkboxes.
11892 This should be called with the cursor in a line with a statistics cookie."
11893 (interactive "P")
11894 (if all
11895 (progn
11896 (org-update-checkbox-count 'all)
11897 (org-map-entries 'org-update-parent-todo-statistics))
11898 (if (not (org-at-heading-p))
11899 (org-update-checkbox-count)
11900 (let ((pos (move-marker (make-marker) (point)))
11901 end l1 l2)
11902 (ignore-errors (org-back-to-heading t))
11903 (if (not (org-at-heading-p))
11904 (org-update-checkbox-count)
11905 (setq l1 (org-outline-level))
11906 (setq end (save-excursion
11907 (outline-next-heading)
11908 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11909 (point)))
11910 (if (and (save-excursion
11911 (re-search-forward
11912 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11913 (not (save-excursion (re-search-forward
11914 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11915 (org-update-checkbox-count)
11916 (if (and l2 (> l2 l1))
11917 (progn
11918 (goto-char end)
11919 (org-update-parent-todo-statistics))
11920 (goto-char pos)
11921 (beginning-of-line 1)
11922 (while (re-search-forward
11923 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11924 (point-at-eol) t)
11925 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11926 (goto-char pos)
11927 (move-marker pos nil)))))
11929 (defvar org-entry-property-inherited-from) ;; defined below
11930 (defun org-update-parent-todo-statistics ()
11931 "Update any statistics cookie in the parent of the current headline.
11932 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11933 the entire subtree and this will travel up the hierarchy and update
11934 statistics everywhere."
11935 (let* ((prop (save-excursion (org-up-heading-safe)
11936 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11937 (recursive (or (not org-hierarchical-todo-statistics)
11938 (and prop (string-match "\\<recursive\\>" prop))))
11939 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11941 (first t)
11942 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11943 level ltoggle l1 new ndel
11944 (cnt-all 0) (cnt-done 0) is-percent kwd
11945 checkbox-beg ov ovs ove cookie-present)
11946 (catch 'exit
11947 (save-excursion
11948 (beginning-of-line 1)
11949 (setq ltoggle (funcall outline-level))
11950 ;; Three situations are to consider:
11952 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11953 ;; to the top-level ancestor on the headline;
11955 ;; 2. If parent has "recursive" property, repeat up to the
11956 ;; headline setting that property, taking inheritance into
11957 ;; account;
11959 ;; 3. Else, move up to direct parent and proceed only once.
11960 (while (and (setq level (org-up-heading-safe))
11961 (or recursive first)
11962 (>= (point) lim))
11963 (setq first nil cookie-present nil)
11964 (unless (and level
11965 (not (string-match
11966 "\\<checkbox\\>"
11967 (downcase (or (org-entry-get nil "COOKIE_DATA")
11968 "")))))
11969 (throw 'exit nil))
11970 (while (re-search-forward box-re (point-at-eol) t)
11971 (setq cnt-all 0 cnt-done 0 cookie-present t)
11972 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11973 (save-match-data
11974 (unless (outline-next-heading) (throw 'exit nil))
11975 (while (and (looking-at org-complex-heading-regexp)
11976 (> (setq l1 (length (match-string 1))) level))
11977 (setq kwd (and (or recursive (= l1 ltoggle))
11978 (match-string 2)))
11979 (if (or (eq org-provide-todo-statistics 'all-headlines)
11980 (and (listp org-provide-todo-statistics)
11981 (or (member kwd org-provide-todo-statistics)
11982 (member kwd org-done-keywords))))
11983 (setq cnt-all (1+ cnt-all))
11984 (if (eq org-provide-todo-statistics t)
11985 (and kwd (setq cnt-all (1+ cnt-all)))))
11986 (and (member kwd org-done-keywords)
11987 (setq cnt-done (1+ cnt-done)))
11988 (outline-next-heading)))
11989 (setq new
11990 (if is-percent
11991 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11992 (format "[%d/%d]" cnt-done cnt-all))
11993 ndel (- (match-end 0) checkbox-beg))
11994 ;; handle overlays when updating cookie from column view
11995 (when (setq ov (car (overlays-at checkbox-beg)))
11996 (setq ovs (overlay-start ov) ove (overlay-end ov))
11997 (delete-overlay ov))
11998 (goto-char checkbox-beg)
11999 (insert new)
12000 (delete-region (point) (+ (point) ndel))
12001 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12002 (when ov (move-overlay ov ovs ove)))
12003 (when cookie-present
12004 (run-hook-with-args 'org-after-todo-statistics-hook
12005 cnt-done (- cnt-all cnt-done))))))
12006 (run-hooks 'org-todo-statistics-hook)))
12008 (defvar org-after-todo-statistics-hook nil
12009 "Hook that is called after a TODO statistics cookie has been updated.
12010 Each function is called with two arguments: the number of not-done entries
12011 and the number of done entries.
12013 For example, the following function, when added to this hook, will switch
12014 an entry to DONE when all children are done, and back to TODO when new
12015 entries are set to a TODO status. Note that this hook is only called
12016 when there is a statistics cookie in the headline!
12018 (defun org-summary-todo (n-done n-not-done)
12019 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12020 (let (org-log-done org-log-states) ; turn off logging
12021 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12024 (defvar org-todo-statistics-hook nil
12025 "Hook that is run whenever Org thinks TODO statistics should be updated.
12026 This hook runs even if there is no statistics cookie present, in which case
12027 `org-after-todo-statistics-hook' would not run.")
12029 (defun org-todo-trigger-tag-changes (state)
12030 "Apply the changes defined in `org-todo-state-tags-triggers'."
12031 (let ((l org-todo-state-tags-triggers)
12032 changes)
12033 (when (or (not state) (equal state ""))
12034 (setq changes (append changes (cdr (assoc "" l)))))
12035 (when (and (stringp state) (> (length state) 0))
12036 (setq changes (append changes (cdr (assoc state l)))))
12037 (when (member state org-not-done-keywords)
12038 (setq changes (append changes (cdr (assoc 'todo l)))))
12039 (when (member state org-done-keywords)
12040 (setq changes (append changes (cdr (assoc 'done l)))))
12041 (dolist (c changes)
12042 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12044 (defun org-local-logging (value)
12045 "Get logging settings from a property VALUE."
12046 (let* (words w a)
12047 ;; directly set the variables, they are already local.
12048 (setq org-log-done nil
12049 org-log-repeat nil
12050 org-todo-log-states nil)
12051 (setq words (org-split-string value))
12052 (while (setq w (pop words))
12053 (cond
12054 ((setq a (assoc w org-startup-options))
12055 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12056 (set (nth 1 a) (nth 2 a))))
12057 ((setq a (org-extract-log-state-settings w))
12058 (and (member (car a) org-todo-keywords-1)
12059 (push a org-todo-log-states)))))))
12061 (defun org-get-todo-sequence-head (kwd)
12062 "Return the head of the TODO sequence to which KWD belongs.
12063 If KWD is not set, check if there is a text property remembering the
12064 right sequence."
12065 (let (p)
12066 (cond
12067 ((not kwd)
12068 (or (get-text-property (point-at-bol) 'org-todo-head)
12069 (progn
12070 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12071 nil (point-at-eol)))
12072 (get-text-property p 'org-todo-head))))
12073 ((not (member kwd org-todo-keywords-1))
12074 (car org-todo-keywords-1))
12075 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12077 (defun org-fast-todo-selection ()
12078 "Fast TODO keyword selection with single keys.
12079 Returns the new TODO keyword, or nil if no state change should occur."
12080 (let* ((fulltable org-todo-key-alist)
12081 (done-keywords org-done-keywords) ;; needed for the faces.
12082 (maxlen (apply 'max (mapcar
12083 (lambda (x)
12084 (if (stringp (car x)) (string-width (car x)) 0))
12085 fulltable)))
12086 (expert nil)
12087 (fwidth (+ maxlen 3 1 3))
12088 (ncol (/ (- (window-width) 4) fwidth))
12089 tg cnt e c tbl
12090 groups ingroup)
12091 (save-excursion
12092 (save-window-excursion
12093 (if expert
12094 (set-buffer (get-buffer-create " *Org todo*"))
12095 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12096 (erase-buffer)
12097 (org-set-local 'org-done-keywords done-keywords)
12098 (setq tbl fulltable cnt 0)
12099 (while (setq e (pop tbl))
12100 (cond
12101 ((equal e '(:startgroup))
12102 (push '() groups) (setq ingroup t)
12103 (when (not (= cnt 0))
12104 (setq cnt 0)
12105 (insert "\n"))
12106 (insert "{ "))
12107 ((equal e '(:endgroup))
12108 (setq ingroup nil cnt 0)
12109 (insert "}\n"))
12110 ((equal e '(:newline))
12111 (when (not (= cnt 0))
12112 (setq cnt 0)
12113 (insert "\n")
12114 (setq e (car tbl))
12115 (while (equal (car tbl) '(:newline))
12116 (insert "\n")
12117 (setq tbl (cdr tbl)))))
12119 (setq tg (car e) c (cdr e))
12120 (if ingroup (push tg (car groups)))
12121 (setq tg (org-add-props tg nil 'face
12122 (org-get-todo-face tg)))
12123 (if (and (= cnt 0) (not ingroup)) (insert " "))
12124 (insert "[" c "] " tg (make-string
12125 (- fwidth 4 (length tg)) ?\ ))
12126 (when (= (setq cnt (1+ cnt)) ncol)
12127 (insert "\n")
12128 (if ingroup (insert " "))
12129 (setq cnt 0)))))
12130 (insert "\n")
12131 (goto-char (point-min))
12132 (if (not expert) (org-fit-window-to-buffer))
12133 (message "[a-z..]:Set [SPC]:clear")
12134 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12135 (cond
12136 ((or (= c ?\C-g)
12137 (and (= c ?q) (not (rassoc c fulltable))))
12138 (setq quit-flag t))
12139 ((= c ?\ ) nil)
12140 ((setq e (rassoc c fulltable) tg (car e))
12142 (t (setq quit-flag t)))))))
12144 (defun org-entry-is-todo-p ()
12145 (member (org-get-todo-state) org-not-done-keywords))
12147 (defun org-entry-is-done-p ()
12148 (member (org-get-todo-state) org-done-keywords))
12150 (defun org-get-todo-state ()
12151 (save-excursion
12152 (org-back-to-heading t)
12153 (and (looking-at org-todo-line-regexp)
12154 (match-end 2)
12155 (match-string 2))))
12157 (defun org-at-date-range-p (&optional inactive-ok)
12158 "Is the cursor inside a date range?"
12159 (interactive)
12160 (save-excursion
12161 (catch 'exit
12162 (let ((pos (point)))
12163 (skip-chars-backward "^[<\r\n")
12164 (skip-chars-backward "<[")
12165 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12166 (>= (match-end 0) pos)
12167 (throw 'exit t))
12168 (skip-chars-backward "^<[\r\n")
12169 (skip-chars-backward "<[")
12170 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12171 (>= (match-end 0) pos)
12172 (throw 'exit t)))
12173 nil)))
12175 (defun org-get-repeat (&optional tagline)
12176 "Check if there is a deadline/schedule with repeater in this entry."
12177 (save-match-data
12178 (save-excursion
12179 (org-back-to-heading t)
12180 (and (re-search-forward (if tagline
12181 (concat tagline "\\s-*" org-repeat-re)
12182 org-repeat-re)
12183 (org-entry-end-position) t)
12184 (match-string-no-properties 1)))))
12186 (defvar org-last-changed-timestamp)
12187 (defvar org-last-inserted-timestamp)
12188 (defvar org-log-post-message)
12189 (defvar org-log-note-purpose)
12190 (defvar org-log-note-how)
12191 (defvar org-log-note-extra)
12192 (defun org-auto-repeat-maybe (done-word)
12193 "Check if the current headline contains a repeated deadline/schedule.
12194 If yes, set TODO state back to what it was and change the base date
12195 of repeating deadline/scheduled time stamps to new date.
12196 This function is run automatically after each state change to a DONE state."
12197 ;; last-state is dynamically scoped into this function
12198 (let* ((repeat (org-get-repeat))
12199 (aa (assoc org-last-state org-todo-kwd-alist))
12200 (interpret (nth 1 aa))
12201 (head (nth 2 aa))
12202 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12203 (msg "Entry repeats: ")
12204 (org-log-done nil)
12205 (org-todo-log-states nil)
12206 re type n what ts time to-state)
12207 (when repeat
12208 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12209 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12210 org-todo-repeat-to-state))
12211 (unless (and to-state (member to-state org-todo-keywords-1))
12212 (setq to-state (if (eq interpret 'type) org-last-state head)))
12213 (org-todo to-state)
12214 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12215 (org-entry-put nil "LAST_REPEAT" (format-time-string
12216 (org-time-stamp-format t t))))
12217 (when org-log-repeat
12218 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12219 (memq 'org-add-log-note post-command-hook))
12220 ;; OK, we are already setup for some record
12221 (if (eq org-log-repeat 'note)
12222 ;; make sure we take a note, not only a time stamp
12223 (setq org-log-note-how 'note))
12224 ;; Set up for taking a record
12225 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12226 org-last-state
12227 'findpos org-log-repeat)))
12228 (org-back-to-heading t)
12229 (org-add-planning-info nil nil 'closed)
12230 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12231 org-deadline-time-regexp "\\)\\|\\("
12232 org-ts-regexp "\\)"))
12233 (while (re-search-forward
12234 re (save-excursion (outline-next-heading) (point)) t)
12235 (setq type (if (match-end 1) org-scheduled-string
12236 (if (match-end 3) org-deadline-string "Plain:"))
12237 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12238 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12239 (setq n (string-to-number (match-string 2 ts))
12240 what (match-string 3 ts))
12241 (if (equal what "w") (setq n (* n 7) what "d"))
12242 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12243 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12244 ;; Preparation, see if we need to modify the start date for the change
12245 (when (match-end 1)
12246 (setq time (save-match-data (org-time-string-to-time ts)))
12247 (cond
12248 ((equal (match-string 1 ts) ".")
12249 ;; Shift starting date to today
12250 (org-timestamp-change
12251 (- (org-today) (time-to-days time))
12252 'day))
12253 ((equal (match-string 1 ts) "+")
12254 (let ((nshiftmax 10) (nshift 0))
12255 (while (or (= nshift 0)
12256 (<= (time-to-days time)
12257 (time-to-days (current-time))))
12258 (when (= (incf nshift) nshiftmax)
12259 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12260 (error "Abort")))
12261 (org-timestamp-change n (cdr (assoc what whata)))
12262 (org-at-timestamp-p t)
12263 (setq ts (match-string 1))
12264 (setq time (save-match-data (org-time-string-to-time ts)))))
12265 (org-timestamp-change (- n) (cdr (assoc what whata)))
12266 ;; rematch, so that we have everything in place for the real shift
12267 (org-at-timestamp-p t)
12268 (setq ts (match-string 1))
12269 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12270 (org-timestamp-change n (cdr (assoc what whata)))
12271 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12272 (setq org-log-post-message msg)
12273 (message "%s" msg))))
12275 (defun org-show-todo-tree (arg)
12276 "Make a compact tree which shows all headlines marked with TODO.
12277 The tree will show the lines where the regexp matches, and all higher
12278 headlines above the match.
12279 With a \\[universal-argument] prefix, prompt for a regexp to match.
12280 With a numeric prefix N, construct a sparse tree for the Nth element
12281 of `org-todo-keywords-1'."
12282 (interactive "P")
12283 (let ((case-fold-search nil)
12284 (kwd-re
12285 (cond ((null arg) org-not-done-regexp)
12286 ((equal arg '(4))
12287 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12288 (mapcar 'list org-todo-keywords-1))))
12289 (concat "\\("
12290 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12291 "\\)\\>")))
12292 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12293 (regexp-quote (nth (1- (prefix-numeric-value arg))
12294 org-todo-keywords-1)))
12295 (t (error "Invalid prefix argument: %s" arg)))))
12296 (message "%d TODO entries found"
12297 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12299 (defun org-deadline (&optional remove time)
12300 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12301 With argument REMOVE, remove any deadline from the item.
12302 With argument TIME, set the deadline at the corresponding date. TIME
12303 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12304 (interactive "P")
12305 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12306 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12307 'region-start-level 'region))
12308 org-loop-over-headlines-in-active-region)
12309 (org-map-entries
12310 `(org-deadline ',remove ,time)
12311 org-loop-over-headlines-in-active-region
12312 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12313 (let* ((old-date (org-entry-get nil "DEADLINE"))
12314 (repeater (and old-date
12315 (string-match
12316 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12317 old-date)
12318 (match-string 1 old-date))))
12319 (if remove
12320 (progn
12321 (when (and old-date org-log-redeadline)
12322 (org-add-log-setup 'deldeadline nil old-date 'findpos
12323 org-log-redeadline))
12324 (org-remove-timestamp-with-keyword org-deadline-string)
12325 (message "Item no longer has a deadline."))
12326 (org-add-planning-info 'deadline time 'closed)
12327 (when (and old-date org-log-redeadline
12328 (not (equal old-date
12329 (substring org-last-inserted-timestamp 1 -1))))
12330 (org-add-log-setup 'redeadline nil old-date 'findpos
12331 org-log-redeadline))
12332 (when repeater
12333 (save-excursion
12334 (org-back-to-heading t)
12335 (when (re-search-forward (concat org-deadline-string " "
12336 org-last-inserted-timestamp)
12337 (save-excursion
12338 (outline-next-heading) (point)) t)
12339 (goto-char (1- (match-end 0)))
12340 (insert " " repeater)
12341 (setq org-last-inserted-timestamp
12342 (concat (substring org-last-inserted-timestamp 0 -1)
12343 " " repeater
12344 (substring org-last-inserted-timestamp -1))))))
12345 (message "Deadline on %s" org-last-inserted-timestamp)))))
12347 (defun org-schedule (&optional remove time)
12348 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12349 With argument REMOVE, remove any scheduling date from the item.
12350 With argument TIME, scheduled at the corresponding date. TIME can
12351 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12352 (interactive "P")
12353 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12354 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12355 'region-start-level 'region))
12356 org-loop-over-headlines-in-active-region)
12357 (org-map-entries
12358 `(org-schedule ',remove ,time)
12359 org-loop-over-headlines-in-active-region
12360 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12361 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12362 (repeater (and old-date
12363 (string-match
12364 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12365 old-date)
12366 (match-string 1 old-date))))
12367 (if remove
12368 (progn
12369 (when (and old-date org-log-reschedule)
12370 (org-add-log-setup 'delschedule nil old-date 'findpos
12371 org-log-reschedule))
12372 (org-remove-timestamp-with-keyword org-scheduled-string)
12373 (message "Item is no longer scheduled."))
12374 (org-add-planning-info 'scheduled time 'closed)
12375 (when (and old-date org-log-reschedule
12376 (not (equal old-date
12377 (substring org-last-inserted-timestamp 1 -1))))
12378 (org-add-log-setup 'reschedule nil old-date 'findpos
12379 org-log-reschedule))
12380 (when repeater
12381 (save-excursion
12382 (org-back-to-heading t)
12383 (when (re-search-forward (concat org-scheduled-string " "
12384 org-last-inserted-timestamp)
12385 (save-excursion
12386 (outline-next-heading) (point)) t)
12387 (goto-char (1- (match-end 0)))
12388 (insert " " repeater)
12389 (setq org-last-inserted-timestamp
12390 (concat (substring org-last-inserted-timestamp 0 -1)
12391 " " repeater
12392 (substring org-last-inserted-timestamp -1))))))
12393 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12395 (defun org-get-scheduled-time (pom &optional inherit)
12396 "Get the scheduled time as a time tuple, of a format suitable
12397 for calling org-schedule with, or if there is no scheduling,
12398 returns nil."
12399 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12400 (when time
12401 (apply 'encode-time (org-parse-time-string time)))))
12403 (defun org-get-deadline-time (pom &optional inherit)
12404 "Get the deadline as a time tuple, of a format suitable for
12405 calling org-deadline with, or if there is no scheduling, returns
12406 nil."
12407 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12408 (when time
12409 (apply 'encode-time (org-parse-time-string time)))))
12411 (defun org-remove-timestamp-with-keyword (keyword)
12412 "Remove all time stamps with KEYWORD in the current entry."
12413 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12414 beg)
12415 (save-excursion
12416 (org-back-to-heading t)
12417 (setq beg (point))
12418 (outline-next-heading)
12419 (while (re-search-backward re beg t)
12420 (replace-match "")
12421 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12422 (equal (char-before) ?\ ))
12423 (backward-delete-char 1)
12424 (if (string-match "^[ \t]*$" (buffer-substring
12425 (point-at-bol) (point-at-eol)))
12426 (delete-region (point-at-bol)
12427 (min (point-max) (1+ (point-at-eol))))))))))
12429 (defun org-add-planning-info (what &optional time &rest remove)
12430 "Insert new timestamp with keyword in the line directly after the headline.
12431 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12432 If non is given, the user is prompted for a date.
12433 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12434 be removed."
12435 (interactive)
12436 (let (org-time-was-given org-end-time-was-given ts
12437 end default-time default-input)
12439 (catch 'exit
12440 (when (and (memq what '(scheduled deadline))
12441 (or (not time)
12442 (and (stringp time)
12443 (string-match "^[-+]+[0-9]" time))))
12444 ;; Try to get a default date/time from existing timestamp
12445 (save-excursion
12446 (org-back-to-heading t)
12447 (setq end (save-excursion (outline-next-heading) (point)))
12448 (when (re-search-forward (if (eq what 'scheduled)
12449 org-scheduled-time-regexp
12450 org-deadline-time-regexp)
12451 end t)
12452 (setq ts (match-string 1)
12453 default-time
12454 (apply 'encode-time (org-parse-time-string ts))
12455 default-input (and ts (org-get-compact-tod ts))))))
12456 (when what
12457 (setq time
12458 (if (stringp time)
12459 ;; This is a string (relative or absolute), set proper date
12460 (apply 'encode-time
12461 (org-read-date-analyze
12462 time default-time (decode-time default-time)))
12463 ;; If necessary, get the time from the user
12464 (or time (org-read-date nil 'to-time nil nil
12465 default-time default-input)))))
12467 (when (and org-insert-labeled-timestamps-at-point
12468 (member what '(scheduled deadline)))
12469 (insert
12470 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12471 (org-insert-time-stamp time org-time-was-given
12472 nil nil nil (list org-end-time-was-given))
12473 (setq what nil))
12474 (save-excursion
12475 (save-restriction
12476 (let (col list elt ts buffer-invisibility-spec)
12477 (org-back-to-heading t)
12478 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12479 (goto-char (match-end 1))
12480 (setq col (current-column))
12481 (goto-char (match-end 0))
12482 (if (eobp) (insert "\n") (forward-char 1))
12483 (when (and (not what)
12484 (not (looking-at
12485 (concat "[ \t]*"
12486 org-keyword-time-not-clock-regexp))))
12487 ;; Nothing to add, nothing to remove...... :-)
12488 (throw 'exit nil))
12489 (if (and (not (looking-at org-outline-regexp))
12490 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12491 "[^\r\n]*"))
12492 (not (equal (match-string 1) org-clock-string)))
12493 (narrow-to-region (match-beginning 0) (match-end 0))
12494 (insert-before-markers "\n")
12495 (backward-char 1)
12496 (narrow-to-region (point) (point))
12497 (and org-adapt-indentation (org-indent-to-column col)))
12498 ;; Check if we have to remove something.
12499 (setq list (cons what remove))
12500 (while list
12501 (setq elt (pop list))
12502 (when (or (and (eq elt 'scheduled)
12503 (re-search-forward org-scheduled-time-regexp nil t))
12504 (and (eq elt 'deadline)
12505 (re-search-forward org-deadline-time-regexp nil t))
12506 (and (eq elt 'closed)
12507 (re-search-forward org-closed-time-regexp nil t)))
12508 (replace-match "")
12509 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12510 (and (looking-at "[ \t]+") (replace-match ""))
12511 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12512 (when what
12513 (insert
12514 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12515 (cond ((eq what 'scheduled) org-scheduled-string)
12516 ((eq what 'deadline) org-deadline-string)
12517 ((eq what 'closed) org-closed-string))
12518 " ")
12519 (setq ts (org-insert-time-stamp
12520 time
12521 (or org-time-was-given
12522 (and (eq what 'closed) org-log-done-with-time))
12523 (eq what 'closed)
12524 nil nil (list org-end-time-was-given)))
12525 (insert
12526 (if (not (or (bolp) (eq (char-before) ?\ )
12527 (memq (char-after) '(32 10))
12528 (eobp))) " " ""))
12529 (end-of-line 1))
12530 (goto-char (point-min))
12531 (widen)
12532 (if (and (looking-at "[ \t]*\n")
12533 (equal (char-before) ?\n))
12534 (delete-region (1- (point)) (point-at-eol)))
12535 ts))))))
12537 (defvar org-log-note-marker (make-marker))
12538 (defvar org-log-note-purpose nil)
12539 (defvar org-log-note-state nil)
12540 (defvar org-log-note-previous-state nil)
12541 (defvar org-log-note-how nil)
12542 (defvar org-log-note-extra nil)
12543 (defvar org-log-note-window-configuration nil)
12544 (defvar org-log-note-return-to (make-marker))
12545 (defvar org-log-note-effective-time nil
12546 "Remembered current time so that dynamically scoped
12547 `org-extend-today-until' affects tha timestamps in state change
12548 log")
12550 (defvar org-log-post-message nil
12551 "Message to be displayed after a log note has been stored.
12552 The auto-repeater uses this.")
12554 (defun org-add-note ()
12555 "Add a note to the current entry.
12556 This is done in the same way as adding a state change note."
12557 (interactive)
12558 (org-add-log-setup 'note nil nil 'findpos nil))
12560 (defvar org-property-end-re)
12561 (defun org-add-log-setup (&optional purpose state prev-state
12562 findpos how extra)
12563 "Set up the post command hook to take a note.
12564 If this is about to TODO state change, the new state is expected in STATE.
12565 When FINDPOS is non-nil, find the correct position for the note in
12566 the current entry. If not, assume that it can be inserted at point.
12567 HOW is an indicator what kind of note should be created.
12568 EXTRA is additional text that will be inserted into the notes buffer."
12569 (let* ((org-log-into-drawer (org-log-into-drawer))
12570 (drawer (cond ((stringp org-log-into-drawer)
12571 org-log-into-drawer)
12572 (org-log-into-drawer "LOGBOOK"))))
12573 (save-restriction
12574 (save-excursion
12575 (when findpos
12576 (org-back-to-heading t)
12577 (narrow-to-region (point) (save-excursion
12578 (outline-next-heading) (point)))
12579 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12580 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12581 "[^\r\n]*\\)?"))
12582 (goto-char (match-end 0))
12583 (cond
12584 (drawer
12585 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12586 nil t)
12587 (progn
12588 (goto-char (match-end 0))
12589 (or org-log-states-order-reversed
12590 (and (re-search-forward org-property-end-re nil t)
12591 (goto-char (1- (match-beginning 0))))))
12592 (insert "\n:" drawer ":\n:END:")
12593 (beginning-of-line 0)
12594 (org-indent-line)
12595 (beginning-of-line 2)
12596 (org-indent-line)
12597 (end-of-line 0)))
12598 ((and org-log-state-notes-insert-after-drawers
12599 (save-excursion
12600 (forward-line) (looking-at org-drawer-regexp)))
12601 (forward-line)
12602 (while (looking-at org-drawer-regexp)
12603 (goto-char (match-end 0))
12604 (re-search-forward org-property-end-re (point-max) t)
12605 (forward-line))
12606 (forward-line -1)))
12607 (unless org-log-states-order-reversed
12608 (and (= (char-after) ?\n) (forward-char 1))
12609 (org-skip-over-state-notes)
12610 (skip-chars-backward " \t\n\r")))
12611 (move-marker org-log-note-marker (point))
12612 (setq org-log-note-purpose purpose
12613 org-log-note-state state
12614 org-log-note-previous-state prev-state
12615 org-log-note-how how
12616 org-log-note-extra extra
12617 org-log-note-effective-time (org-current-effective-time))
12618 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12620 (defun org-skip-over-state-notes ()
12621 "Skip past the list of State notes in an entry."
12622 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12623 (when (ignore-errors (goto-char (org-in-item-p)))
12624 (let* ((struct (org-list-struct))
12625 (prevs (org-list-prevs-alist struct)))
12626 (while (looking-at "[ \t]*- State")
12627 (goto-char (or (org-list-get-next-item (point) struct prevs)
12628 (org-list-get-item-end (point) struct)))))))
12630 (defun org-add-log-note (&optional purpose)
12631 "Pop up a window for taking a note, and add this note later at point."
12632 (remove-hook 'post-command-hook 'org-add-log-note)
12633 (setq org-log-note-window-configuration (current-window-configuration))
12634 (delete-other-windows)
12635 (move-marker org-log-note-return-to (point))
12636 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12637 (goto-char org-log-note-marker)
12638 (org-switch-to-buffer-other-window "*Org Note*")
12639 (erase-buffer)
12640 (if (memq org-log-note-how '(time state))
12641 (let (current-prefix-arg) (org-store-log-note))
12642 (let ((org-inhibit-startup t)) (org-mode))
12643 (insert (format "# Insert note for %s.
12644 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12645 (cond
12646 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12647 ((eq org-log-note-purpose 'done) "closed todo item")
12648 ((eq org-log-note-purpose 'state)
12649 (format "state change from \"%s\" to \"%s\""
12650 (or org-log-note-previous-state "")
12651 (or org-log-note-state "")))
12652 ((eq org-log-note-purpose 'reschedule)
12653 "rescheduling")
12654 ((eq org-log-note-purpose 'delschedule)
12655 "no longer scheduled")
12656 ((eq org-log-note-purpose 'redeadline)
12657 "changing deadline")
12658 ((eq org-log-note-purpose 'deldeadline)
12659 "removing deadline")
12660 ((eq org-log-note-purpose 'refile)
12661 "refiling")
12662 ((eq org-log-note-purpose 'note)
12663 "this entry")
12664 (t (error "This should not happen")))))
12665 (if org-log-note-extra (insert org-log-note-extra))
12666 (org-set-local 'org-finish-function 'org-store-log-note)
12667 (run-hooks 'org-log-buffer-setup-hook)))
12669 (defvar org-note-abort nil) ; dynamically scoped
12670 (defun org-store-log-note ()
12671 "Finish taking a log note, and insert it to where it belongs."
12672 (let ((txt (buffer-string))
12673 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12674 lines ind bul)
12675 (kill-buffer (current-buffer))
12676 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12677 (setq txt (replace-match "" t t txt)))
12678 (if (string-match "\\s-+\\'" txt)
12679 (setq txt (replace-match "" t t txt)))
12680 (setq lines (org-split-string txt "\n"))
12681 (when (and note (string-match "\\S-" note))
12682 (setq note
12683 (org-replace-escapes
12684 note
12685 (list (cons "%u" (user-login-name))
12686 (cons "%U" user-full-name)
12687 (cons "%t" (format-time-string
12688 (org-time-stamp-format 'long 'inactive)
12689 org-log-note-effective-time))
12690 (cons "%T" (format-time-string
12691 (org-time-stamp-format 'long nil)
12692 org-log-note-effective-time))
12693 (cons "%d" (format-time-string
12694 (org-time-stamp-format nil 'inactive)
12695 org-log-note-effective-time))
12696 (cons "%D" (format-time-string
12697 (org-time-stamp-format nil nil)
12698 org-log-note-effective-time))
12699 (cons "%s" (if org-log-note-state
12700 (concat "\"" org-log-note-state "\"")
12701 ""))
12702 (cons "%S" (if org-log-note-previous-state
12703 (concat "\"" org-log-note-previous-state "\"")
12704 "\"\"")))))
12705 (if lines (setq note (concat note " \\\\")))
12706 (push note lines))
12707 (when (or current-prefix-arg org-note-abort)
12708 (when org-log-into-drawer
12709 (org-remove-empty-drawer-at
12710 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12711 org-log-note-marker))
12712 (setq lines nil))
12713 (when lines
12714 (with-current-buffer (marker-buffer org-log-note-marker)
12715 (save-excursion
12716 (goto-char org-log-note-marker)
12717 (move-marker org-log-note-marker nil)
12718 (end-of-line 1)
12719 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12720 (setq ind (save-excursion
12721 (if (ignore-errors (goto-char (org-in-item-p)))
12722 (let ((struct (org-list-struct)))
12723 (org-list-get-ind
12724 (org-list-get-top-point struct) struct))
12725 (skip-chars-backward " \r\t\n")
12726 (cond
12727 ((and (org-at-heading-p)
12728 org-adapt-indentation)
12729 (1+ (org-current-level)))
12730 ((org-at-heading-p) 0)
12731 (t (org-get-indentation))))))
12732 (setq bul (org-list-bullet-string "-"))
12733 (org-indent-line-to ind)
12734 (insert bul (pop lines))
12735 (let ((ind-body (+ (length bul) ind)))
12736 (while lines
12737 (insert "\n")
12738 (org-indent-line-to ind-body)
12739 (insert (pop lines))))
12740 (message "Note stored")
12741 (org-back-to-heading t)
12742 (org-cycle-hide-drawers 'children)))))
12743 (set-window-configuration org-log-note-window-configuration)
12744 (with-current-buffer (marker-buffer org-log-note-return-to)
12745 (goto-char org-log-note-return-to))
12746 (move-marker org-log-note-return-to nil)
12747 (and org-log-post-message (message "%s" org-log-post-message)))
12749 (defun org-remove-empty-drawer-at (drawer pos)
12750 "Remove an empty drawer DRAWER at position POS.
12751 POS may also be a marker."
12752 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12753 (save-excursion
12754 (save-restriction
12755 (widen)
12756 (goto-char pos)
12757 (if (org-in-regexp
12758 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12759 (replace-match ""))))))
12761 (defvar org-ts-type nil)
12762 (defun org-sparse-tree (&optional arg type)
12763 "Create a sparse tree, prompt for the details.
12764 This command can create sparse trees. You first need to select the type
12765 of match used to create the tree:
12767 t Show all TODO entries.
12768 T Show entries with a specific TODO keyword.
12769 m Show entries selected by a tags/property match.
12770 p Enter a property name and its value (both with completion on existing
12771 names/values) and show entries with that property.
12772 r Show entries matching a regular expression (`/' can be used as well).
12773 b Show deadlines and scheduled items before a date.
12774 a Show deadlines and scheduled items after a date.
12775 d Show deadlines due within `org-deadline-warning-days'.
12776 D Show deadlines and scheduled items between a date range."
12777 (interactive "P")
12778 (let (ans kwd value ts-type)
12779 (setq type (or type org-sparse-tree-default-date-type))
12780 (setq org-ts-type type)
12781 (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"
12782 (cond ((eq type 'all) "all timestamps")
12783 ((eq type 'scheduled) "only scheduled")
12784 ((eq type 'deadline) "only deadline")
12785 ((eq type 'active) "only active timestamps")
12786 ((eq type 'inactive) "only inactive timestamps")
12787 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12788 (t "scheduled/deadline")))
12789 (setq ans (read-char-exclusive))
12790 (cond
12791 ((equal ans ?c)
12792 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12793 ((equal ans ?d)
12794 (call-interactively 'org-check-deadlines))
12795 ((equal ans ?b)
12796 (call-interactively 'org-check-before-date))
12797 ((equal ans ?a)
12798 (call-interactively 'org-check-after-date))
12799 ((equal ans ?D)
12800 (call-interactively 'org-check-dates-range))
12801 ((equal ans ?t)
12802 (org-show-todo-tree nil))
12803 ((equal ans ?T)
12804 (org-show-todo-tree '(4)))
12805 ((member ans '(?T ?m))
12806 (call-interactively 'org-match-sparse-tree))
12807 ((member ans '(?p ?P))
12808 (setq kwd (org-icompleting-read "Property: "
12809 (mapcar 'list (org-buffer-property-keys))))
12810 (setq value (org-icompleting-read "Value: "
12811 (mapcar 'list (org-property-values kwd))))
12812 (unless (string-match "\\`{.*}\\'" value)
12813 (setq value (concat "\"" value "\"")))
12814 (org-match-sparse-tree arg (concat kwd "=" value)))
12815 ((member ans '(?r ?R ?/))
12816 (call-interactively 'org-occur))
12817 (t (error "No such sparse tree command \"%c\"" ans)))))
12819 (defvar org-occur-highlights nil
12820 "List of overlays used for occur matches.")
12821 (make-variable-buffer-local 'org-occur-highlights)
12822 (defvar org-occur-parameters nil
12823 "Parameters of the active org-occur calls.
12824 This is a list, each call to org-occur pushes as cons cell,
12825 containing the regular expression and the callback, onto the list.
12826 The list can contain several entries if `org-occur' has been called
12827 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12828 will only contain one set of parameters. When the highlights are
12829 removed (for example with `C-c C-c', or with the next edit (depending
12830 on `org-remove-highlights-with-change'), this variable is emptied
12831 as well.")
12832 (make-variable-buffer-local 'org-occur-parameters)
12834 (defun org-occur (regexp &optional keep-previous callback)
12835 "Make a compact tree which shows all matches of REGEXP.
12836 The tree will show the lines where the regexp matches, and all higher
12837 headlines above the match. It will also show the heading after the match,
12838 to make sure editing the matching entry is easy.
12839 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12840 call to `org-occur' will be kept, to allow stacking of calls to this
12841 command.
12842 If CALLBACK is non-nil, it is a function which is called to confirm
12843 that the match should indeed be shown."
12844 (interactive "sRegexp: \nP")
12845 (when (equal regexp "")
12846 (error "Regexp cannot be empty"))
12847 (unless keep-previous
12848 (org-remove-occur-highlights nil nil t))
12849 (push (cons regexp callback) org-occur-parameters)
12850 (let ((cnt 0))
12851 (save-excursion
12852 (goto-char (point-min))
12853 (if (or (not keep-previous) ; do not want to keep
12854 (not org-occur-highlights)) ; no previous matches
12855 ;; hide everything
12856 (org-overview))
12857 (while (re-search-forward regexp nil t)
12858 (when (or (not callback)
12859 (save-match-data (funcall callback)))
12860 (setq cnt (1+ cnt))
12861 (when org-highlight-sparse-tree-matches
12862 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12863 (org-show-context 'occur-tree))))
12864 (when org-remove-highlights-with-change
12865 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12866 nil 'local))
12867 (unless org-sparse-tree-open-archived-trees
12868 (org-hide-archived-subtrees (point-min) (point-max)))
12869 (run-hooks 'org-occur-hook)
12870 (if (org-called-interactively-p 'interactive)
12871 (message "%d match(es) for regexp %s" cnt regexp))
12872 cnt))
12874 (defun org-occur-next-match (&optional n reset)
12875 "Function for `next-error-function' to find sparse tree matches.
12876 N is the number of matches to move, when negative move backwards.
12877 RESET is entirely ignored - this function always goes back to the
12878 starting point when no match is found."
12879 (let* ((limit (if (< n 0) (point-min) (point-max)))
12880 (search-func (if (< n 0)
12881 'previous-single-char-property-change
12882 'next-single-char-property-change))
12883 (n (abs n))
12884 (pos (point))
12886 (catch 'exit
12887 (while (setq p1 (funcall search-func (point) 'org-type))
12888 (when (equal p1 limit)
12889 (goto-char pos)
12890 (error "No more matches"))
12891 (when (equal (get-char-property p1 'org-type) 'org-occur)
12892 (setq n (1- n))
12893 (when (= n 0)
12894 (goto-char p1)
12895 (throw 'exit (point))))
12896 (goto-char p1))
12897 (goto-char p1)
12898 (error "No more matches"))))
12900 (defun org-show-context (&optional key)
12901 "Make sure point and context are visible.
12902 How much context is shown depends upon the variables
12903 `org-show-hierarchy-above', `org-show-following-heading',
12904 `org-show-entry-below' and `org-show-siblings'."
12905 (let ((heading-p (org-at-heading-p t))
12906 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12907 (following-p (org-get-alist-option org-show-following-heading key))
12908 (entry-p (org-get-alist-option org-show-entry-below key))
12909 (siblings-p (org-get-alist-option org-show-siblings key)))
12910 (catch 'exit
12911 ;; Show heading or entry text
12912 (if (and heading-p (not entry-p))
12913 (org-flag-heading nil) ; only show the heading
12914 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12915 (org-show-hidden-entry))) ; show entire entry
12916 (when following-p
12917 ;; Show next sibling, or heading below text
12918 (save-excursion
12919 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12920 (org-flag-heading nil))))
12921 (when siblings-p (org-show-siblings))
12922 (when hierarchy-p
12923 ;; show all higher headings, possibly with siblings
12924 (save-excursion
12925 (while (and (condition-case nil
12926 (progn (org-up-heading-all 1) t)
12927 (error nil))
12928 (not (bobp)))
12929 (org-flag-heading nil)
12930 (when siblings-p (org-show-siblings))))))))
12932 (defvar org-reveal-start-hook nil
12933 "Hook run before revealing a location.")
12935 (defun org-reveal (&optional siblings)
12936 "Show current entry, hierarchy above it, and the following headline.
12937 This can be used to show a consistent set of context around locations
12938 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12939 not t for the search context.
12941 With optional argument SIBLINGS, on each level of the hierarchy all
12942 siblings are shown. This repairs the tree structure to what it would
12943 look like when opened with hierarchical calls to `org-cycle'.
12944 With double optional argument \\[universal-argument] \\[universal-argument], \
12945 go to the parent and show the
12946 entire tree."
12947 (interactive "P")
12948 (run-hooks 'org-reveal-start-hook)
12949 (let ((org-show-hierarchy-above t)
12950 (org-show-following-heading t)
12951 (org-show-siblings (if siblings t org-show-siblings)))
12952 (org-show-context nil))
12953 (when (equal siblings '(16))
12954 (save-excursion
12955 (when (org-up-heading-safe)
12956 (org-show-subtree)
12957 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12959 (defun org-highlight-new-match (beg end)
12960 "Highlight from BEG to END and mark the highlight is an occur headline."
12961 (let ((ov (make-overlay beg end)))
12962 (overlay-put ov 'face 'secondary-selection)
12963 (overlay-put ov 'org-type 'org-occur)
12964 (push ov org-occur-highlights)))
12966 (defun org-remove-occur-highlights (&optional beg end noremove)
12967 "Remove the occur highlights from the buffer.
12968 BEG and END are ignored. If NOREMOVE is nil, remove this function
12969 from the `before-change-functions' in the current buffer."
12970 (interactive)
12971 (unless org-inhibit-highlight-removal
12972 (mapc 'delete-overlay org-occur-highlights)
12973 (setq org-occur-highlights nil)
12974 (setq org-occur-parameters nil)
12975 (unless noremove
12976 (remove-hook 'before-change-functions
12977 'org-remove-occur-highlights 'local))))
12979 ;;;; Priorities
12981 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12982 "Regular expression matching the priority indicator.")
12984 (defvar org-remove-priority-next-time nil)
12986 (defun org-priority-up ()
12987 "Increase the priority of the current item."
12988 (interactive)
12989 (org-priority 'up))
12991 (defun org-priority-down ()
12992 "Decrease the priority of the current item."
12993 (interactive)
12994 (org-priority 'down))
12996 (defun org-priority (&optional action)
12997 "Change the priority of an item.
12998 ACTION can be `set', `up', `down', or a character."
12999 (interactive)
13000 (unless org-enable-priority-commands
13001 (error "Priority commands are disabled"))
13002 (setq action (or action 'set))
13003 (let (current new news have remove)
13004 (save-excursion
13005 (org-back-to-heading t)
13006 (if (looking-at org-priority-regexp)
13007 (setq current (string-to-char (match-string 2))
13008 have t))
13009 (cond
13010 ((eq action 'remove)
13011 (setq remove t new ?\ ))
13012 ((or (eq action 'set)
13013 (if (featurep 'xemacs) (characterp action) (integerp action)))
13014 (if (not (eq action 'set))
13015 (setq new action)
13016 (message "Priority %c-%c, SPC to remove: "
13017 org-highest-priority org-lowest-priority)
13018 (save-match-data
13019 (setq new (read-char-exclusive))))
13020 (if (and (= (upcase org-highest-priority) org-highest-priority)
13021 (= (upcase org-lowest-priority) org-lowest-priority))
13022 (setq new (upcase new)))
13023 (cond ((equal new ?\ ) (setq remove t))
13024 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13025 (error "Priority must be between `%c' and `%c'"
13026 org-highest-priority org-lowest-priority))))
13027 ((eq action 'up)
13028 (setq new (if have
13029 (1- current) ; normal cycling
13030 ;; last priority was empty
13031 (if (eq last-command this-command)
13032 org-lowest-priority ; wrap around empty to lowest
13033 ;; default
13034 (if org-priority-start-cycle-with-default
13035 org-default-priority
13036 (1- org-default-priority))))))
13037 ((eq action 'down)
13038 (setq new (if have
13039 (1+ current) ; normal cycling
13040 ;; last priority was empty
13041 (if (eq last-command this-command)
13042 org-highest-priority ; wrap around empty to highest
13043 ;; default
13044 (if org-priority-start-cycle-with-default
13045 org-default-priority
13046 (1+ org-default-priority))))))
13047 (t (error "Invalid action")))
13048 (if (or (< (upcase new) org-highest-priority)
13049 (> (upcase new) org-lowest-priority))
13050 (if (and (memq action '(up down))
13051 (not have) (not (eq last-command this-command)))
13052 ;; `new' is from default priority
13053 (error
13054 "The default can not be set, see `org-default-priority' why")
13055 ;; normal cycling: `new' is beyond highest/lowest priority
13056 ;; and is wrapped around to the empty priority
13057 (setq remove t)))
13058 (setq news (format "%c" new))
13059 (if have
13060 (if remove
13061 (replace-match "" t t nil 1)
13062 (replace-match news t t nil 2))
13063 (if remove
13064 (error "No priority cookie found in line")
13065 (let ((case-fold-search nil))
13066 (looking-at org-todo-line-regexp))
13067 (if (match-end 2)
13068 (progn
13069 (goto-char (match-end 2))
13070 (insert " [#" news "]"))
13071 (goto-char (match-beginning 3))
13072 (insert "[#" news "] "))))
13073 (org-preserve-lc (org-set-tags nil 'align)))
13074 (if remove
13075 (message "Priority removed")
13076 (message "Priority of current item set to %s" news))))
13078 (defun org-get-priority (s)
13079 "Find priority cookie and return priority."
13080 (if (functionp org-get-priority-function)
13081 (funcall org-get-priority-function)
13082 (save-match-data
13083 (if (not (string-match org-priority-regexp s))
13084 (* 1000 (- org-lowest-priority org-default-priority))
13085 (* 1000 (- org-lowest-priority
13086 (string-to-char (match-string 2 s))))))))
13088 ;;;; Tags
13090 (defvar org-agenda-archives-mode)
13091 (defvar org-map-continue-from nil
13092 "Position from where mapping should continue.
13093 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13095 (defvar org-scanner-tags nil
13096 "The current tag list while the tags scanner is running.")
13097 (defvar org-trust-scanner-tags nil
13098 "Should `org-get-tags-at' use the tags for the scanner.
13099 This is for internal dynamical scoping only.
13100 When this is non-nil, the function `org-get-tags-at' will return the value
13101 of `org-scanner-tags' instead of building the list by itself. This
13102 can lead to large speed-ups when the tags scanner is used in a file with
13103 many entries, and when the list of tags is retrieved, for example to
13104 obtain a list of properties. Building the tags list for each entry in such
13105 a file becomes an N^2 operation - but with this variable set, it scales
13106 as N.")
13108 (defun org-scan-tags (action matcher todo-only &optional start-level)
13109 "Scan headline tags with inheritance and produce output ACTION.
13111 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13112 or `agenda' to produce an entry list for an agenda view. It can also be
13113 a Lisp form or a function that should be called at each matched headline, in
13114 this case the return value is a list of all return values from these calls.
13116 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13117 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13118 only lines with a not-done TODO keyword are included in the output.
13119 This should be the same variable that was scoped into
13120 and set by `org-make-tags-matcher' when it constructed MATCHER.
13122 START-LEVEL can be a string with asterisks, reducing the scope to
13123 headlines matching this string."
13124 (require 'org-agenda)
13125 (let* ((re (concat "^"
13126 (if start-level
13127 ;; Get the correct level to match
13128 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13129 org-outline-regexp)
13130 " *\\(\\<\\("
13131 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13132 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13133 (props (list 'face 'default
13134 'done-face 'org-agenda-done
13135 'undone-face 'default
13136 'mouse-face 'highlight
13137 'org-not-done-regexp org-not-done-regexp
13138 'org-todo-regexp org-todo-regexp
13139 'org-complex-heading-regexp org-complex-heading-regexp
13140 'help-echo
13141 (format "mouse-2 or RET jump to org file %s"
13142 (abbreviate-file-name
13143 (or (buffer-file-name (buffer-base-buffer))
13144 (buffer-name (buffer-base-buffer)))))))
13145 (case-fold-search nil)
13146 (org-map-continue-from nil)
13147 lspos tags tags-list
13148 (tags-alist (list (cons 0 org-file-tags)))
13149 (llast 0) rtn rtn1 level category i txt
13150 todo marker entry priority)
13151 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13152 (setq action (list 'lambda nil action)))
13153 (save-excursion
13154 (goto-char (point-min))
13155 (when (eq action 'sparse-tree)
13156 (org-overview)
13157 (org-remove-occur-highlights))
13158 (while (re-search-forward re nil t)
13159 (setq org-map-continue-from nil)
13160 (catch :skip
13161 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13162 tags (if (match-end 4) (org-match-string-no-properties 4)))
13163 (goto-char (setq lspos (match-beginning 0)))
13164 (setq level (org-reduced-level (funcall outline-level))
13165 category (org-get-category))
13166 (setq i llast llast level)
13167 ;; remove tag lists from same and sublevels
13168 (while (>= i level)
13169 (when (setq entry (assoc i tags-alist))
13170 (setq tags-alist (delete entry tags-alist)))
13171 (setq i (1- i)))
13172 ;; add the next tags
13173 (when tags
13174 (setq tags (org-split-string tags ":")
13175 tags-alist
13176 (cons (cons level tags) tags-alist)))
13177 ;; compile tags for current headline
13178 (setq tags-list
13179 (if org-use-tag-inheritance
13180 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13181 tags)
13182 org-scanner-tags tags-list)
13183 (when org-use-tag-inheritance
13184 (setcdr (car tags-alist)
13185 (mapcar (lambda (x)
13186 (setq x (copy-sequence x))
13187 (org-add-prop-inherited x))
13188 (cdar tags-alist))))
13189 (when (and tags org-use-tag-inheritance
13190 (or (not (eq t org-use-tag-inheritance))
13191 org-tags-exclude-from-inheritance))
13192 ;; selective inheritance, remove uninherited ones
13193 (setcdr (car tags-alist)
13194 (org-remove-uninherited-tags (cdar tags-alist))))
13195 (when (and
13197 ;; eval matcher only when the todo condition is OK
13198 (and (or (not todo-only) (member todo org-not-done-keywords))
13199 (let ((case-fold-search t) (org-trust-scanner-tags t))
13200 (eval matcher)))
13202 ;; Call the skipper, but return t if it does not skip,
13203 ;; so that the `and' form continues evaluating
13204 (progn
13205 (unless (eq action 'sparse-tree) (org-agenda-skip))
13208 ;; Check if timestamps are deselecting this entry
13209 (or (not todo-only)
13210 (and (member todo org-not-done-keywords)
13211 (or (not org-agenda-tags-todo-honor-ignore-options)
13212 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13214 ;; Extra check for the archive tag
13215 ;; FIXME: Does the skipper already do this????
13217 (not (member org-archive-tag tags-list))
13218 ;; we have an archive tag, should we use this anyway?
13219 (or (not org-agenda-skip-archived-trees)
13220 (and (eq action 'agenda) org-agenda-archives-mode))))
13222 ;; select this headline
13224 (cond
13225 ((eq action 'sparse-tree)
13226 (and org-highlight-sparse-tree-matches
13227 (org-get-heading) (match-end 0)
13228 (org-highlight-new-match
13229 (match-beginning 1) (match-end 1)))
13230 (org-show-context 'tags-tree))
13231 ((eq action 'agenda)
13232 (setq txt (org-agenda-format-item
13234 (concat
13235 (if (eq org-tags-match-list-sublevels 'indented)
13236 (make-string (1- level) ?.) "")
13237 (org-get-heading))
13238 category
13239 tags-list)
13240 priority (org-get-priority txt))
13241 (goto-char lspos)
13242 (setq marker (org-agenda-new-marker))
13243 (org-add-props txt props
13244 'org-marker marker 'org-hd-marker marker 'org-category category
13245 'todo-state todo
13246 'priority priority 'type "tagsmatch")
13247 (push txt rtn))
13248 ((functionp action)
13249 (setq org-map-continue-from nil)
13250 (save-excursion
13251 (setq rtn1 (funcall action))
13252 (push rtn1 rtn)))
13253 (t (error "Invalid action")))
13255 ;; if we are to skip sublevels, jump to end of subtree
13256 (unless org-tags-match-list-sublevels
13257 (org-end-of-subtree t)
13258 (backward-char 1))))
13259 ;; Get the correct position from where to continue
13260 (if org-map-continue-from
13261 (goto-char org-map-continue-from)
13262 (and (= (point) lspos) (end-of-line 1)))))
13263 (when (and (eq action 'sparse-tree)
13264 (not org-sparse-tree-open-archived-trees))
13265 (org-hide-archived-subtrees (point-min) (point-max)))
13266 (nreverse rtn)))
13268 (defun org-remove-uninherited-tags (tags)
13269 "Remove all tags that are not inherited from the list TAGS."
13270 (cond
13271 ((eq org-use-tag-inheritance t)
13272 (if org-tags-exclude-from-inheritance
13273 (org-delete-all org-tags-exclude-from-inheritance tags)
13274 tags))
13275 ((not org-use-tag-inheritance) nil)
13276 ((stringp org-use-tag-inheritance)
13277 (delq nil (mapcar
13278 (lambda (x)
13279 (if (and (string-match org-use-tag-inheritance x)
13280 (not (member x org-tags-exclude-from-inheritance)))
13281 x nil))
13282 tags)))
13283 ((listp org-use-tag-inheritance)
13284 (delq nil (mapcar
13285 (lambda (x)
13286 (if (member x org-use-tag-inheritance) x nil))
13287 tags)))))
13289 (defun org-match-sparse-tree (&optional todo-only match)
13290 "Create a sparse tree according to tags string MATCH.
13291 MATCH can contain positive and negative selection of tags, like
13292 \"+WORK+URGENT-WITHBOSS\".
13293 If optional argument TODO-ONLY is non-nil, only select lines that are
13294 also TODO lines."
13295 (interactive "P")
13296 (org-agenda-prepare-buffers (list (current-buffer)))
13297 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13299 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13301 (defvar org-cached-props nil)
13302 (defun org-cached-entry-get (pom property)
13303 (if (or (eq t org-use-property-inheritance)
13304 (and (stringp org-use-property-inheritance)
13305 (string-match org-use-property-inheritance property))
13306 (and (listp org-use-property-inheritance)
13307 (member property org-use-property-inheritance)))
13308 ;; Caching is not possible, check it directly
13309 (org-entry-get pom property 'inherit)
13310 ;; Get all properties, so that we can do complicated checks easily
13311 (cdr (assoc property (or org-cached-props
13312 (setq org-cached-props
13313 (org-entry-properties pom)))))))
13315 (defun org-global-tags-completion-table (&optional files)
13316 "Return the list of all tags in all agenda buffer/files.
13317 Optional FILES argument is a list of files which can be used
13318 instead of the agenda files."
13319 (save-excursion
13320 (org-uniquify
13321 (delq nil
13322 (apply 'append
13323 (mapcar
13324 (lambda (file)
13325 (set-buffer (find-file-noselect file))
13326 (append (org-get-buffer-tags)
13327 (mapcar (lambda (x) (if (stringp (car-safe x))
13328 (list (car-safe x)) nil))
13329 org-tag-alist)))
13330 (if (and files (car files))
13331 files
13332 (org-agenda-files))))))))
13334 (defun org-make-tags-matcher (match)
13335 "Create the TAGS/TODO matcher form for the selection string MATCH.
13337 The variable `todo-only' is scoped dynamically into this function.
13338 It will be set to t if the matcher restricts matching to TODO entries,
13339 otherwise will not be touched.
13341 Returns a cons of the selection string MATCH and the constructed
13342 lisp form implementing the matcher. The matcher is to be evaluated
13343 at an Org entry, with point on the headline, and returns t if the
13344 entry matches the selection string MATCH. The returned lisp form
13345 references two variables with information about the entry, which
13346 must be bound around the form's evaluation: todo, the TODO keyword
13347 at the entry (or nil of none); and tags-list, the list of all tags
13348 at the entry including inherited ones. Additionally, the category
13349 of the entry (if any) must be specified as the text property
13350 'org-category on the headline.
13352 See also `org-scan-tags'.
13354 (declare (special todo-only))
13355 (unless (boundp 'todo-only)
13356 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13357 (unless match
13358 ;; Get a new match request, with completion
13359 (let ((org-last-tags-completion-table
13360 (org-global-tags-completion-table)))
13361 (setq match (org-completing-read-no-i
13362 "Match: " 'org-tags-completion-function nil nil nil
13363 'org-tags-history))))
13365 ;; Parse the string and create a lisp form
13366 (let ((match0 match)
13367 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13368 minus tag mm
13369 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13370 orterms term orlist re-p str-p level-p level-op time-p
13371 prop-p pn pv po gv rest)
13372 (if (string-match "/+" match)
13373 ;; match contains also a todo-matching request
13374 (progn
13375 (setq tagsmatch (substring match 0 (match-beginning 0))
13376 todomatch (substring match (match-end 0)))
13377 (if (string-match "^!" todomatch)
13378 (setq todo-only t todomatch (substring todomatch 1)))
13379 (if (string-match "^\\s-*$" todomatch)
13380 (setq todomatch nil)))
13381 ;; only matching tags
13382 (setq tagsmatch match todomatch nil))
13384 ;; Make the tags matcher
13385 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13386 (setq tagsmatcher t)
13387 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13388 (while (setq term (pop orterms))
13389 (while (and (equal (substring term -1) "\\") orterms)
13390 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13391 (while (string-match re term)
13392 (setq rest (substring term (match-end 0))
13393 minus (and (match-end 1)
13394 (equal (match-string 1 term) "-"))
13395 tag (save-match-data (replace-regexp-in-string
13396 "\\\\-" "-"
13397 (match-string 2 term)))
13398 re-p (equal (string-to-char tag) ?{)
13399 level-p (match-end 4)
13400 prop-p (match-end 5)
13401 mm (cond
13402 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13403 (level-p
13404 (setq level-op (org-op-to-function (match-string 3 term)))
13405 `(,level-op level ,(string-to-number
13406 (match-string 4 term))))
13407 (prop-p
13408 (setq pn (match-string 5 term)
13409 po (match-string 6 term)
13410 pv (match-string 7 term)
13411 re-p (equal (string-to-char pv) ?{)
13412 str-p (equal (string-to-char pv) ?\")
13413 time-p (save-match-data
13414 (string-match "^\"[[<].*[]>]\"$" pv))
13415 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13416 (if time-p (setq pv (org-matcher-time pv)))
13417 (setq po (org-op-to-function po (if time-p 'time str-p)))
13418 (cond
13419 ((equal pn "CATEGORY")
13420 (setq gv '(get-text-property (point) 'org-category)))
13421 ((equal pn "TODO")
13422 (setq gv 'todo))
13424 (setq gv `(org-cached-entry-get nil ,pn))))
13425 (if re-p
13426 (if (eq po 'org<>)
13427 `(not (string-match ,pv (or ,gv "")))
13428 `(string-match ,pv (or ,gv "")))
13429 (if str-p
13430 `(,po (or ,gv "") ,pv)
13431 `(,po (string-to-number (or ,gv ""))
13432 ,(string-to-number pv) ))))
13433 (t `(member ,tag tags-list)))
13434 mm (if minus (list 'not mm) mm)
13435 term rest)
13436 (push mm tagsmatcher))
13437 (push (if (> (length tagsmatcher) 1)
13438 (cons 'and tagsmatcher)
13439 (car tagsmatcher))
13440 orlist)
13441 (setq tagsmatcher nil))
13442 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13443 (setq tagsmatcher
13444 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13445 ;; Make the todo matcher
13446 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13447 (setq todomatcher t)
13448 (setq orterms (org-split-string todomatch "|") orlist nil)
13449 (while (setq term (pop orterms))
13450 (while (string-match re term)
13451 (setq minus (and (match-end 1)
13452 (equal (match-string 1 term) "-"))
13453 kwd (match-string 2 term)
13454 re-p (equal (string-to-char kwd) ?{)
13455 term (substring term (match-end 0))
13456 mm (if re-p
13457 `(string-match ,(substring kwd 1 -1) todo)
13458 (list 'equal 'todo kwd))
13459 mm (if minus (list 'not mm) mm))
13460 (push mm todomatcher))
13461 (push (if (> (length todomatcher) 1)
13462 (cons 'and todomatcher)
13463 (car todomatcher))
13464 orlist)
13465 (setq todomatcher nil))
13466 (setq todomatcher (if (> (length orlist) 1)
13467 (cons 'or orlist) (car orlist))))
13469 ;; Return the string and lisp forms of the matcher
13470 (setq matcher (if todomatcher
13471 (list 'and tagsmatcher todomatcher)
13472 tagsmatcher))
13473 (when todo-only
13474 (setq matcher (list 'and '(member todo org-not-done-keywords)
13475 matcher)))
13476 (cons match0 matcher)))
13478 (defun org-op-to-function (op &optional stringp)
13479 "Turn an operator into the appropriate function."
13480 (setq op
13481 (cond
13482 ((equal op "<" ) '(< string< org-time<))
13483 ((equal op ">" ) '(> org-string> org-time>))
13484 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13485 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13486 ((member op '("=" "==")) '(= string= org-time=))
13487 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13488 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13490 (defun org<> (a b) (not (= a b)))
13491 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13492 (defun org-string>= (a b) (not (string< a b)))
13493 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13494 (defun org-string<> (a b) (not (string= a b)))
13495 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13496 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13497 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13498 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> 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) (org<> a b)))
13501 (defun org-2ft (s)
13502 "Convert S to a floating point time.
13503 If S is already a number, just return it. If it is a string, parse
13504 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13505 (cond
13506 ((numberp s) s)
13507 ((stringp s)
13508 (condition-case nil
13509 (float-time (apply 'encode-time (org-parse-time-string s)))
13510 (error 0.)))
13511 (t 0.)))
13513 (defun org-time-today ()
13514 "Time in seconds today at 0:00.
13515 Returns the float number of seconds since the beginning of the
13516 epoch to the beginning of today (00:00)."
13517 (float-time (apply 'encode-time
13518 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13520 (defun org-matcher-time (s)
13521 "Interpret a time comparison value."
13522 (save-match-data
13523 (cond
13524 ((string= s "<now>") (float-time))
13525 ((string= s "<today>") (org-time-today))
13526 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13527 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13528 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13529 (+ (org-time-today)
13530 (* (string-to-number (match-string 1 s))
13531 (cdr (assoc (match-string 2 s)
13532 '(("d" . 86400.0) ("w" . 604800.0)
13533 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13534 (t (org-2ft s)))))
13536 (defun org-match-any-p (re list)
13537 "Does re match any element of list?"
13538 (setq list (mapcar (lambda (x) (string-match re x)) list))
13539 (delq nil list))
13541 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13542 (defvar org-tags-overlay (make-overlay 1 1))
13543 (org-detach-overlay org-tags-overlay)
13545 (defun org-get-local-tags-at (&optional pos)
13546 "Get a list of tags defined in the current headline."
13547 (org-get-tags-at pos 'local))
13549 (defun org-get-local-tags ()
13550 "Get a list of tags defined in the current headline."
13551 (org-get-tags-at nil 'local))
13553 (defun org-get-tags-at (&optional pos local)
13554 "Get a list of all headline tags applicable at POS.
13555 POS defaults to point. If tags are inherited, the list contains
13556 the targets in the same sequence as the headlines appear, i.e.
13557 the tags of the current headline come last.
13558 When LOCAL is non-nil, only return tags from the current headline,
13559 ignore inherited ones."
13560 (interactive)
13561 (if (and org-trust-scanner-tags
13562 (or (not pos) (equal pos (point)))
13563 (not local))
13564 org-scanner-tags
13565 (let (tags ltags lastpos parent)
13566 (save-excursion
13567 (save-restriction
13568 (widen)
13569 (goto-char (or pos (point)))
13570 (save-match-data
13571 (catch 'done
13572 (condition-case nil
13573 (progn
13574 (org-back-to-heading t)
13575 (while (not (equal lastpos (point)))
13576 (setq lastpos (point))
13577 (when (looking-at
13578 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13579 (setq ltags (org-split-string
13580 (org-match-string-no-properties 1) ":"))
13581 (when parent
13582 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13583 (setq tags (append
13584 (if parent
13585 (org-remove-uninherited-tags ltags)
13586 ltags)
13587 tags)))
13588 (or org-use-tag-inheritance (throw 'done t))
13589 (if local (throw 'done t))
13590 (or (org-up-heading-safe) (error nil))
13591 (setq parent t)))
13592 (error nil)))))
13593 (if local
13594 tags
13595 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13597 (defun org-add-prop-inherited (s)
13598 (add-text-properties 0 (length s) '(inherited t) s)
13601 (defun org-toggle-tag (tag &optional onoff)
13602 "Toggle the tag TAG for the current line.
13603 If ONOFF is `on' or `off', don't toggle but set to this state."
13604 (let (res current)
13605 (save-excursion
13606 (org-back-to-heading t)
13607 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13608 (point-at-eol) t)
13609 (progn
13610 (setq current (match-string 1))
13611 (replace-match ""))
13612 (setq current ""))
13613 (setq current (nreverse (org-split-string current ":")))
13614 (cond
13615 ((eq onoff 'on)
13616 (setq res t)
13617 (or (member tag current) (push tag current)))
13618 ((eq onoff 'off)
13619 (or (not (member tag current)) (setq current (delete tag current))))
13620 (t (if (member tag current)
13621 (setq current (delete tag current))
13622 (setq res t)
13623 (push tag current))))
13624 (end-of-line 1)
13625 (if current
13626 (progn
13627 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13628 (org-set-tags nil t))
13629 (delete-horizontal-space))
13630 (run-hooks 'org-after-tags-change-hook))
13631 res))
13633 (defun org-align-tags-here (to-col)
13634 ;; Assumes that this is a headline
13635 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13636 (beginning-of-line 1)
13637 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13638 (< pos (match-beginning 2)))
13639 (progn
13640 (setq tags-l (- (match-end 2) (match-beginning 2)))
13641 (goto-char (match-beginning 1))
13642 (insert " ")
13643 (delete-region (point) (1+ (match-beginning 2)))
13644 (setq ncol (max (current-column)
13645 (1+ col)
13646 (if (> to-col 0)
13647 to-col
13648 (- (abs to-col) tags-l))))
13649 (setq p (point))
13650 (insert (make-string (- ncol (current-column)) ?\ ))
13651 (setq ncol (current-column))
13652 (when indent-tabs-mode (tabify p (point-at-eol)))
13653 (org-move-to-column (min ncol col) t))
13654 (goto-char pos))))
13656 (defun org-set-tags-command (&optional arg just-align)
13657 "Call the set-tags command for the current entry."
13658 (interactive "P")
13659 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13660 (org-set-tags arg just-align)
13661 (save-excursion
13662 (org-back-to-heading t)
13663 (org-set-tags arg just-align))))
13665 (defun org-set-tags-to (data)
13666 "Set the tags of the current entry to DATA, replacing the current tags.
13667 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13668 If DATA is nil or the empty string, any tags will be removed."
13669 (interactive "sTags: ")
13670 (setq data
13671 (cond
13672 ((eq data nil) "")
13673 ((equal data "") "")
13674 ((stringp data)
13675 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13676 ":"))
13677 ((listp data)
13678 (concat ":" (mapconcat 'identity data ":") ":"))))
13679 (when data
13680 (save-excursion
13681 (org-back-to-heading t)
13682 (when (looking-at org-complex-heading-regexp)
13683 (if (match-end 5)
13684 (progn
13685 (goto-char (match-beginning 5))
13686 (insert data)
13687 (delete-region (point) (point-at-eol))
13688 (org-set-tags nil 'align))
13689 (goto-char (point-at-eol))
13690 (insert " " data)
13691 (org-set-tags nil 'align)))
13692 (beginning-of-line 1)
13693 (if (looking-at ".*?\\([ \t]+\\)$")
13694 (delete-region (match-beginning 1) (match-end 1))))))
13696 (defun org-align-all-tags ()
13697 "Align the tags i all headings."
13698 (interactive)
13699 (save-excursion
13700 (or (ignore-errors (org-back-to-heading t))
13701 (outline-next-heading))
13702 (if (org-at-heading-p)
13703 (org-set-tags t)
13704 (message "No headings"))))
13706 (defvar org-indent-indentation-per-level)
13707 (defun org-set-tags (&optional arg just-align)
13708 "Set the tags for the current headline.
13709 With prefix ARG, realign all tags in headings in the current buffer."
13710 (interactive "P")
13711 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13712 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13713 'region-start-level 'region))
13714 org-loop-over-headlines-in-active-region)
13715 (org-map-entries
13716 ;; We don't use ARG and JUST-ALIGN here these args are not
13717 ;; useful when looping over headlines
13718 `(org-set-tags)
13719 org-loop-over-headlines-in-active-region
13720 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13721 (let* ((re org-outline-regexp-bol)
13722 (current (unless arg (org-get-tags-string)))
13723 (col (current-column))
13724 (org-setting-tags t)
13725 table current-tags inherited-tags ; computed below when needed
13726 tags p0 c0 c1 rpl di tc level)
13727 (if arg
13728 (save-excursion
13729 (goto-char (point-min))
13730 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13731 (while (re-search-forward re nil t)
13732 (org-set-tags nil t)
13733 (end-of-line 1)))
13734 (message "All tags realigned to column %d" org-tags-column))
13735 (if just-align
13736 (setq tags current)
13737 ;; Get a new set of tags from the user
13738 (save-excursion
13739 (setq table (append org-tag-persistent-alist
13740 (or org-tag-alist (org-get-buffer-tags))
13741 (and
13742 org-complete-tags-always-offer-all-agenda-tags
13743 (org-global-tags-completion-table
13744 (org-agenda-files))))
13745 org-last-tags-completion-table table
13746 current-tags (org-split-string current ":")
13747 inherited-tags (nreverse
13748 (nthcdr (length current-tags)
13749 (nreverse (org-get-tags-at))))
13750 tags
13751 (if (or (eq t org-use-fast-tag-selection)
13752 (and org-use-fast-tag-selection
13753 (delq nil (mapcar 'cdr table))))
13754 (org-fast-tag-selection
13755 current-tags inherited-tags table
13756 (if org-fast-tag-selection-include-todo
13757 org-todo-key-alist))
13758 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13759 (org-trim
13760 (org-icompleting-read "Tags: "
13761 'org-tags-completion-function
13762 nil nil current 'org-tags-history))))))
13763 (while (string-match "[-+&]+" tags)
13764 ;; No boolean logic, just a list
13765 (setq tags (replace-match ":" t t tags))))
13767 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13769 (if org-tags-sort-function
13770 (setq tags (mapconcat 'identity
13771 (sort (org-split-string
13772 tags (org-re "[^[:alnum:]_@#%]+"))
13773 org-tags-sort-function) ":")))
13775 (if (string-match "\\`[\t ]*\\'" tags)
13776 (setq tags "")
13777 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13778 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13780 ;; Insert new tags at the correct column
13781 (beginning-of-line 1)
13782 (setq level (or (and (looking-at org-outline-regexp)
13783 (- (match-end 0) (point) 1))
13785 (cond
13786 ((and (equal current "") (equal tags "")))
13787 ((re-search-forward
13788 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13789 (point-at-eol) t)
13790 (if (equal tags "")
13791 (setq rpl "")
13792 (goto-char (match-beginning 0))
13793 (setq c0 (current-column)
13794 ;; compute offset for the case of org-indent-mode active
13795 di (if org-indent-mode
13796 (* (1- org-indent-indentation-per-level) (1- level))
13798 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13799 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13800 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13801 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13802 (replace-match rpl t t)
13803 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13804 tags)
13805 (t (error "Tags alignment failed")))
13806 (org-move-to-column col)
13807 (unless just-align
13808 (run-hooks 'org-after-tags-change-hook))))))
13810 (defun org-change-tag-in-region (beg end tag off)
13811 "Add or remove TAG for each entry in the region.
13812 This works in the agenda, and also in an org-mode buffer."
13813 (interactive
13814 (list (region-beginning) (region-end)
13815 (let ((org-last-tags-completion-table
13816 (if (derived-mode-p 'org-mode)
13817 (org-get-buffer-tags)
13818 (org-global-tags-completion-table))))
13819 (org-icompleting-read
13820 "Tag: " 'org-tags-completion-function nil nil nil
13821 'org-tags-history))
13822 (progn
13823 (message "[s]et or [r]emove? ")
13824 (equal (read-char-exclusive) ?r))))
13825 (if (fboundp 'deactivate-mark) (deactivate-mark))
13826 (let ((agendap (equal major-mode 'org-agenda-mode))
13827 l1 l2 m buf pos newhead (cnt 0))
13828 (goto-char end)
13829 (setq l2 (1- (org-current-line)))
13830 (goto-char beg)
13831 (setq l1 (org-current-line))
13832 (loop for l from l1 to l2 do
13833 (org-goto-line l)
13834 (setq m (get-text-property (point) 'org-hd-marker))
13835 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13836 (and agendap m))
13837 (setq buf (if agendap (marker-buffer m) (current-buffer))
13838 pos (if agendap m (point)))
13839 (with-current-buffer buf
13840 (save-excursion
13841 (save-restriction
13842 (goto-char pos)
13843 (setq cnt (1+ cnt))
13844 (org-toggle-tag tag (if off 'off 'on))
13845 (setq newhead (org-get-heading)))))
13846 (and agendap (org-agenda-change-all-lines newhead m))))
13847 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13849 (defun org-tags-completion-function (string predicate &optional flag)
13850 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13851 (confirm (lambda (x) (stringp (car x)))))
13852 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13853 (setq s1 (match-string 1 string)
13854 s2 (match-string 2 string))
13855 (setq s1 "" s2 string))
13856 (cond
13857 ((eq flag nil)
13858 ;; try completion
13859 (setq rtn (try-completion s2 ctable confirm))
13860 (if (stringp rtn)
13861 (setq rtn
13862 (concat s1 s2 (substring rtn (length s2))
13863 (if (and org-add-colon-after-tag-completion
13864 (assoc rtn ctable))
13865 ":" ""))))
13866 rtn)
13867 ((eq flag t)
13868 ;; all-completions
13869 (all-completions s2 ctable confirm)
13871 ((eq flag 'lambda)
13872 ;; exact match?
13873 (assoc s2 ctable)))
13876 (defun org-fast-tag-insert (kwd tags face &optional end)
13877 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13878 (insert (format "%-12s" (concat kwd ":"))
13879 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13880 (or end "")))
13882 (defun org-fast-tag-show-exit (flag)
13883 (save-excursion
13884 (org-goto-line 3)
13885 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13886 (replace-match ""))
13887 (when flag
13888 (end-of-line 1)
13889 (org-move-to-column (- (window-width) 19) t)
13890 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13892 (defun org-set-current-tags-overlay (current prefix)
13893 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13894 (if (featurep 'xemacs)
13895 (org-overlay-display org-tags-overlay (concat prefix s)
13896 'secondary-selection)
13897 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13898 (org-overlay-display org-tags-overlay (concat prefix s)))))
13900 (defvar org-last-tag-selection-key nil)
13901 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13902 "Fast tag selection with single keys.
13903 CURRENT is the current list of tags in the headline, INHERITED is the
13904 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13905 possibly with grouping information. TODO-TABLE is a similar table with
13906 TODO keywords, should these have keys assigned to them.
13907 If the keys are nil, a-z are automatically assigned.
13908 Returns the new tags string, or nil to not change the current settings."
13909 (let* ((fulltable (append table todo-table))
13910 (maxlen (apply 'max (mapcar
13911 (lambda (x)
13912 (if (stringp (car x)) (string-width (car x)) 0))
13913 fulltable)))
13914 (buf (current-buffer))
13915 (expert (eq org-fast-tag-selection-single-key 'expert))
13916 (buffer-tags nil)
13917 (fwidth (+ maxlen 3 1 3))
13918 (ncol (/ (- (window-width) 4) fwidth))
13919 (i-face 'org-done)
13920 (c-face 'org-todo)
13921 tg cnt e c char c1 c2 ntable tbl rtn
13922 ov-start ov-end ov-prefix
13923 (exit-after-next org-fast-tag-selection-single-key)
13924 (done-keywords org-done-keywords)
13925 groups ingroup)
13926 (save-excursion
13927 (beginning-of-line 1)
13928 (if (looking-at
13929 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13930 (setq ov-start (match-beginning 1)
13931 ov-end (match-end 1)
13932 ov-prefix "")
13933 (setq ov-start (1- (point-at-eol))
13934 ov-end (1+ ov-start))
13935 (skip-chars-forward "^\n\r")
13936 (setq ov-prefix
13937 (concat
13938 (buffer-substring (1- (point)) (point))
13939 (if (> (current-column) org-tags-column)
13941 (make-string (- org-tags-column (current-column)) ?\ ))))))
13942 (move-overlay org-tags-overlay ov-start ov-end)
13943 (save-window-excursion
13944 (if expert
13945 (set-buffer (get-buffer-create " *Org tags*"))
13946 (delete-other-windows)
13947 (split-window-vertically)
13948 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13949 (erase-buffer)
13950 (org-set-local 'org-done-keywords done-keywords)
13951 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13952 (org-fast-tag-insert "Current" current c-face "\n\n")
13953 (org-fast-tag-show-exit exit-after-next)
13954 (org-set-current-tags-overlay current ov-prefix)
13955 (setq tbl fulltable char ?a cnt 0)
13956 (while (setq e (pop tbl))
13957 (cond
13958 ((equal (car e) :startgroup)
13959 (push '() groups) (setq ingroup t)
13960 (when (not (= cnt 0))
13961 (setq cnt 0)
13962 (insert "\n"))
13963 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13964 ((equal (car e) :endgroup)
13965 (setq ingroup nil cnt 0)
13966 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13967 ((equal e '(:newline))
13968 (when (not (= cnt 0))
13969 (setq cnt 0)
13970 (insert "\n")
13971 (setq e (car tbl))
13972 (while (equal (car tbl) '(:newline))
13973 (insert "\n")
13974 (setq tbl (cdr tbl)))))
13976 (setq tg (copy-sequence (car e)) c2 nil)
13977 (if (cdr e)
13978 (setq c (cdr e))
13979 ;; automatically assign a character.
13980 (setq c1 (string-to-char
13981 (downcase (substring
13982 tg (if (= (string-to-char tg) ?@) 1 0)))))
13983 (if (or (rassoc c1 ntable) (rassoc c1 table))
13984 (while (or (rassoc char ntable) (rassoc char table))
13985 (setq char (1+ char)))
13986 (setq c2 c1))
13987 (setq c (or c2 char)))
13988 (if ingroup (push tg (car groups)))
13989 (setq tg (org-add-props tg nil 'face
13990 (cond
13991 ((not (assoc tg table))
13992 (org-get-todo-face tg))
13993 ((member tg current) c-face)
13994 ((member tg inherited) i-face))))
13995 (if (and (= cnt 0) (not ingroup)) (insert " "))
13996 (insert "[" c "] " tg (make-string
13997 (- fwidth 4 (length tg)) ?\ ))
13998 (push (cons tg c) ntable)
13999 (when (= (setq cnt (1+ cnt)) ncol)
14000 (insert "\n")
14001 (if ingroup (insert " "))
14002 (setq cnt 0)))))
14003 (setq ntable (nreverse ntable))
14004 (insert "\n")
14005 (goto-char (point-min))
14006 (if (not expert) (org-fit-window-to-buffer))
14007 (setq rtn
14008 (catch 'exit
14009 (while t
14010 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14011 (if (not groups) "no " "")
14012 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14013 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14014 (setq org-last-tag-selection-key c)
14015 (cond
14016 ((= c ?\r) (throw 'exit t))
14017 ((= c ?!)
14018 (setq groups (not groups))
14019 (goto-char (point-min))
14020 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14021 ((= c ?\C-c)
14022 (if (not expert)
14023 (org-fast-tag-show-exit
14024 (setq exit-after-next (not exit-after-next)))
14025 (setq expert nil)
14026 (delete-other-windows)
14027 (set-window-buffer (split-window-vertically) " *Org tags*")
14028 (org-switch-to-buffer-other-window " *Org tags*")
14029 (org-fit-window-to-buffer)))
14030 ((or (= c ?\C-g)
14031 (and (= c ?q) (not (rassoc c ntable))))
14032 (org-detach-overlay org-tags-overlay)
14033 (setq quit-flag t))
14034 ((= c ?\ )
14035 (setq current nil)
14036 (if exit-after-next (setq exit-after-next 'now)))
14037 ((= c ?\t)
14038 (condition-case nil
14039 (setq tg (org-icompleting-read
14040 "Tag: "
14041 (or buffer-tags
14042 (with-current-buffer buf
14043 (org-get-buffer-tags)))))
14044 (quit (setq tg "")))
14045 (when (string-match "\\S-" tg)
14046 (add-to-list 'buffer-tags (list tg))
14047 (if (member tg current)
14048 (setq current (delete tg current))
14049 (push tg current)))
14050 (if exit-after-next (setq exit-after-next 'now)))
14051 ((setq e (rassoc c todo-table) tg (car e))
14052 (with-current-buffer buf
14053 (save-excursion (org-todo tg)))
14054 (if exit-after-next (setq exit-after-next 'now)))
14055 ((setq e (rassoc c ntable) tg (car e))
14056 (if (member tg current)
14057 (setq current (delete tg current))
14058 (loop for g in groups do
14059 (if (member tg g)
14060 (mapc (lambda (x)
14061 (setq current (delete x current)))
14062 g)))
14063 (push tg current))
14064 (if exit-after-next (setq exit-after-next 'now))))
14066 ;; Create a sorted list
14067 (setq current
14068 (sort current
14069 (lambda (a b)
14070 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14071 (if (eq exit-after-next 'now) (throw 'exit t))
14072 (goto-char (point-min))
14073 (beginning-of-line 2)
14074 (delete-region (point) (point-at-eol))
14075 (org-fast-tag-insert "Current" current c-face)
14076 (org-set-current-tags-overlay current ov-prefix)
14077 (while (re-search-forward
14078 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14079 (setq tg (match-string 1))
14080 (add-text-properties
14081 (match-beginning 1) (match-end 1)
14082 (list 'face
14083 (cond
14084 ((member tg current) c-face)
14085 ((member tg inherited) i-face)
14086 (t (get-text-property (match-beginning 1) 'face))))))
14087 (goto-char (point-min)))))
14088 (org-detach-overlay org-tags-overlay)
14089 (if rtn
14090 (mapconcat 'identity current ":")
14091 nil))))
14093 (defun org-get-tags-string ()
14094 "Get the TAGS string in the current headline."
14095 (unless (org-at-heading-p t)
14096 (error "Not on a heading"))
14097 (save-excursion
14098 (beginning-of-line 1)
14099 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14100 (org-match-string-no-properties 1)
14101 "")))
14103 (defun org-get-tags ()
14104 "Get the list of tags specified in the current headline."
14105 (org-split-string (org-get-tags-string) ":"))
14107 (defun org-get-buffer-tags ()
14108 "Get a table of all tags used in the buffer, for completion."
14109 (let (tags)
14110 (save-excursion
14111 (goto-char (point-min))
14112 (while (re-search-forward
14113 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14114 (when (equal (char-after (point-at-bol 0)) ?*)
14115 (mapc (lambda (x) (add-to-list 'tags x))
14116 (org-split-string (org-match-string-no-properties 1) ":")))))
14117 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14118 (mapcar 'list tags)))
14120 ;;;; The mapping API
14122 ;;;###autoload
14123 (defun org-map-entries (func &optional match scope &rest skip)
14124 "Call FUNC at each headline selected by MATCH in SCOPE.
14126 FUNC is a function or a lisp form. The function will be called without
14127 arguments, with the cursor positioned at the beginning of the headline.
14128 The return values of all calls to the function will be collected and
14129 returned as a list.
14131 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14132 does not need to preserve point. After evaluation, the cursor will be
14133 moved to the end of the line (presumably of the headline of the
14134 processed entry) and search continues from there. Under some
14135 circumstances, this may not produce the wanted results. For example,
14136 if you have removed (e.g. archived) the current (sub)tree it could
14137 mean that the next entry will be skipped entirely. In such cases, you
14138 can specify the position from where search should continue by making
14139 FUNC set the variable `org-map-continue-from' to the desired buffer
14140 position.
14142 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14143 Only headlines that are matched by this query will be considered during
14144 the iteration. When MATCH is nil or t, all headlines will be
14145 visited by the iteration.
14147 SCOPE determines the scope of this command. It can be any of:
14149 nil The current buffer, respecting the restriction if any
14150 tree The subtree started with the entry at point
14151 region The entries within the active region, if any
14152 region-start-level
14153 The entries within the active region, but only those at
14154 the same level than the first one.
14155 file The current buffer, without restriction
14156 file-with-archives
14157 The current buffer, and any archives associated with it
14158 agenda All agenda files
14159 agenda-with-archives
14160 All agenda files with any archive files associated with them
14161 \(file1 file2 ...)
14162 If this is a list, all files in the list will be scanned
14164 The remaining args are treated as settings for the skipping facilities of
14165 the scanner. The following items can be given here:
14167 archive skip trees with the archive tag.
14168 comment skip trees with the COMMENT keyword
14169 function or Emacs Lisp form:
14170 will be used as value for `org-agenda-skip-function', so whenever
14171 the function returns t, FUNC will not be called for that
14172 entry and search will continue from the point where the
14173 function leaves it.
14175 If your function needs to retrieve the tags including inherited tags
14176 at the *current* entry, you can use the value of the variable
14177 `org-scanner-tags' which will be much faster than getting the value
14178 with `org-get-tags-at'. If your function gets properties with
14179 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14180 to t around the call to `org-entry-properties' to get the same speedup.
14181 Note that if your function moves around to retrieve tags and properties at
14182 a *different* entry, you cannot use these techniques."
14183 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14184 (not (org-region-active-p)))
14185 (let* ((org-agenda-archives-mode nil) ; just to make sure
14186 (org-agenda-skip-archived-trees (memq 'archive skip))
14187 (org-agenda-skip-comment-trees (memq 'comment skip))
14188 (org-agenda-skip-function
14189 (car (org-delete-all '(comment archive) skip)))
14190 (org-tags-match-list-sublevels t)
14191 (start-level (eq scope 'region-start-level))
14192 matcher file res
14193 org-todo-keywords-for-agenda
14194 org-done-keywords-for-agenda
14195 org-todo-keyword-alist-for-agenda
14196 org-drawers-for-agenda
14197 org-tag-alist-for-agenda
14198 todo-only)
14200 (cond
14201 ((eq match t) (setq matcher t))
14202 ((eq match nil) (setq matcher t))
14203 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14205 (save-excursion
14206 (save-restriction
14207 (cond ((eq scope 'tree)
14208 (org-back-to-heading t)
14209 (org-narrow-to-subtree)
14210 (setq scope nil))
14211 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14212 (org-region-active-p))
14213 ;; If needed, set start-level to a string like "2"
14214 (when start-level
14215 (save-excursion
14216 (goto-char (region-beginning))
14217 (unless (org-at-heading-p) (outline-next-heading))
14218 (setq start-level (org-current-level))))
14219 (narrow-to-region (region-beginning)
14220 (save-excursion
14221 (goto-char (region-end))
14222 (unless (and (bolp) (org-at-heading-p))
14223 (outline-next-heading))
14224 (point)))
14225 (setq scope nil)))
14227 (if (not scope)
14228 (progn
14229 (org-agenda-prepare-buffers
14230 (list (buffer-file-name (current-buffer))))
14231 (setq res (org-scan-tags func matcher todo-only start-level)))
14232 ;; Get the right scope
14233 (cond
14234 ((and scope (listp scope) (symbolp (car scope)))
14235 (setq scope (eval scope)))
14236 ((eq scope 'agenda)
14237 (setq scope (org-agenda-files t)))
14238 ((eq scope 'agenda-with-archives)
14239 (setq scope (org-agenda-files t))
14240 (setq scope (org-add-archive-files scope)))
14241 ((eq scope 'file)
14242 (setq scope (list (buffer-file-name))))
14243 ((eq scope 'file-with-archives)
14244 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14245 (org-agenda-prepare-buffers scope)
14246 (while (setq file (pop scope))
14247 (with-current-buffer (org-find-base-buffer-visiting file)
14248 (save-excursion
14249 (save-restriction
14250 (widen)
14251 (goto-char (point-min))
14252 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14253 res)))
14255 ;;;; Properties
14257 ;;; Setting and retrieving properties
14259 (defconst org-special-properties
14260 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14261 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14262 "The special properties valid in Org-mode.
14264 These are properties that are not defined in the property drawer,
14265 but in some other way.")
14267 (defconst org-default-properties
14268 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14269 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14270 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14271 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14272 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14273 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14274 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14275 "Some properties that are used by Org-mode for various purposes.
14276 Being in this list makes sure that they are offered for completion.")
14278 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14279 "Regular expression matching the first line of a property drawer.")
14281 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14282 "Regular expression matching the last line of a property drawer.")
14284 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14285 "Regular expression matching the first line of a property drawer.")
14287 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14288 "Regular expression matching the first line of a property drawer.")
14290 (defconst org-property-drawer-re
14291 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14292 org-property-end-re "\\)\n?")
14293 "Matches an entire property drawer.")
14295 (defconst org-clock-drawer-re
14296 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14297 org-property-end-re "\\)\n?")
14298 "Matches an entire clock drawer.")
14300 (defsubst org-re-property (property)
14301 "Return a regexp matching a PROPERTY line.
14302 Match group 1 will be set to the value."
14303 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14305 (defsubst org-re-property-keyword (property)
14306 "Return a regexp matching a PROPERTY line, possibly with no
14307 value for the property."
14308 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14310 (defun org-property-action ()
14311 "Do an action on properties."
14312 (interactive)
14313 (let (c)
14314 (org-at-property-p)
14315 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14316 (setq c (read-char-exclusive))
14317 (cond
14318 ((equal c ?s)
14319 (call-interactively 'org-set-property))
14320 ((equal c ?d)
14321 (call-interactively 'org-delete-property))
14322 ((equal c ?D)
14323 (call-interactively 'org-delete-property-globally))
14324 ((equal c ?c)
14325 (call-interactively 'org-compute-property-at-point))
14326 (t (error "No such property action %c" c)))))
14328 (defun org-inc-effort ()
14329 "Increment the value of the effort property in the current entry."
14330 (interactive)
14331 (org-set-effort nil t))
14333 (defun org-set-effort (&optional value increment)
14334 "Set the effort property of the current entry.
14335 With numerical prefix arg, use the nth allowed value, 0 stands for the
14336 10th allowed value.
14338 When INCREMENT is non-nil, set the property to the next allowed value."
14339 (interactive "P")
14340 (if (equal value 0) (setq value 10))
14341 (let* ((completion-ignore-case t)
14342 (prop org-effort-property)
14343 (cur (org-entry-get nil prop))
14344 (allowed (org-property-get-allowed-values nil prop 'table))
14345 (existing (mapcar 'list (org-property-values prop)))
14347 (val (cond
14348 ((stringp value) value)
14349 ((and allowed (integerp value))
14350 (or (car (nth (1- value) allowed))
14351 (car (org-last allowed))))
14352 ((and allowed increment)
14353 (or (caadr (member (list cur) allowed))
14354 (error "Allowed effort values are not set")))
14355 (allowed
14356 (message "Select 1-9,0, [RET%s]: %s"
14357 (if cur (concat "=" cur) "")
14358 (mapconcat 'car allowed " "))
14359 (setq rpl (read-char-exclusive))
14360 (if (equal rpl ?\r)
14362 (setq rpl (- rpl ?0))
14363 (if (equal rpl 0) (setq rpl 10))
14364 (if (and (> rpl 0) (<= rpl (length allowed)))
14365 (car (nth (1- rpl) allowed))
14366 (org-completing-read "Effort: " allowed nil))))
14368 (let (org-completion-use-ido org-completion-use-iswitchb)
14369 (org-completing-read
14370 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14371 (concat "[" cur "]") "")
14372 ": ")
14373 existing nil nil "" nil cur))))))
14374 (unless (equal (org-entry-get nil prop) val)
14375 (org-entry-put nil prop val))
14376 (message "%s is now %s" prop val)))
14378 (defun org-at-property-p ()
14379 "Is cursor inside a property drawer?"
14380 (save-excursion
14381 (beginning-of-line 1)
14382 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14383 (save-match-data ;; Used by calling procedures
14384 (let ((p (point))
14385 (range (unless (org-before-first-heading-p)
14386 (org-get-property-block))))
14387 (and range (<= (car range) p) (< p (cdr range))))))))
14389 (defun org-get-property-block (&optional beg end force)
14390 "Return the (beg . end) range of the body of the property drawer.
14391 BEG and END are the beginning and end of the current subtree, or of
14392 the part before the first headline. If they are not given, they will
14393 be found. If the drawer does not exist and FORCE is non-nil, create
14394 the drawer."
14395 (catch 'exit
14396 (save-excursion
14397 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14398 (progn (org-back-to-heading t) (point))))
14399 (end (or end (and (not (outline-next-heading)) (point-max))
14400 (point))))
14401 (goto-char beg)
14402 (if (re-search-forward org-property-start-re end t)
14403 (setq beg (1+ (match-end 0)))
14404 (if force
14405 (save-excursion
14406 (org-insert-property-drawer)
14407 (setq end (progn (outline-next-heading) (point))))
14408 (throw 'exit nil))
14409 (goto-char beg)
14410 (if (re-search-forward org-property-start-re end t)
14411 (setq beg (1+ (match-end 0)))))
14412 (if (re-search-forward org-property-end-re end t)
14413 (setq end (match-beginning 0))
14414 (or force (throw 'exit nil))
14415 (goto-char beg)
14416 (setq end beg)
14417 (org-indent-line)
14418 (insert ":END:\n"))
14419 (cons beg end)))))
14421 (defun org-entry-properties (&optional pom which specific)
14422 "Get all properties of the entry at point-or-marker POM.
14423 This includes the TODO keyword, the tags, time strings for deadline,
14424 scheduled, and clocking, and any additional properties defined in the
14425 entry. The return value is an alist, keys may occur multiple times
14426 if the property key was used several times.
14427 POM may also be nil, in which case the current entry is used.
14428 If WHICH is nil or `all', get all properties. If WHICH is
14429 `special' or `standard', only get that subclass. If WHICH
14430 is a string only get exactly this property. SPECIFIC can be a string, the
14431 specific property we are interested in. Specifying it can speed
14432 things up because then unnecessary parsing is avoided."
14433 (setq which (or which 'all))
14434 (org-with-point-at pom
14435 (let ((clockstr (substring org-clock-string 0 -1))
14436 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14437 (case-fold-search nil)
14438 beg end range props sum-props key key1 value string clocksum clocksumt)
14439 (save-excursion
14440 (when (condition-case nil
14441 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14442 (error nil))
14443 (setq beg (point))
14444 (setq sum-props (get-text-property (point) 'org-summaries))
14445 (setq clocksum (get-text-property (point) :org-clock-minutes)
14446 clocksumt (get-text-property (point) :org-clock-minutes-today))
14447 (outline-next-heading)
14448 (setq end (point))
14449 (when (memq which '(all special))
14450 ;; Get the special properties, like TODO and tags
14451 (goto-char beg)
14452 (when (and (or (not specific) (string= specific "TODO"))
14453 (looking-at org-todo-line-regexp) (match-end 2))
14454 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14455 (when (and (or (not specific) (string= specific "PRIORITY"))
14456 (looking-at org-priority-regexp))
14457 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14458 (when (or (not specific) (string= specific "FILE"))
14459 (push (cons "FILE" buffer-file-name) props))
14460 (when (and (or (not specific) (string= specific "TAGS"))
14461 (setq value (org-get-tags-string))
14462 (string-match "\\S-" value))
14463 (push (cons "TAGS" value) props))
14464 (when (and (or (not specific) (string= specific "ALLTAGS"))
14465 (setq value (org-get-tags-at)))
14466 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14467 ":"))
14468 props))
14469 (when (or (not specific) (string= specific "BLOCKED"))
14470 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14471 (when (or (not specific)
14472 (member specific
14473 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14474 "TIMESTAMP" "TIMESTAMP_IA")))
14475 (catch 'match
14476 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14477 (setq key (if (match-end 1)
14478 (substring (org-match-string-no-properties 1)
14479 0 -1))
14480 string (if (equal key clockstr)
14481 (org-trim
14482 (buffer-substring-no-properties
14483 (match-beginning 3) (goto-char
14484 (point-at-eol))))
14485 (substring (org-match-string-no-properties 3)
14486 1 -1)))
14487 ;; Get the correct property name from the key. This is
14488 ;; necessary if the user has configured time keywords.
14489 (setq key1 (concat key ":"))
14490 (cond
14491 ((not key)
14492 (setq key
14493 (if (= (char-after (match-beginning 3)) ?\[)
14494 "TIMESTAMP_IA" "TIMESTAMP")))
14495 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14496 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14497 ((equal key1 org-closed-string) (setq key "CLOSED"))
14498 ((equal key1 org-clock-string) (setq key "CLOCK")))
14499 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14500 (progn
14501 (push (cons key string) props)
14502 ;; no need to search further if match is found
14503 (throw 'match t))
14504 (when (or (equal key "CLOCK") (not (assoc key props)))
14505 (push (cons key string) props)))))))
14507 (when (memq which '(all standard))
14508 ;; Get the standard properties, like :PROP: ...
14509 (setq range (org-get-property-block beg end))
14510 (when range
14511 (goto-char (car range))
14512 (while (re-search-forward
14513 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14514 (cdr range) t)
14515 (setq key (org-match-string-no-properties 1)
14516 value (org-trim (or (org-match-string-no-properties 2) "")))
14517 (unless (member key excluded)
14518 (push (cons key (or value "")) props)))))
14519 (if clocksum
14520 (push (cons "CLOCKSUM"
14521 (org-columns-number-to-string (/ (float clocksum) 60.)
14522 'add_times))
14523 props))
14524 (if clocksumt
14525 (push (cons "CLOCKSUM_T"
14526 (org-columns-number-to-string (/ (float clocksumt) 60.)
14527 'add_times))
14528 props))
14529 (unless (assoc "CATEGORY" props)
14530 (push (cons "CATEGORY" (org-get-category)) props))
14531 (append sum-props (nreverse props)))))))
14533 (defun org-entry-get (pom property &optional inherit literal-nil)
14534 "Get value of PROPERTY for entry or content at point-or-marker POM.
14535 If INHERIT is non-nil and the entry does not have the property,
14536 then also check higher levels of the hierarchy.
14537 If INHERIT is the symbol `selective', use inheritance only if the setting
14538 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14539 If the property is present but empty, the return value is the empty string.
14540 If the property is not present at all, nil is returned.
14542 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14543 do not interpret it as the list atom nil. This is used for inheritance
14544 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14545 (org-with-point-at pom
14546 (if (and inherit (if (eq inherit 'selective)
14547 (org-property-inherit-p property)
14549 (org-entry-get-with-inheritance property literal-nil)
14550 (if (member property org-special-properties)
14551 ;; We need a special property. Use `org-entry-properties' to
14552 ;; retrieve it, but specify the wanted property
14553 (cdr (assoc property (org-entry-properties nil 'special property)))
14554 (let* ((range (org-get-property-block))
14555 (props (list (or (assoc property org-file-properties)
14556 (assoc property org-global-properties)
14557 (assoc property org-global-properties-fixed))))
14558 (ap (lambda (key)
14559 (when (re-search-forward
14560 (org-re-property key) (cdr range) t)
14561 (setq props
14562 (org-update-property-plist
14564 (if (match-end 1)
14565 (org-match-string-no-properties 1) "")
14566 props)))))
14567 val)
14568 (when (and range (goto-char (car range)))
14569 (funcall ap property)
14570 (goto-char (car range))
14571 (while (funcall ap (concat property "+")))
14572 (setq val (cdr (assoc property props)))
14573 (when val (if literal-nil val (org-not-nil val)))))))))
14575 (defun org-property-or-variable-value (var &optional inherit)
14576 "Check if there is a property fixing the value of VAR.
14577 If yes, return this value. If not, return the current value of the variable."
14578 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14579 (if (and prop (stringp prop) (string-match "\\S-" prop))
14580 (read prop)
14581 (symbol-value var))))
14583 (defun org-entry-delete (pom property)
14584 "Delete the property PROPERTY from entry at point-or-marker POM."
14585 (org-with-point-at pom
14586 (if (member property org-special-properties)
14587 nil ; cannot delete these properties.
14588 (let ((range (org-get-property-block)))
14589 (if (and range
14590 (goto-char (car range))
14591 (re-search-forward
14592 (org-re-property property)
14593 (cdr range) t))
14594 (progn
14595 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14597 nil)))))
14599 ;; Multi-values properties are properties that contain multiple values
14600 ;; These values are assumed to be single words, separated by whitespace.
14601 (defun org-entry-add-to-multivalued-property (pom property value)
14602 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14603 (let* ((old (org-entry-get pom property))
14604 (values (and old (org-split-string old "[ \t]"))))
14605 (setq value (org-entry-protect-space value))
14606 (unless (member value values)
14607 (setq values (cons value values))
14608 (org-entry-put pom property
14609 (mapconcat 'identity values " ")))))
14611 (defun org-entry-remove-from-multivalued-property (pom property value)
14612 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14613 (let* ((old (org-entry-get pom property))
14614 (values (and old (org-split-string old "[ \t]"))))
14615 (setq value (org-entry-protect-space value))
14616 (when (member value values)
14617 (setq values (delete value values))
14618 (org-entry-put pom property
14619 (mapconcat 'identity values " ")))))
14621 (defun org-entry-member-in-multivalued-property (pom property value)
14622 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14623 (let* ((old (org-entry-get pom property))
14624 (values (and old (org-split-string old "[ \t]"))))
14625 (setq value (org-entry-protect-space value))
14626 (member value values)))
14628 (defun org-entry-get-multivalued-property (pom property)
14629 "Return a list of values in a multivalued property."
14630 (let* ((value (org-entry-get pom property))
14631 (values (and value (org-split-string value "[ \t]"))))
14632 (mapcar 'org-entry-restore-space values)))
14634 (defun org-entry-put-multivalued-property (pom property &rest values)
14635 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14636 VALUES should be a list of strings. Spaces will be protected."
14637 (org-entry-put pom property
14638 (mapconcat 'org-entry-protect-space values " "))
14639 (let* ((value (org-entry-get pom property))
14640 (values (and value (org-split-string value "[ \t]"))))
14641 (mapcar 'org-entry-restore-space values)))
14643 (defun org-entry-protect-space (s)
14644 "Protect spaces and newline in string S."
14645 (while (string-match " " s)
14646 (setq s (replace-match "%20" t t s)))
14647 (while (string-match "\n" s)
14648 (setq s (replace-match "%0A" t t s)))
14651 (defun org-entry-restore-space (s)
14652 "Restore spaces and newline in string S."
14653 (while (string-match "%20" s)
14654 (setq s (replace-match " " t t s)))
14655 (while (string-match "%0A" s)
14656 (setq s (replace-match "\n" t t s)))
14659 (defvar org-entry-property-inherited-from (make-marker)
14660 "Marker pointing to the entry from where a property was inherited.
14661 Each call to `org-entry-get-with-inheritance' will set this marker to the
14662 location of the entry where the inheritance search matched. If there was
14663 no match, the marker will point nowhere.
14664 Note that also `org-entry-get' calls this function, if the INHERIT flag
14665 is set.")
14667 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14668 "Get PROPERTY of entry or content at point, search higher levels if needed.
14669 The search will stop at the first ancestor which has the property defined.
14670 If the value found is \"nil\", return nil to show that the property
14671 should be considered as undefined (this is the meaning of nil here).
14672 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14673 (move-marker org-entry-property-inherited-from nil)
14674 (let (tmp)
14675 (save-excursion
14676 (save-restriction
14677 (widen)
14678 (catch 'ex
14679 (while t
14680 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14681 (or (ignore-errors (org-back-to-heading t))
14682 (goto-char (point-min)))
14683 (move-marker org-entry-property-inherited-from (point))
14684 (throw 'ex tmp))
14685 (or (ignore-errors (org-up-heading-safe))
14686 (throw 'ex nil))))))
14687 (setq tmp (or tmp
14688 (cdr (assoc property org-file-properties))
14689 (cdr (assoc property org-global-properties))
14690 (cdr (assoc property org-global-properties-fixed))))
14691 (if literal-nil tmp (org-not-nil tmp))))
14693 (defvar org-property-changed-functions nil
14694 "Hook called when the value of a property has changed.
14695 Each hook function should accept two arguments, the name of the property
14696 and the new value.")
14698 (defun org-entry-put (pom property value)
14699 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14700 (org-with-point-at pom
14701 (org-back-to-heading t)
14702 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14703 range)
14704 (cond
14705 ((equal property "TODO")
14706 (when (and (stringp value) (string-match "\\S-" value)
14707 (not (member value org-todo-keywords-1)))
14708 (error "\"%s\" is not a valid TODO state" value))
14709 (if (or (not value)
14710 (not (string-match "\\S-" value)))
14711 (setq value 'none))
14712 (org-todo value)
14713 (org-set-tags nil 'align))
14714 ((equal property "PRIORITY")
14715 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14716 (string-to-char value) ?\ ))
14717 (org-set-tags nil 'align))
14718 ((equal property "SCHEDULED")
14719 (if (re-search-forward org-scheduled-time-regexp end t)
14720 (cond
14721 ((eq value 'earlier) (org-timestamp-change -1 'day))
14722 ((eq value 'later) (org-timestamp-change 1 'day))
14723 (t (call-interactively 'org-schedule)))
14724 (call-interactively 'org-schedule)))
14725 ((equal property "DEADLINE")
14726 (if (re-search-forward org-deadline-time-regexp end t)
14727 (cond
14728 ((eq value 'earlier) (org-timestamp-change -1 'day))
14729 ((eq value 'later) (org-timestamp-change 1 'day))
14730 (t (call-interactively 'org-deadline)))
14731 (call-interactively 'org-deadline)))
14732 ((member property org-special-properties)
14733 (error "The %s property can not yet be set with `org-entry-put'"
14734 property))
14735 (t ; a non-special property
14736 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14737 (setq range (org-get-property-block beg end 'force))
14738 (goto-char (car range))
14739 (if (re-search-forward
14740 (org-re-property-keyword property) (cdr range) t)
14741 (progn
14742 (delete-region (match-beginning 0) (match-end 0))
14743 (goto-char (match-beginning 0)))
14744 (goto-char (cdr range))
14745 (insert "\n")
14746 (backward-char 1)
14747 (org-indent-line))
14748 (insert ":" property ":")
14749 (and value (insert " " value))
14750 (org-indent-line)))))
14751 (run-hook-with-args 'org-property-changed-functions property value)))
14753 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14754 "Get all property keys in the current buffer.
14755 With INCLUDE-SPECIALS, also list the special properties that reflect things
14756 like tags and TODO state.
14757 With INCLUDE-DEFAULTS, also include properties that has special meaning
14758 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14759 and others.
14760 With INCLUDE-COLUMNS, also include property names given in COLUMN
14761 formats in the current buffer."
14762 (let (rtn range cfmt s p)
14763 (save-excursion
14764 (save-restriction
14765 (widen)
14766 (goto-char (point-min))
14767 (while (re-search-forward org-property-start-re nil t)
14768 (setq range (org-get-property-block))
14769 (goto-char (car range))
14770 (while (re-search-forward
14771 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14772 (cdr range) t)
14773 (add-to-list 'rtn (org-match-string-no-properties 1)))
14774 (outline-next-heading))))
14776 (when include-specials
14777 (setq rtn (append org-special-properties rtn)))
14779 (when include-defaults
14780 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14781 (add-to-list 'rtn org-effort-property))
14783 (when include-columns
14784 (save-excursion
14785 (save-restriction
14786 (widen)
14787 (goto-char (point-min))
14788 (while (re-search-forward
14789 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14790 nil t)
14791 (setq cfmt (match-string 2) s 0)
14792 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14793 cfmt s)
14794 (setq s (match-end 0)
14795 p (match-string 1 cfmt))
14796 (unless (or (equal p "ITEM")
14797 (member p org-special-properties))
14798 (add-to-list 'rtn (match-string 1 cfmt))))))))
14800 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14802 (defun org-property-values (key)
14803 "Return a list of all values of property KEY in the current buffer."
14804 (save-excursion
14805 (save-restriction
14806 (widen)
14807 (goto-char (point-min))
14808 (let ((re (org-re-property key))
14809 values)
14810 (while (re-search-forward re nil t)
14811 (add-to-list 'values (org-trim (match-string 1))))
14812 (delete "" values)))))
14814 (defun org-insert-property-drawer ()
14815 "Insert a property drawer into the current entry."
14816 (org-back-to-heading t)
14817 (looking-at org-outline-regexp)
14818 (let ((indent (if org-adapt-indentation
14819 (- (match-end 0) (match-beginning 0))
14821 (beg (point))
14822 (re (concat "^[ \t]*" org-keyword-time-regexp))
14823 end hiddenp)
14824 (outline-next-heading)
14825 (setq end (point))
14826 (goto-char beg)
14827 (while (re-search-forward re end t))
14828 (setq hiddenp (outline-invisible-p))
14829 (end-of-line 1)
14830 (and (equal (char-after) ?\n) (forward-char 1))
14831 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14832 (if (member (match-string 1) '("CLOCK:" ":END:"))
14833 ;; just skip this line
14834 (beginning-of-line 2)
14835 ;; Drawer start, find the end
14836 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14837 (beginning-of-line 1)))
14838 (org-skip-over-state-notes)
14839 (skip-chars-backward " \t\n\r")
14840 (if (eq (char-before) ?*) (forward-char 1))
14841 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14842 (beginning-of-line 0)
14843 (org-indent-to-column indent)
14844 (beginning-of-line 2)
14845 (org-indent-to-column indent)
14846 (beginning-of-line 0)
14847 (if hiddenp
14848 (save-excursion
14849 (org-back-to-heading t)
14850 (hide-entry))
14851 (org-flag-drawer t))))
14853 (defun org-insert-drawer (&optional arg drawer)
14854 "Insert a drawer at point.
14856 Optional argument DRAWER, when non-nil, is a string representing
14857 drawer's name. Otherwise, the user is prompted for a name.
14859 If a region is active, insert the drawer around that region
14860 instead.
14862 Point is left between drawer's boundaries."
14863 (interactive "P")
14864 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14865 "LOGBOOK"))
14866 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14867 ;; internally by Org. They are meant to be inserted
14868 ;; automatically.
14869 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14870 ;; Remove system drawers from list. Note: For some reason,
14871 ;; `org-completing-read' ignores the predicate while
14872 ;; `completing-read' handles it fine.
14873 (drawer (if arg "PROPERTIES"
14874 (or drawer
14875 (completing-read
14876 "Drawer: " org-drawers
14877 (lambda (d) (not (member d system-drawers))))))))
14878 (cond
14879 ;; With C-u, fall back on `org-insert-property-drawer'
14880 (arg (org-insert-property-drawer))
14881 ;; With an active region, insert a drawer at point.
14882 ((not (org-region-active-p))
14883 (progn
14884 (unless (bolp) (insert "\n"))
14885 (insert (format ":%s:\n\n:END:\n" drawer))
14886 (forward-line -2)))
14887 ;; Otherwise, insert the drawer at point
14889 (let ((rbeg (region-beginning))
14890 (rend (copy-marker (region-end))))
14891 (unwind-protect
14892 (progn
14893 (goto-char rbeg)
14894 (beginning-of-line)
14895 (when (save-excursion
14896 (re-search-forward org-outline-regexp-bol rend t))
14897 (error "Drawers cannot contain headlines"))
14898 ;; Position point at the beginning of the first
14899 ;; non-blank line in region. Insert drawer's opening
14900 ;; there, then indent it.
14901 (org-skip-whitespace)
14902 (beginning-of-line)
14903 (insert ":" drawer ":\n")
14904 (forward-line -1)
14905 (indent-for-tab-command)
14906 ;; Move point to the beginning of the first blank line
14907 ;; after the last non-blank line in region. Insert
14908 ;; drawer's closing, then indent it.
14909 (goto-char rend)
14910 (skip-chars-backward " \r\t\n")
14911 (insert "\n:END:")
14912 (deactivate-mark t)
14913 (indent-for-tab-command)
14914 (unless (eolp) (insert "\n")))
14915 ;; Clear marker, whatever the outcome of insertion is.
14916 (set-marker rend nil)))))))
14918 (defvar org-property-set-functions-alist nil
14919 "Property set function alist.
14920 Each entry should have the following format:
14922 (PROPERTY . READ-FUNCTION)
14924 The read function will be called with the same argument as
14925 `org-completing-read'.")
14927 (defun org-set-property-function (property)
14928 "Get the function that should be used to set PROPERTY.
14929 This is computed according to `org-property-set-functions-alist'."
14930 (or (cdr (assoc property org-property-set-functions-alist))
14931 'org-completing-read))
14933 (defun org-read-property-value (property)
14934 "Read PROPERTY value from user."
14935 (let* ((completion-ignore-case t)
14936 (allowed (org-property-get-allowed-values nil property 'table))
14937 (cur (org-entry-get nil property))
14938 (prompt (concat property " value"
14939 (if (and cur (string-match "\\S-" cur))
14940 (concat " [" cur "]") "") ": "))
14941 (set-function (org-set-property-function property))
14942 (val (if allowed
14943 (funcall set-function prompt allowed nil
14944 (not (get-text-property 0 'org-unrestricted
14945 (caar allowed))))
14946 (let (org-completion-use-ido org-completion-use-iswitchb)
14947 (funcall set-function prompt
14948 (mapcar 'list (org-property-values property))
14949 nil nil "" nil cur)))))
14950 (if (equal val "")
14952 val)))
14954 (defvar org-last-set-property nil)
14955 (defun org-read-property-name ()
14956 "Read a property name."
14957 (let* ((completion-ignore-case t)
14958 (keys (org-buffer-property-keys nil t t))
14959 (default-prop (or (save-excursion
14960 (save-match-data
14961 (beginning-of-line)
14962 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14963 (null (string= (match-string 1) "END"))
14964 (match-string 1))))
14965 org-last-set-property))
14966 (property (org-icompleting-read
14967 (concat "Property"
14968 (if default-prop (concat " [" default-prop "]") "")
14969 ": ")
14970 (mapcar 'list keys)
14971 nil nil nil nil
14972 default-prop
14974 (if (member property keys)
14975 property
14976 (or (cdr (assoc (downcase property)
14977 (mapcar (lambda (x) (cons (downcase x) x))
14978 keys)))
14979 property))))
14981 (defun org-set-property (property value)
14982 "In the current entry, set PROPERTY to VALUE.
14983 When called interactively, this will prompt for a property name, offering
14984 completion on existing and default properties. And then it will prompt
14985 for a value, offering completion either on allowed values (via an inherited
14986 xxx_ALL property) or on existing values in other instances of this property
14987 in the current file."
14988 (interactive (list nil nil))
14989 (let* ((property (or property (org-read-property-name)))
14990 (value (or value (org-read-property-value property)))
14991 (fn (cdr (assoc property org-properties-postprocess-alist))))
14992 (setq org-last-set-property property)
14993 ;; Possibly postprocess the inserted value:
14994 (when fn (setq value (funcall fn value)))
14995 (unless (equal (org-entry-get nil property) value)
14996 (org-entry-put nil property value))))
14998 (defun org-delete-property (property)
14999 "In the current entry, delete PROPERTY."
15000 (interactive
15001 (let* ((completion-ignore-case t)
15002 (prop (org-icompleting-read "Property: "
15003 (org-entry-properties nil 'standard))))
15004 (list prop)))
15005 (message "Property %s %s" property
15006 (if (org-entry-delete nil property)
15007 "deleted"
15008 "was not present in the entry")))
15010 (defun org-delete-property-globally (property)
15011 "Remove PROPERTY globally, from all entries."
15012 (interactive
15013 (let* ((completion-ignore-case t)
15014 (prop (org-icompleting-read
15015 "Globally remove property: "
15016 (mapcar 'list (org-buffer-property-keys)))))
15017 (list prop)))
15018 (save-excursion
15019 (save-restriction
15020 (widen)
15021 (goto-char (point-min))
15022 (let ((cnt 0))
15023 (while (re-search-forward
15024 (org-re-property property)
15025 nil t)
15026 (setq cnt (1+ cnt))
15027 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15028 (message "Property \"%s\" removed from %d entries" property cnt)))))
15030 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15032 (defun org-compute-property-at-point ()
15033 "Compute the property at point.
15034 This looks for an enclosing column format, extracts the operator and
15035 then applies it to the property in the column format's scope."
15036 (interactive)
15037 (unless (org-at-property-p)
15038 (error "Not at a property"))
15039 (let ((prop (org-match-string-no-properties 2)))
15040 (org-columns-get-format-and-top-level)
15041 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15042 (error "No operator defined for property %s" prop))
15043 (org-columns-compute prop)))
15045 (defvar org-property-allowed-value-functions nil
15046 "Hook for functions supplying allowed values for a specific property.
15047 The functions must take a single argument, the name of the property, and
15048 return a flat list of allowed values. If \":ETC\" is one of
15049 the values, this means that these values are intended as defaults for
15050 completion, but that other values should be allowed too.
15051 The functions must return nil if they are not responsible for this
15052 property.")
15054 (defun org-property-get-allowed-values (pom property &optional table)
15055 "Get allowed values for the property PROPERTY.
15056 When TABLE is non-nil, return an alist that can directly be used for
15057 completion."
15058 (let (vals)
15059 (cond
15060 ((equal property "TODO")
15061 (setq vals (org-with-point-at pom
15062 (append org-todo-keywords-1 '("")))))
15063 ((equal property "PRIORITY")
15064 (let ((n org-lowest-priority))
15065 (while (>= n org-highest-priority)
15066 (push (char-to-string n) vals)
15067 (setq n (1- n)))))
15068 ((member property org-special-properties))
15069 ((setq vals (run-hook-with-args-until-success
15070 'org-property-allowed-value-functions property)))
15072 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15073 (when (and vals (string-match "\\S-" vals))
15074 (setq vals (car (read-from-string (concat "(" vals ")"))))
15075 (setq vals (mapcar (lambda (x)
15076 (cond ((stringp x) x)
15077 ((numberp x) (number-to-string x))
15078 ((symbolp x) (symbol-name x))
15079 (t "???")))
15080 vals)))))
15081 (when (member ":ETC" vals)
15082 (setq vals (remove ":ETC" vals))
15083 (org-add-props (car vals) '(org-unrestricted t)))
15084 (if table (mapcar 'list vals) vals)))
15086 (defun org-property-previous-allowed-value (&optional previous)
15087 "Switch to the next allowed value for this property."
15088 (interactive)
15089 (org-property-next-allowed-value t))
15091 (defun org-property-next-allowed-value (&optional previous)
15092 "Switch to the next allowed value for this property."
15093 (interactive)
15094 (unless (org-at-property-p)
15095 (error "Not at a property"))
15096 (let* ((key (match-string 2))
15097 (value (match-string 3))
15098 (allowed (or (org-property-get-allowed-values (point) key)
15099 (and (member value '("[ ]" "[-]" "[X]"))
15100 '("[ ]" "[X]"))))
15101 nval)
15102 (unless allowed
15103 (error "Allowed values for this property have not been defined"))
15104 (if previous (setq allowed (reverse allowed)))
15105 (if (member value allowed)
15106 (setq nval (car (cdr (member value allowed)))))
15107 (setq nval (or nval (car allowed)))
15108 (if (equal nval value)
15109 (error "Only one allowed value for this property"))
15110 (org-at-property-p)
15111 (replace-match (concat " :" key ": " nval) t t)
15112 (org-indent-line)
15113 (beginning-of-line 1)
15114 (skip-chars-forward " \t")
15115 (run-hook-with-args 'org-property-changed-functions key nval)))
15117 (defun org-find-olp (path &optional this-buffer)
15118 "Return a marker pointing to the entry at outline path OLP.
15119 If anything goes wrong, throw an error.
15120 You can wrap this call to catch the error like this:
15122 (condition-case msg
15123 (org-mobile-locate-entry (match-string 4))
15124 (error (nth 1 msg)))
15126 The return value will then be either a string with the error message,
15127 or a marker if everything is OK.
15129 If THIS-BUFFER is set, the outline path does not contain a file,
15130 only headings."
15131 (let* ((file (if this-buffer buffer-file-name (pop path)))
15132 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15133 (level 1)
15134 (lmin 1)
15135 (lmax 1)
15136 limit re end found pos heading cnt flevel)
15137 (unless buffer (error "File not found :%s" file))
15138 (with-current-buffer buffer
15139 (save-excursion
15140 (save-restriction
15141 (widen)
15142 (setq limit (point-max))
15143 (goto-char (point-min))
15144 (while (setq heading (pop path))
15145 (setq re (format org-complex-heading-regexp-format
15146 (regexp-quote heading)))
15147 (setq cnt 0 pos (point))
15148 (while (re-search-forward re end t)
15149 (setq level (- (match-end 1) (match-beginning 1)))
15150 (if (and (>= level lmin) (<= level lmax))
15151 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15152 (when (= cnt 0) (error "Heading not found on level %d: %s"
15153 lmax heading))
15154 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15155 lmax heading))
15156 (goto-char found)
15157 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15158 (setq end (save-excursion (org-end-of-subtree t t))))
15159 (when (org-at-heading-p)
15160 (move-marker (make-marker) (point))))))))
15162 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15163 "Find node HEADING in BUFFER.
15164 Return a marker to the heading if it was found, or nil if not.
15165 If POS-ONLY is set, return just the position instead of a marker.
15167 The heading text must match exact, but it may have a TODO keyword,
15168 a priority cookie and tags in the standard locations."
15169 (with-current-buffer (or buffer (current-buffer))
15170 (save-excursion
15171 (save-restriction
15172 (widen)
15173 (goto-char (point-min))
15174 (let (case-fold-search)
15175 (if (re-search-forward
15176 (format org-complex-heading-regexp-format
15177 (regexp-quote heading)) nil t)
15178 (if pos-only
15179 (match-beginning 0)
15180 (move-marker (make-marker) (match-beginning 0)))))))))
15182 (defun org-find-exact-heading-in-directory (heading &optional dir)
15183 "Find Org node headline HEADING in all .org files in directory DIR.
15184 When the target headline is found, return a marker to this location."
15185 (let ((files (directory-files (or dir default-directory)
15186 nil "\\`[^.#].*\\.org\\'"))
15187 file visiting m buffer)
15188 (catch 'found
15189 (while (setq file (pop files))
15190 (message "trying %s" file)
15191 (setq visiting (org-find-base-buffer-visiting file))
15192 (setq buffer (or visiting (find-file-noselect file)))
15193 (setq m (org-find-exact-headline-in-buffer
15194 heading buffer))
15195 (when (and (not m) (not visiting)) (kill-buffer buffer))
15196 (and m (throw 'found m))))))
15198 (defun org-find-entry-with-id (ident)
15199 "Locate the entry that contains the ID property with exact value IDENT.
15200 IDENT can be a string, a symbol or a number, this function will search for
15201 the string representation of it.
15202 Return the position where this entry starts, or nil if there is no such entry."
15203 (interactive "sID: ")
15204 (let ((id (cond
15205 ((stringp ident) ident)
15206 ((symbol-name ident) (symbol-name ident))
15207 ((numberp ident) (number-to-string ident))
15208 (t (error "IDENT %s must be a string, symbol or number" ident))))
15209 (case-fold-search nil))
15210 (save-excursion
15211 (save-restriction
15212 (widen)
15213 (goto-char (point-min))
15214 (when (re-search-forward
15215 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15216 nil t)
15217 (org-back-to-heading t)
15218 (point))))))
15220 ;;;; Timestamps
15222 (defvar org-last-changed-timestamp nil)
15223 (defvar org-last-inserted-timestamp nil
15224 "The last time stamp inserted with `org-insert-time-stamp'.")
15225 (defvar org-time-was-given) ; dynamically scoped parameter
15226 (defvar org-end-time-was-given) ; dynamically scoped parameter
15227 (defvar org-ts-what) ; dynamically scoped parameter
15229 (defun org-time-stamp (arg &optional inactive)
15230 "Prompt for a date/time and insert a time stamp.
15231 If the user specifies a time like HH:MM or if this command is
15232 called with at least one prefix argument, the time stamp contains
15233 the date and the time. Otherwise, only the date is be included.
15235 All parts of a date not specified by the user is filled in from
15236 the current date/time. So if you just press return without
15237 typing anything, the time stamp will represent the current
15238 date/time.
15240 If there is already a timestamp at the cursor, it will be
15241 modified.
15243 With two universal prefix arguments, insert an active timestamp
15244 with the current time without prompting the user."
15245 (interactive "P")
15246 (let* ((ts nil)
15247 (default-time
15248 ;; Default time is either today, or, when entering a range,
15249 ;; the range start.
15250 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15251 (save-excursion
15252 (re-search-backward
15253 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15254 (- (point) 20) t)))
15255 (apply 'encode-time (org-parse-time-string (match-string 1)))
15256 (current-time)))
15257 (default-input (and ts (org-get-compact-tod ts)))
15258 (repeater (save-excursion
15259 (save-match-data
15260 (beginning-of-line)
15261 (when (re-search-forward
15262 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15263 (save-excursion (progn (end-of-line) (point))) t)
15264 (match-string 0)))))
15265 org-time-was-given org-end-time-was-given time)
15266 (cond
15267 ((and (org-at-timestamp-p t)
15268 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15269 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15270 (insert "--")
15271 (setq time (let ((this-command this-command))
15272 (org-read-date arg 'totime nil nil
15273 default-time default-input inactive)))
15274 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15275 ((org-at-timestamp-p t)
15276 (setq time (let ((this-command this-command))
15277 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15278 (when (org-at-timestamp-p t) ; just to get the match data
15279 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15280 (replace-match "")
15281 (setq org-last-changed-timestamp
15282 (org-insert-time-stamp
15283 time (or org-time-was-given arg)
15284 inactive nil nil (list org-end-time-was-given)))
15285 (when repeater (goto-char (1- (point))) (insert " " repeater)
15286 (setq org-last-changed-timestamp
15287 (concat (substring org-last-inserted-timestamp 0 -1)
15288 " " repeater ">"))))
15289 (message "Timestamp updated"))
15290 ((equal arg '(16))
15291 (org-insert-time-stamp (current-time) t))
15293 (setq time (let ((this-command this-command))
15294 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15295 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15296 nil nil (list org-end-time-was-given))))))
15298 ;; FIXME: can we use this for something else, like computing time differences?
15299 (defun org-get-compact-tod (s)
15300 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15301 (let* ((t1 (match-string 1 s))
15302 (h1 (string-to-number (match-string 2 s)))
15303 (m1 (string-to-number (match-string 3 s)))
15304 (t2 (and (match-end 4) (match-string 5 s)))
15305 (h2 (and t2 (string-to-number (match-string 6 s))))
15306 (m2 (and t2 (string-to-number (match-string 7 s))))
15307 dh dm)
15308 (if (not t2)
15310 (setq dh (- h2 h1) dm (- m2 m1))
15311 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15312 (concat t1 "+" (number-to-string dh)
15313 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15315 (defun org-time-stamp-inactive (&optional arg)
15316 "Insert an inactive time stamp.
15317 An inactive time stamp is enclosed in square brackets instead of angle
15318 brackets. It is inactive in the sense that it does not trigger agenda entries,
15319 does not link to the calendar and cannot be changed with the S-cursor keys.
15320 So these are more for recording a certain time/date."
15321 (interactive "P")
15322 (org-time-stamp arg 'inactive))
15324 (defvar org-date-ovl (make-overlay 1 1))
15325 (overlay-put org-date-ovl 'face 'org-date-selected)
15326 (org-detach-overlay org-date-ovl)
15328 (defvar org-ans1) ; dynamically scoped parameter
15329 (defvar org-ans2) ; dynamically scoped parameter
15331 (defvar org-plain-time-of-day-regexp) ; defined below
15333 (defvar org-overriding-default-time nil) ; dynamically scoped
15334 (defvar org-read-date-overlay nil)
15335 (defvar org-dcst nil) ; dynamically scoped
15336 (defvar org-read-date-history nil)
15337 (defvar org-read-date-final-answer nil)
15338 (defvar org-read-date-analyze-futurep nil)
15339 (defvar org-read-date-analyze-forced-year nil)
15340 (defvar org-read-date-inactive)
15342 (defun org-read-date (&optional org-with-time to-time from-string prompt
15343 default-time default-input inactive)
15344 "Read a date, possibly a time, and make things smooth for the user.
15345 The prompt will suggest to enter an ISO date, but you can also enter anything
15346 which will at least partially be understood by `parse-time-string'.
15347 Unrecognized parts of the date will default to the current day, month, year,
15348 hour and minute. If this command is called to replace a timestamp at point,
15349 or to enter the second timestamp of a range, the default time is taken
15350 from the existing stamp. Furthermore, the command prefers the future,
15351 so if you are giving a date where the year is not given, and the day-month
15352 combination is already past in the current year, it will assume you
15353 mean next year. For details, see the manual. A few examples:
15355 3-2-5 --> 2003-02-05
15356 feb 15 --> currentyear-02-15
15357 2/15 --> currentyear-02-15
15358 sep 12 9 --> 2009-09-12
15359 12:45 --> today 12:45
15360 22 sept 0:34 --> currentyear-09-22 0:34
15361 12 --> currentyear-currentmonth-12
15362 Fri --> nearest Friday (today or later)
15363 etc.
15365 Furthermore you can specify a relative date by giving, as the *first* thing
15366 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15367 change in days weeks, months, years.
15368 With a single plus or minus, the date is relative to today. With a double
15369 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15370 +4d --> four days from today
15371 +4 --> same as above
15372 +2w --> two weeks from today
15373 ++5 --> five days from default date
15375 The function understands only English month and weekday abbreviations.
15377 While prompting, a calendar is popped up - you can also select the
15378 date with the mouse (button 1). The calendar shows a period of three
15379 months. To scroll it to other months, use the keys `>' and `<'.
15380 If you don't like the calendar, turn it off with
15381 \(setq org-read-date-popup-calendar nil)
15383 With optional argument TO-TIME, the date will immediately be converted
15384 to an internal time.
15385 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15386 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15387 still enter a time, and this function will inform the calling routine
15388 about this change. The calling routine may then choose to change the
15389 format used to insert the time stamp into the buffer to include the time.
15390 With optional argument FROM-STRING, read from this string instead from
15391 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15392 the time/date that is used for everything that is not specified by the
15393 user."
15394 (require 'parse-time)
15395 (let* ((org-time-stamp-rounding-minutes
15396 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15397 (org-dcst org-display-custom-times)
15398 (ct (org-current-time))
15399 (org-def (or org-overriding-default-time default-time ct))
15400 (org-defdecode (decode-time org-def))
15401 (dummy (progn
15402 (when (< (nth 2 org-defdecode) org-extend-today-until)
15403 (setcar (nthcdr 2 org-defdecode) -1)
15404 (setcar (nthcdr 1 org-defdecode) 59)
15405 (setq org-def (apply 'encode-time org-defdecode)
15406 org-defdecode (decode-time org-def)))))
15407 (calendar-frame-setup nil)
15408 (calendar-setup nil)
15409 (calendar-move-hook nil)
15410 (calendar-view-diary-initially-flag nil)
15411 (calendar-view-holidays-initially-flag nil)
15412 (timestr (format-time-string
15413 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15414 (prompt (concat (if prompt (concat prompt " ") "")
15415 (format "Date+time [%s]: " timestr)))
15416 ans (org-ans0 "") org-ans1 org-ans2 final)
15418 (cond
15419 (from-string (setq ans from-string))
15420 (org-read-date-popup-calendar
15421 (save-excursion
15422 (save-window-excursion
15423 (calendar)
15424 (org-eval-in-calendar '(setq cursor-type nil) t)
15425 (unwind-protect
15426 (progn
15427 (calendar-forward-day (- (time-to-days org-def)
15428 (calendar-absolute-from-gregorian
15429 (calendar-current-date))))
15430 (org-eval-in-calendar nil t)
15431 (let* ((old-map (current-local-map))
15432 (map (copy-keymap calendar-mode-map))
15433 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15434 (org-defkey map (kbd "RET") 'org-calendar-select)
15435 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15436 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15437 (org-defkey minibuffer-local-map [(meta shift left)]
15438 (lambda () (interactive)
15439 (org-eval-in-calendar '(calendar-backward-month 1))))
15440 (org-defkey minibuffer-local-map [(meta shift right)]
15441 (lambda () (interactive)
15442 (org-eval-in-calendar '(calendar-forward-month 1))))
15443 (org-defkey minibuffer-local-map [(meta shift up)]
15444 (lambda () (interactive)
15445 (org-eval-in-calendar '(calendar-backward-year 1))))
15446 (org-defkey minibuffer-local-map [(meta shift down)]
15447 (lambda () (interactive)
15448 (org-eval-in-calendar '(calendar-forward-year 1))))
15449 (org-defkey minibuffer-local-map [?\e (shift left)]
15450 (lambda () (interactive)
15451 (org-eval-in-calendar '(calendar-backward-month 1))))
15452 (org-defkey minibuffer-local-map [?\e (shift right)]
15453 (lambda () (interactive)
15454 (org-eval-in-calendar '(calendar-forward-month 1))))
15455 (org-defkey minibuffer-local-map [?\e (shift up)]
15456 (lambda () (interactive)
15457 (org-eval-in-calendar '(calendar-backward-year 1))))
15458 (org-defkey minibuffer-local-map [?\e (shift down)]
15459 (lambda () (interactive)
15460 (org-eval-in-calendar '(calendar-forward-year 1))))
15461 (org-defkey minibuffer-local-map [(shift up)]
15462 (lambda () (interactive)
15463 (org-eval-in-calendar '(calendar-backward-week 1))))
15464 (org-defkey minibuffer-local-map [(shift down)]
15465 (lambda () (interactive)
15466 (org-eval-in-calendar '(calendar-forward-week 1))))
15467 (org-defkey minibuffer-local-map [(shift left)]
15468 (lambda () (interactive)
15469 (org-eval-in-calendar '(calendar-backward-day 1))))
15470 (org-defkey minibuffer-local-map [(shift right)]
15471 (lambda () (interactive)
15472 (org-eval-in-calendar '(calendar-forward-day 1))))
15473 (org-defkey minibuffer-local-map ">"
15474 (lambda () (interactive)
15475 (org-eval-in-calendar '(scroll-calendar-left 1))))
15476 (org-defkey minibuffer-local-map "<"
15477 (lambda () (interactive)
15478 (org-eval-in-calendar '(scroll-calendar-right 1))))
15479 (org-defkey minibuffer-local-map "\C-v"
15480 (lambda () (interactive)
15481 (org-eval-in-calendar
15482 '(calendar-scroll-left-three-months 1))))
15483 (org-defkey minibuffer-local-map "\M-v"
15484 (lambda () (interactive)
15485 (org-eval-in-calendar
15486 '(calendar-scroll-right-three-months 1))))
15487 (run-hooks 'org-read-date-minibuffer-setup-hook)
15488 (unwind-protect
15489 (progn
15490 (use-local-map map)
15491 (setq org-read-date-inactive inactive)
15492 (add-hook 'post-command-hook 'org-read-date-display)
15493 (setq org-ans0 (read-string prompt default-input
15494 'org-read-date-history nil))
15495 ;; org-ans0: from prompt
15496 ;; org-ans1: from mouse click
15497 ;; org-ans2: from calendar motion
15498 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15499 (remove-hook 'post-command-hook 'org-read-date-display)
15500 (use-local-map old-map)
15501 (when org-read-date-overlay
15502 (delete-overlay org-read-date-overlay)
15503 (setq org-read-date-overlay nil)))))
15504 (bury-buffer "*Calendar*")))))
15506 (t ; Naked prompt only
15507 (unwind-protect
15508 (setq ans (read-string prompt default-input
15509 'org-read-date-history timestr))
15510 (when org-read-date-overlay
15511 (delete-overlay org-read-date-overlay)
15512 (setq org-read-date-overlay nil)))))
15514 (setq final (org-read-date-analyze ans org-def org-defdecode))
15516 (when org-read-date-analyze-forced-year
15517 (message "Year was forced into %s"
15518 (if org-read-date-force-compatible-dates
15519 "compatible range (1970-2037)"
15520 "range representable on this machine"))
15521 (ding))
15523 ;; One round trip to get rid of 34th of August and stuff like that....
15524 (setq final (decode-time (apply 'encode-time final)))
15526 (setq org-read-date-final-answer ans)
15528 (if to-time
15529 (apply 'encode-time final)
15530 (if (and (boundp 'org-time-was-given) org-time-was-given)
15531 (format "%04d-%02d-%02d %02d:%02d"
15532 (nth 5 final) (nth 4 final) (nth 3 final)
15533 (nth 2 final) (nth 1 final))
15534 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15536 (defvar org-def)
15537 (defvar org-defdecode)
15538 (defvar org-with-time)
15539 (defun org-read-date-display ()
15540 "Display the current date prompt interpretation in the minibuffer."
15541 (when org-read-date-display-live
15542 (when org-read-date-overlay
15543 (delete-overlay org-read-date-overlay))
15544 (when (minibufferp (current-buffer))
15545 (save-excursion
15546 (end-of-line 1)
15547 (while (not (equal (buffer-substring
15548 (max (point-min) (- (point) 4)) (point))
15549 " "))
15550 (insert " ")))
15551 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15552 " " (or org-ans1 org-ans2)))
15553 (org-end-time-was-given nil)
15554 (f (org-read-date-analyze ans org-def org-defdecode))
15555 (fmts (if org-dcst
15556 org-time-stamp-custom-formats
15557 org-time-stamp-formats))
15558 (fmt (if (or org-with-time
15559 (and (boundp 'org-time-was-given) org-time-was-given))
15560 (cdr fmts)
15561 (car fmts)))
15562 (txt (format-time-string fmt (apply 'encode-time f)))
15563 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15564 (txt (concat "=> " txt)))
15565 (when (and org-end-time-was-given
15566 (string-match org-plain-time-of-day-regexp txt))
15567 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15568 org-end-time-was-given
15569 (substring txt (match-end 0)))))
15570 (when org-read-date-analyze-futurep
15571 (setq txt (concat txt " (=>F)")))
15572 (setq org-read-date-overlay
15573 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15574 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15576 (defun org-read-date-analyze (ans org-def org-defdecode)
15577 "Analyze the combined answer of the date prompt."
15578 ;; FIXME: cleanup and comment
15579 (let ((nowdecode (decode-time (current-time)))
15580 delta deltan deltaw deltadef year month day
15581 hour minute second wday pm h2 m2 tl wday1
15582 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15583 (setq org-read-date-analyze-futurep nil
15584 org-read-date-analyze-forced-year nil)
15585 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15586 (setq ans "+0"))
15588 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15589 (setq ans (replace-match "" t t ans)
15590 deltan (car delta)
15591 deltaw (nth 1 delta)
15592 deltadef (nth 2 delta)))
15594 ;; Check if there is an iso week date in there. If yes, store the
15595 ;; info and postpone interpreting it until the rest of the parsing
15596 ;; is done.
15597 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15598 (setq iso-year (if (match-end 1)
15599 (org-small-year-to-year
15600 (string-to-number (match-string 1 ans))))
15601 iso-weekday (if (match-end 3)
15602 (string-to-number (match-string 3 ans)))
15603 iso-week (string-to-number (match-string 2 ans)))
15604 (setq ans (replace-match "" t t ans)))
15606 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15607 (when (string-match
15608 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15609 (setq year (if (match-end 2)
15610 (string-to-number (match-string 2 ans))
15611 (progn (setq kill-year t)
15612 (string-to-number (format-time-string "%Y"))))
15613 month (string-to-number (match-string 3 ans))
15614 day (string-to-number (match-string 4 ans)))
15615 (if (< year 100) (setq year (+ 2000 year)))
15616 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15617 t nil ans)))
15619 ;; Help matching dotted european dates
15620 (when (string-match
15621 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15622 (setq year (if (match-end 3)
15623 (string-to-number (match-string 3 ans))
15624 (progn (setq kill-year t)
15625 (string-to-number (format-time-string "%Y"))))
15626 day (string-to-number (match-string 1 ans))
15627 month (string-to-number (match-string 2 ans))
15628 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15629 t nil ans)))
15631 ;; Help matching american dates, like 5/30 or 5/30/7
15632 (when (string-match
15633 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15634 (setq year (if (match-end 4)
15635 (string-to-number (match-string 4 ans))
15636 (progn (setq kill-year t)
15637 (string-to-number (format-time-string "%Y"))))
15638 month (string-to-number (match-string 1 ans))
15639 day (string-to-number (match-string 2 ans)))
15640 (if (< year 100) (setq year (+ 2000 year)))
15641 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15642 t nil ans)))
15643 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15644 ;; If there is a time with am/pm, and *no* time without it, we convert
15645 ;; so that matching will be successful.
15646 (loop for i from 1 to 2 do ; twice, for end time as well
15647 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15648 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15649 (setq hour (string-to-number (match-string 1 ans))
15650 minute (if (match-end 3)
15651 (string-to-number (match-string 3 ans))
15653 pm (equal ?p
15654 (string-to-char (downcase (match-string 4 ans)))))
15655 (if (and (= hour 12) (not pm))
15656 (setq hour 0)
15657 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15658 (setq ans (replace-match (format "%02d:%02d" hour minute)
15659 t t ans))))
15661 ;; Check if a time range is given as a duration
15662 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15663 (setq hour (string-to-number (match-string 1 ans))
15664 h2 (+ hour (string-to-number (match-string 3 ans)))
15665 minute (string-to-number (match-string 2 ans))
15666 m2 (+ minute (if (match-end 5) (string-to-number
15667 (match-string 5 ans))0)))
15668 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15669 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15670 t t ans)))
15672 ;; Check if there is a time range
15673 (when (boundp 'org-end-time-was-given)
15674 (setq org-time-was-given nil)
15675 (when (and (string-match org-plain-time-of-day-regexp ans)
15676 (match-end 8))
15677 (setq org-end-time-was-given (match-string 8 ans))
15678 (setq ans (concat (substring ans 0 (match-beginning 7))
15679 (substring ans (match-end 7))))))
15681 (setq tl (parse-time-string ans)
15682 day (or (nth 3 tl) (nth 3 org-defdecode))
15683 month (or (nth 4 tl)
15684 (if (and org-read-date-prefer-future
15685 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15686 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15687 (nth 4 org-defdecode)))
15688 year (or (and (not kill-year) (nth 5 tl))
15689 (if (and org-read-date-prefer-future
15690 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15691 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15692 (nth 5 org-defdecode)))
15693 hour (or (nth 2 tl) (nth 2 org-defdecode))
15694 minute (or (nth 1 tl) (nth 1 org-defdecode))
15695 second (or (nth 0 tl) 0)
15696 wday (nth 6 tl))
15698 (when (and (eq org-read-date-prefer-future 'time)
15699 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15700 (equal day (nth 3 nowdecode))
15701 (equal month (nth 4 nowdecode))
15702 (equal year (nth 5 nowdecode))
15703 (nth 2 tl)
15704 (or (< (nth 2 tl) (nth 2 nowdecode))
15705 (and (= (nth 2 tl) (nth 2 nowdecode))
15706 (nth 1 tl)
15707 (< (nth 1 tl) (nth 1 nowdecode)))))
15708 (setq day (1+ day)
15709 futurep t))
15711 ;; Special date definitions below
15712 (cond
15713 (iso-week
15714 ;; There was an iso week
15715 (require 'cal-iso)
15716 (setq futurep nil)
15717 (setq year (or iso-year year)
15718 day (or iso-weekday wday 1)
15719 wday nil ; to make sure that the trigger below does not match
15720 iso-date (calendar-gregorian-from-absolute
15721 (calendar-absolute-from-iso
15722 (list iso-week day year))))
15723 ; FIXME: Should we also push ISO weeks into the future?
15724 ; (when (and org-read-date-prefer-future
15725 ; (not iso-year)
15726 ; (< (calendar-absolute-from-gregorian iso-date)
15727 ; (time-to-days (current-time))))
15728 ; (setq year (1+ year)
15729 ; iso-date (calendar-gregorian-from-absolute
15730 ; (calendar-absolute-from-iso
15731 ; (list iso-week day year)))))
15732 (setq month (car iso-date)
15733 year (nth 2 iso-date)
15734 day (nth 1 iso-date)))
15735 (deltan
15736 (setq futurep nil)
15737 (unless deltadef
15738 (let ((now (decode-time (current-time))))
15739 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15740 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15741 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15742 ((equal deltaw "m") (setq month (+ month deltan)))
15743 ((equal deltaw "y") (setq year (+ year deltan)))))
15744 ((and wday (not (nth 3 tl)))
15745 ;; Weekday was given, but no day, so pick that day in the week
15746 ;; on or after the derived date.
15747 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15748 (unless (equal wday wday1)
15749 (setq day (+ day (% (- wday wday1 -7) 7))))))
15750 (if (and (boundp 'org-time-was-given)
15751 (nth 2 tl))
15752 (setq org-time-was-given t))
15753 (if (< year 100) (setq year (+ 2000 year)))
15754 ;; Check of the date is representable
15755 (if org-read-date-force-compatible-dates
15756 (progn
15757 (if (< year 1970)
15758 (setq year 1970 org-read-date-analyze-forced-year t))
15759 (if (> year 2037)
15760 (setq year 2037 org-read-date-analyze-forced-year t)))
15761 (condition-case nil
15762 (ignore (encode-time second minute hour day month year))
15763 (error
15764 (setq year (nth 5 org-defdecode))
15765 (setq org-read-date-analyze-forced-year t))))
15766 (setq org-read-date-analyze-futurep futurep)
15767 (list second minute hour day month year)))
15769 (defvar parse-time-weekdays)
15770 (defun org-read-date-get-relative (s today default)
15771 "Check string S for special relative date string.
15772 TODAY and DEFAULT are internal times, for today and for a default.
15773 Return shift list (N what def-flag)
15774 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15775 N is the number of WHATs to shift.
15776 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15777 the DEFAULT date rather than TODAY."
15778 (require 'parse-time)
15779 (when (and
15780 (string-match
15781 (concat
15782 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15783 "\\([0-9]+\\)?"
15784 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15785 "\\([ \t]\\|$\\)") s)
15786 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15787 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15788 (string-to-char (substring (match-string 1 s) -1))
15789 ?+))
15790 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15791 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15792 (what (if (match-end 3) (match-string 3 s) "d"))
15793 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15794 (date (if rel default today))
15795 (wday (nth 6 (decode-time date)))
15796 delta)
15797 (if wday1
15798 (progn
15799 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15800 (if (= dir ?-) (setq delta (- delta 7)))
15801 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15802 (list delta "d" rel))
15803 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15805 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15806 "Turn a user-specified date into the internal representation.
15807 The internal representation needed by the calendar is (month day year).
15808 This is a wrapper to handle the brain-dead convention in calendar that
15809 user function argument order change dependent on argument order."
15810 (if (boundp 'calendar-date-style)
15811 (cond
15812 ((eq calendar-date-style 'american)
15813 (list arg1 arg2 arg3))
15814 ((eq calendar-date-style 'european)
15815 (list arg2 arg1 arg3))
15816 ((eq calendar-date-style 'iso)
15817 (list arg2 arg3 arg1)))
15818 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15819 (if (org-bound-and-true-p european-calendar-style)
15820 (list arg2 arg1 arg3)
15821 (list arg1 arg2 arg3)))))
15823 (defun org-eval-in-calendar (form &optional keepdate)
15824 "Eval FORM in the calendar window and return to current window.
15825 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15826 otherwise stick to the current value of `org-ans2'."
15827 (let ((sf (selected-frame))
15828 (sw (selected-window)))
15829 (select-window (get-buffer-window "*Calendar*" t))
15830 (eval form)
15831 (when (and (not keepdate) (calendar-cursor-to-date))
15832 (let* ((date (calendar-cursor-to-date))
15833 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15834 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15835 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15836 (select-window sw)
15837 (org-select-frame-set-input-focus sf)))
15839 (defun org-calendar-select ()
15840 "Return to `org-read-date' with the date currently selected.
15841 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15842 (interactive)
15843 (when (calendar-cursor-to-date)
15844 (let* ((date (calendar-cursor-to-date))
15845 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15846 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15847 (if (active-minibuffer-window) (exit-minibuffer))))
15849 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15850 "Insert a date stamp for the date given by the internal TIME.
15851 WITH-HM means use the stamp format that includes the time of the day.
15852 INACTIVE means use square brackets instead of angular ones, so that the
15853 stamp will not contribute to the agenda.
15854 PRE and POST are optional strings to be inserted before and after the
15855 stamp.
15856 The command returns the inserted time stamp."
15857 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15858 stamp)
15859 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15860 (insert-before-markers (or pre ""))
15861 (when (listp extra)
15862 (setq extra (car extra))
15863 (if (and (stringp extra)
15864 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15865 (setq extra (format "-%02d:%02d"
15866 (string-to-number (match-string 1 extra))
15867 (string-to-number (match-string 2 extra))))
15868 (setq extra nil)))
15869 (when extra
15870 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15871 (insert-before-markers (setq stamp (format-time-string fmt time)))
15872 (insert-before-markers (or post ""))
15873 (setq org-last-inserted-timestamp stamp)))
15875 (defun org-toggle-time-stamp-overlays ()
15876 "Toggle the use of custom time stamp formats."
15877 (interactive)
15878 (setq org-display-custom-times (not org-display-custom-times))
15879 (unless org-display-custom-times
15880 (let ((p (point-min)) (bmp (buffer-modified-p)))
15881 (while (setq p (next-single-property-change p 'display))
15882 (if (and (get-text-property p 'display)
15883 (eq (get-text-property p 'face) 'org-date))
15884 (remove-text-properties
15885 p (setq p (next-single-property-change p 'display))
15886 '(display t))))
15887 (set-buffer-modified-p bmp)))
15888 (if (featurep 'xemacs)
15889 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15890 (org-restart-font-lock)
15891 (setq org-table-may-need-update t)
15892 (if org-display-custom-times
15893 (message "Time stamps are overlaid with custom format")
15894 (message "Time stamp overlays removed")))
15896 (defun org-display-custom-time (beg end)
15897 "Overlay modified time stamp format over timestamp between BEG and END."
15898 (let* ((ts (buffer-substring beg end))
15899 t1 w1 with-hm tf time str w2 (off 0))
15900 (save-match-data
15901 (setq t1 (org-parse-time-string ts t))
15902 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15903 (setq off (- (match-end 0) (match-beginning 0)))))
15904 (setq end (- end off))
15905 (setq w1 (- end beg)
15906 with-hm (and (nth 1 t1) (nth 2 t1))
15907 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15908 time (org-fix-decoded-time t1)
15909 str (org-add-props
15910 (format-time-string
15911 (substring tf 1 -1) (apply 'encode-time time))
15912 nil 'mouse-face 'highlight)
15913 w2 (length str))
15914 (if (not (= w2 w1))
15915 (add-text-properties (1+ beg) (+ 2 beg)
15916 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15917 (if (featurep 'xemacs)
15918 (progn
15919 (put-text-property beg end 'invisible t)
15920 (put-text-property beg end 'end-glyph (make-glyph str)))
15921 (put-text-property beg end 'display str))))
15923 (defun org-translate-time (string)
15924 "Translate all timestamps in STRING to custom format.
15925 But do this only if the variable `org-display-custom-times' is set."
15926 (when org-display-custom-times
15927 (save-match-data
15928 (let* ((start 0)
15929 (re org-ts-regexp-both)
15930 t1 with-hm inactive tf time str beg end)
15931 (while (setq start (string-match re string start))
15932 (setq beg (match-beginning 0)
15933 end (match-end 0)
15934 t1 (save-match-data
15935 (org-parse-time-string (substring string beg end) t))
15936 with-hm (and (nth 1 t1) (nth 2 t1))
15937 inactive (equal (substring string beg (1+ beg)) "[")
15938 tf (funcall (if with-hm 'cdr 'car)
15939 org-time-stamp-custom-formats)
15940 time (org-fix-decoded-time t1)
15941 str (format-time-string
15942 (concat
15943 (if inactive "[" "<") (substring tf 1 -1)
15944 (if inactive "]" ">"))
15945 (apply 'encode-time time))
15946 string (replace-match str t t string)
15947 start (+ start (length str)))))))
15948 string)
15950 (defun org-fix-decoded-time (time)
15951 "Set 0 instead of nil for the first 6 elements of time.
15952 Don't touch the rest."
15953 (let ((n 0))
15954 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15956 (defun org-days-to-time (timestamp-string)
15957 "Difference between TIMESTAMP-STRING and now in days."
15958 (- (time-to-days (org-time-string-to-time timestamp-string))
15959 (time-to-days (current-time))))
15961 (defun org-deadline-close (timestamp-string &optional ndays)
15962 "Is the time in TIMESTAMP-STRING close to the current date?"
15963 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15964 (and (< (org-days-to-time timestamp-string) ndays)
15965 (not (org-entry-is-done-p))))
15967 (defun org-get-wdays (ts)
15968 "Get the deadline lead time appropriate for timestring TS."
15969 (cond
15970 ((<= org-deadline-warning-days 0)
15971 ;; 0 or negative, enforce this value no matter what
15972 (- org-deadline-warning-days))
15973 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15974 ;; lead time is specified.
15975 (floor (* (string-to-number (match-string 1 ts))
15976 (cdr (assoc (match-string 2 ts)
15977 '(("d" . 1) ("w" . 7)
15978 ("m" . 30.4) ("y" . 365.25)))))))
15979 ;; go for the default.
15980 (t org-deadline-warning-days)))
15982 (defun org-calendar-select-mouse (ev)
15983 "Return to `org-read-date' with the date currently selected.
15984 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15985 (interactive "e")
15986 (mouse-set-point ev)
15987 (when (calendar-cursor-to-date)
15988 (let* ((date (calendar-cursor-to-date))
15989 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15990 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15991 (if (active-minibuffer-window) (exit-minibuffer))))
15993 (defun org-check-deadlines (ndays)
15994 "Check if there are any deadlines due or past due.
15995 A deadline is considered due if it happens within `org-deadline-warning-days'
15996 days from today's date. If the deadline appears in an entry marked DONE,
15997 it is not shown. The prefix arg NDAYS can be used to test that many
15998 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15999 (interactive "P")
16000 (let* ((org-warn-days
16001 (cond
16002 ((equal ndays '(4)) 100000)
16003 (ndays (prefix-numeric-value ndays))
16004 (t (abs org-deadline-warning-days))))
16005 (case-fold-search nil)
16006 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16007 (callback
16008 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16010 (message "%d deadlines past-due or due within %d days"
16011 (org-occur regexp nil callback)
16012 org-warn-days)))
16014 (defsubst org-re-timestamp (type)
16015 "Return a regexp for timestamp TYPE.
16016 Allowed values for TYPE are:
16018 all: all timestamps
16019 active: only active timestamps (<...>)
16020 inactive: only inactive timestamps ([...])
16021 scheduled: only scheduled timestamps
16022 deadline: only deadline timestamps
16024 When TYPE is nil, fall back on returning a regexp that matches
16025 both scheduled and deadline timestamps."
16026 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16027 ((eq type 'active) org-ts-regexp)
16028 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16029 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16030 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16031 ((eq type 'scheduled-or-deadline)
16032 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16034 (defun org-check-before-date (date)
16035 "Check if there are deadlines or scheduled entries before DATE."
16036 (interactive (list (org-read-date)))
16037 (let ((case-fold-search nil)
16038 (regexp (org-re-timestamp org-ts-type))
16039 (callback
16040 (lambda () (time-less-p
16041 (org-time-string-to-time (match-string 1))
16042 (org-time-string-to-time date)))))
16043 (message "%d entries before %s"
16044 (org-occur regexp nil callback) date)))
16046 (defun org-check-after-date (date)
16047 "Check if there are deadlines or scheduled entries after DATE."
16048 (interactive (list (org-read-date)))
16049 (let ((case-fold-search nil)
16050 (regexp (org-re-timestamp org-ts-type))
16051 (callback
16052 (lambda () (not
16053 (time-less-p
16054 (org-time-string-to-time (match-string 1))
16055 (org-time-string-to-time date))))))
16056 (message "%d entries after %s"
16057 (org-occur regexp nil callback) date)))
16059 (defun org-check-dates-range (start-date end-date)
16060 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16061 (interactive (list (org-read-date nil nil nil "Range starts")
16062 (org-read-date nil nil nil "Range end")))
16063 (let ((case-fold-search nil)
16064 (regexp (org-re-timestamp org-ts-type))
16065 (callback
16066 (lambda ()
16067 (let ((match (match-string 1)))
16068 (and
16069 (not (time-less-p
16070 (org-time-string-to-time match)
16071 (org-time-string-to-time start-date)))
16072 (time-less-p
16073 (org-time-string-to-time match)
16074 (org-time-string-to-time end-date)))))))
16075 (message "%d entries between %s and %s"
16076 (org-occur regexp nil callback) start-date end-date)))
16078 (defun org-evaluate-time-range (&optional to-buffer)
16079 "Evaluate a time range by computing the difference between start and end.
16080 Normally the result is just printed in the echo area, but with prefix arg
16081 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16082 If the time range is actually in a table, the result is inserted into the
16083 next column.
16084 For time difference computation, a year is assumed to be exactly 365
16085 days in order to avoid rounding problems."
16086 (interactive "P")
16088 (org-clock-update-time-maybe)
16089 (save-excursion
16090 (unless (org-at-date-range-p t)
16091 (goto-char (point-at-bol))
16092 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16093 (if (not (org-at-date-range-p t))
16094 (error "Not at a time-stamp range, and none found in current line")))
16095 (let* ((ts1 (match-string 1))
16096 (ts2 (match-string 2))
16097 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16098 (match-end (match-end 0))
16099 (time1 (org-time-string-to-time ts1))
16100 (time2 (org-time-string-to-time ts2))
16101 (t1 (org-float-time time1))
16102 (t2 (org-float-time time2))
16103 (diff (abs (- t2 t1)))
16104 (negative (< (- t2 t1) 0))
16105 ;; (ys (floor (* 365 24 60 60)))
16106 (ds (* 24 60 60))
16107 (hs (* 60 60))
16108 (fy "%dy %dd %02d:%02d")
16109 (fy1 "%dy %dd")
16110 (fd "%dd %02d:%02d")
16111 (fd1 "%dd")
16112 (fh "%02d:%02d")
16113 y d h m align)
16114 (if havetime
16115 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16117 d (floor (/ diff ds)) diff (mod diff ds)
16118 h (floor (/ diff hs)) diff (mod diff hs)
16119 m (floor (/ diff 60)))
16120 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16122 d (floor (+ (/ diff ds) 0.5))
16123 h 0 m 0))
16124 (if (not to-buffer)
16125 (message "%s" (org-make-tdiff-string y d h m))
16126 (if (org-at-table-p)
16127 (progn
16128 (goto-char match-end)
16129 (setq align t)
16130 (and (looking-at " *|") (goto-char (match-end 0))))
16131 (goto-char match-end))
16132 (if (looking-at
16133 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16134 (replace-match ""))
16135 (if negative (insert " -"))
16136 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16137 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16138 (insert " " (format fh h m))))
16139 (if align (org-table-align))
16140 (message "Time difference inserted")))))
16142 (defun org-make-tdiff-string (y d h m)
16143 (let ((fmt "")
16144 (l nil))
16145 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16146 l (push y l)))
16147 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16148 l (push d l)))
16149 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16150 l (push h l)))
16151 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16152 l (push m l)))
16153 (apply 'format fmt (nreverse l))))
16155 (defun org-time-string-to-time (s &optional buffer pos)
16156 "Convert a timestamp string into internal time."
16157 (condition-case errdata
16158 (apply 'encode-time (org-parse-time-string s))
16159 (error (error "Bad timestamp `%s'%s\nError was: %s"
16160 s (if (not (and buffer pos))
16162 (format " at %d in buffer `%s'" pos buffer))
16163 (cdr errdata)))))
16165 (defun org-time-string-to-seconds (s)
16166 "Convert a timestamp string to a number of seconds."
16167 (org-float-time (org-time-string-to-time s)))
16169 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16170 "Convert a time stamp to an absolute day number.
16171 If there is a specifier for a cyclic time stamp, get the closest date to
16172 DAYNR.
16173 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16174 The variable date is bound by the calendar when this is called."
16175 (cond
16176 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16177 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16178 daynr
16179 (+ daynr 1000)))
16180 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16181 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16182 (time-to-days (current-time))) (match-string 0 s)
16183 prefer show-all))
16184 (t (time-to-days
16185 (condition-case errdata
16186 (apply 'encode-time (org-parse-time-string s))
16187 (error (error "Bad timestamp `%s'%s\nError was: %s"
16188 s (if (not (and buffer pos))
16190 (format " at %d in buffer `%s'" pos buffer))
16191 (cdr errdata))))))))
16193 (defun org-days-to-iso-week (days)
16194 "Return the iso week number."
16195 (require 'cal-iso)
16196 (car (calendar-iso-from-absolute days)))
16198 (defun org-small-year-to-year (year)
16199 "Convert 2-digit years into 4-digit years.
16200 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16201 The year 2000 cannot be abbreviated. Any year larger than 99
16202 is returned unchanged."
16203 (if (< year 38)
16204 (setq year (+ 2000 year))
16205 (if (< year 100)
16206 (setq year (+ 1900 year))))
16207 year)
16209 (defun org-time-from-absolute (d)
16210 "Return the time corresponding to date D.
16211 D may be an absolute day number, or a calendar-type list (month day year)."
16212 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16213 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16215 (defun org-calendar-holiday ()
16216 "List of holidays, for Diary display in Org-mode."
16217 (require 'holidays)
16218 (let ((hl (funcall
16219 (if (fboundp 'calendar-check-holidays)
16220 'calendar-check-holidays 'check-calendar-holidays) date)))
16221 (if hl (mapconcat 'identity hl "; "))))
16223 (defun org-diary-sexp-entry (sexp entry date)
16224 "Process a SEXP diary ENTRY for DATE."
16225 (require 'diary-lib)
16226 (let ((result (if calendar-debug-sexp
16227 (let ((stack-trace-on-error t))
16228 (eval (car (read-from-string sexp))))
16229 (condition-case nil
16230 (eval (car (read-from-string sexp)))
16231 (error
16232 (beep)
16233 (message "Bad sexp at line %d in %s: %s"
16234 (org-current-line)
16235 (buffer-file-name) sexp)
16236 (sleep-for 2))))))
16237 (cond ((stringp result) (split-string result "; "))
16238 ((and (consp result)
16239 (not (consp (cdr result)))
16240 (stringp (cdr result))) (cdr result))
16241 ((and (consp result)
16242 (stringp (car result))) result)
16243 (result entry))))
16245 (defun org-diary-to-ical-string (frombuf)
16246 "Get iCalendar entries from diary entries in buffer FROMBUF.
16247 This uses the icalendar.el library."
16248 (let* ((tmpdir (if (featurep 'xemacs)
16249 (temp-directory)
16250 temporary-file-directory))
16251 (tmpfile (make-temp-name
16252 (expand-file-name "orgics" tmpdir)))
16253 buf rtn b e)
16254 (with-current-buffer frombuf
16255 (icalendar-export-region (point-min) (point-max) tmpfile)
16256 (setq buf (find-buffer-visiting tmpfile))
16257 (set-buffer buf)
16258 (goto-char (point-min))
16259 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16260 (setq b (match-beginning 0)))
16261 (goto-char (point-max))
16262 (if (re-search-backward "^END:VEVENT" nil t)
16263 (setq e (match-end 0)))
16264 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16265 (kill-buffer buf)
16266 (delete-file tmpfile)
16267 rtn))
16269 (defun org-closest-date (start current change prefer show-all)
16270 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16271 When PREFER is `past', return a date that is either CURRENT or past.
16272 When PREFER is `future', return a date that is either CURRENT or future.
16273 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16274 ;; Make the proper lists from the dates
16275 (catch 'exit
16276 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16277 dn dw sday cday n1 n2 n0
16278 d m y y1 y2 date1 date2 nmonths nm ny m2)
16280 (setq start (org-date-to-gregorian start)
16281 current (org-date-to-gregorian
16282 (if show-all
16283 current
16284 (time-to-days (current-time))))
16285 sday (calendar-absolute-from-gregorian start)
16286 cday (calendar-absolute-from-gregorian current))
16288 (if (<= cday sday) (throw 'exit sday))
16290 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16291 (setq dn (string-to-number (match-string 1 change))
16292 dw (cdr (assoc (match-string 2 change) a1)))
16293 (error "Invalid change specifier: %s" change))
16294 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16295 (cond
16296 ((eq dw 'day)
16297 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16298 n2 (+ n1 dn)))
16299 ((eq dw 'year)
16300 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16301 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16302 (setq date1 (list m d y1)
16303 n1 (calendar-absolute-from-gregorian date1)
16304 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16305 n2 (calendar-absolute-from-gregorian date2)))
16306 ((eq dw 'month)
16307 ;; approx number of month between the two dates
16308 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16309 ;; How often does dn fit in there?
16310 (setq d (nth 1 start) m (car start) y (nth 2 start)
16311 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16312 m (+ m nm)
16313 ny (floor (/ m 12))
16314 y (+ y ny)
16315 m (- m (* ny 12)))
16316 (while (> m 12) (setq m (- m 12) y (1+ y)))
16317 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16318 (setq m2 (+ m dn) y2 y)
16319 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16320 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16321 (while (<= n2 cday)
16322 (setq n1 n2 m m2 y y2)
16323 (setq m2 (+ m dn) y2 y)
16324 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16325 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16326 ;; Make sure n1 is the earlier date
16327 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16328 (if show-all
16329 (cond
16330 ((eq prefer 'past) (if (= cday n2) n2 n1))
16331 ((eq prefer 'future) (if (= cday n1) n1 n2))
16332 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16333 (cond
16334 ((eq prefer 'past) (if (= cday n2) n2 n1))
16335 ((eq prefer 'future) (if (= cday n1) n1 n2))
16336 (t (if (= cday n1) n1 n2)))))))
16338 (defun org-date-to-gregorian (date)
16339 "Turn any specification of DATE into a Gregorian date for the calendar."
16340 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16341 ((and (listp date) (= (length date) 3)) date)
16342 ((stringp date)
16343 (setq date (org-parse-time-string date))
16344 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16345 ((listp date)
16346 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16348 (defun org-parse-time-string (s &optional nodefault)
16349 "Parse the standard Org-mode time string.
16350 This should be a lot faster than the normal `parse-time-string'.
16351 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16352 hour and minute fields will be nil if not given."
16353 (if (string-match org-ts-regexp0 s)
16354 (list 0
16355 (if (or (match-beginning 8) (not nodefault))
16356 (string-to-number (or (match-string 8 s) "0")))
16357 (if (or (match-beginning 7) (not nodefault))
16358 (string-to-number (or (match-string 7 s) "0")))
16359 (string-to-number (match-string 4 s))
16360 (string-to-number (match-string 3 s))
16361 (string-to-number (match-string 2 s))
16362 nil nil nil)
16363 (error "Not a standard Org-mode time string: %s" s)))
16365 (defun org-timestamp-up (&optional arg)
16366 "Increase the date item at the cursor by one.
16367 If the cursor is on the year, change the year. If it is on the month,
16368 the day or the time, change that.
16369 With prefix ARG, change by that many units."
16370 (interactive "p")
16371 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16373 (defun org-timestamp-down (&optional arg)
16374 "Decrease the date item at the cursor by one.
16375 If the cursor is on the year, change the year. If it is on the month,
16376 the day or the time, change that.
16377 With prefix ARG, change by that many units."
16378 (interactive "p")
16379 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16381 (defun org-timestamp-up-day (&optional arg)
16382 "Increase the date in the time stamp by one day.
16383 With prefix ARG, change that many days."
16384 (interactive "p")
16385 (if (and (not (org-at-timestamp-p t))
16386 (org-at-heading-p))
16387 (org-todo 'up)
16388 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16390 (defun org-timestamp-down-day (&optional arg)
16391 "Decrease the date in the time stamp by one day.
16392 With prefix ARG, change that many days."
16393 (interactive "p")
16394 (if (and (not (org-at-timestamp-p t))
16395 (org-at-heading-p))
16396 (org-todo 'down)
16397 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16399 (defun org-at-timestamp-p (&optional inactive-ok)
16400 "Determine if the cursor is in or at a timestamp."
16401 (interactive)
16402 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16403 (pos (point))
16404 (ans (or (looking-at tsr)
16405 (save-excursion
16406 (skip-chars-backward "^[<\n\r\t")
16407 (if (> (point) (point-min)) (backward-char 1))
16408 (and (looking-at tsr)
16409 (> (- (match-end 0) pos) -1))))))
16410 (and ans
16411 (boundp 'org-ts-what)
16412 (setq org-ts-what
16413 (cond
16414 ((= pos (match-beginning 0)) 'bracket)
16415 ;; Point is considered to be "on the bracket" whether
16416 ;; it's really on it or right after it.
16417 ((= pos (1- (match-end 0))) 'bracket)
16418 ((= pos (match-end 0)) 'after)
16419 ((org-pos-in-match-range pos 2) 'year)
16420 ((org-pos-in-match-range pos 3) 'month)
16421 ((org-pos-in-match-range pos 7) 'hour)
16422 ((org-pos-in-match-range pos 8) 'minute)
16423 ((or (org-pos-in-match-range pos 4)
16424 (org-pos-in-match-range pos 5)) 'day)
16425 ((and (> pos (or (match-end 8) (match-end 5)))
16426 (< pos (match-end 0)))
16427 (- pos (or (match-end 8) (match-end 5))))
16428 (t 'day))))
16429 ans))
16431 (defun org-toggle-timestamp-type ()
16432 "Toggle the type (<active> or [inactive]) of a time stamp."
16433 (interactive)
16434 (when (org-at-timestamp-p t)
16435 (let ((beg (match-beginning 0)) (end (match-end 0))
16436 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16437 (save-excursion
16438 (goto-char beg)
16439 (while (re-search-forward "[][<>]" end t)
16440 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16441 t t)))
16442 (message "Timestamp is now %sactive"
16443 (if (equal (char-after beg) ?<) "" "in")))))
16445 (defvar org-clock-history) ; defined in org-clock.el
16446 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16447 (defun org-timestamp-change (n &optional what updown)
16448 "Change the date in the time stamp at point.
16449 The date will be changed by N times WHAT. WHAT can be `day', `month',
16450 `year', `minute', `second'. If WHAT is not given, the cursor position
16451 in the timestamp determines what will be changed."
16452 (let ((origin (point)) origin-cat
16453 with-hm inactive
16454 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16455 org-ts-what
16456 extra rem
16457 ts time time0 fixnext clrgx)
16458 (if (not (org-at-timestamp-p t))
16459 (error "Not at a timestamp"))
16460 (if (and (not what) (eq org-ts-what 'bracket))
16461 (org-toggle-timestamp-type)
16462 ;; Point isn't on brackets. Remember the part of the time-stamp
16463 ;; the point was in. Indeed, size of time-stamps may change,
16464 ;; but point must be kept in the same category nonetheless.
16465 (setq origin-cat org-ts-what)
16466 (if (and (not what) (not (eq org-ts-what 'day))
16467 org-display-custom-times
16468 (get-text-property (point) 'display)
16469 (not (get-text-property (1- (point)) 'display)))
16470 (setq org-ts-what 'day))
16471 (setq org-ts-what (or what org-ts-what)
16472 inactive (= (char-after (match-beginning 0)) ?\[)
16473 ts (match-string 0))
16474 (replace-match "")
16475 (if (string-match
16476 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16478 (setq extra (match-string 1 ts)))
16479 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16480 (setq with-hm t))
16481 (setq time0 (org-parse-time-string ts))
16482 (when (and updown
16483 (eq org-ts-what 'minute)
16484 (not current-prefix-arg))
16485 ;; This looks like s-up and s-down. Change by one rounding step.
16486 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16487 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16488 (setcar (cdr time0) (+ (nth 1 time0)
16489 (if (> n 0) (- rem) (- dm rem))))))
16490 (setq time
16491 (encode-time (or (car time0) 0)
16492 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16493 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16494 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16495 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16496 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16497 (nthcdr 6 time0)))
16498 (when (and (member org-ts-what '(hour minute))
16499 extra
16500 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16501 (setq extra (org-modify-ts-extra
16502 extra
16503 (if (eq org-ts-what 'hour) 2 5)
16504 n dm)))
16505 (when (integerp org-ts-what)
16506 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16507 (if (eq what 'calendar)
16508 (let ((cal-date (org-get-date-from-calendar)))
16509 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16510 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16511 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16512 (setcar time0 (or (car time0) 0))
16513 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16514 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16515 (setq time (apply 'encode-time time0))))
16516 ;; Insert the new time-stamp, and ensure point stays in the same
16517 ;; category as before (i.e. not after the last position in that
16518 ;; category).
16519 (let ((pos (point)))
16520 ;; Stay before inserted string. `save-excursion' is of no use.
16521 (setq org-last-changed-timestamp
16522 (org-insert-time-stamp time with-hm inactive nil nil extra))
16523 (goto-char pos))
16524 (save-match-data
16525 (looking-at org-ts-regexp3)
16526 (goto-char (cond
16527 ;; `day' category ends before `hour' if any, or at
16528 ;; the end of the day name.
16529 ((eq origin-cat 'day)
16530 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16531 ((eq origin-cat 'hour) (min (match-end 7) origin))
16532 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16533 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16534 ;; `year' and `month' have both fixed size: point
16535 ;; couldn't have moved into another part.
16536 (t origin))))
16537 ;; Update clock if on a CLOCK line.
16538 (org-clock-update-time-maybe)
16539 ;; Maybe adjust the closest clock in `org-clock-history'
16540 (when org-clock-adjust-closest
16541 (if (not (and (org-at-clock-log-p)
16542 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16543 org-clock-history))))))
16544 (message "No clock to adjust")
16545 (cond ((save-excursion ; fix previous clock?
16546 (re-search-backward org-ts-regexp0 nil t)
16547 (org-looking-back (concat org-clock-string " \\[")))
16548 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16549 ((save-excursion ; fix next clock?
16550 (re-search-backward org-ts-regexp0 nil t)
16551 (looking-at (concat org-ts-regexp0 "\\] =>")))
16552 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16553 (save-window-excursion
16554 ;; Find closest clock to point, adjust the previous/next one in history
16555 (let* ((p (save-excursion (org-back-to-heading t)))
16556 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16557 (clfixnth
16558 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16559 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16560 (if (not clfixpos)
16561 (message "No clock to adjust")
16562 (save-excursion
16563 (org-goto-marker-or-bmk clfixpos)
16564 (org-show-subtree)
16565 (when (re-search-forward clrgx nil t)
16566 (goto-char (match-beginning 1))
16567 (let (org-clock-adjust-closest)
16568 (org-timestamp-change n org-ts-what updown))
16569 (message "Clock adjusted in %s for heading: %s"
16570 (file-name-nondirectory (buffer-file-name))
16571 (org-get-heading t t)))))))))
16572 ;; Try to recenter the calendar window, if any.
16573 (if (and org-calendar-follow-timestamp-change
16574 (get-buffer-window "*Calendar*" t)
16575 (memq org-ts-what '(day month year)))
16576 (org-recenter-calendar (time-to-days time))))))
16578 (defun org-modify-ts-extra (s pos n dm)
16579 "Change the different parts of the lead-time and repeat fields in timestamp."
16580 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16581 ng h m new rem)
16582 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16583 (cond
16584 ((or (org-pos-in-match-range pos 2)
16585 (org-pos-in-match-range pos 3))
16586 (setq m (string-to-number (match-string 3 s))
16587 h (string-to-number (match-string 2 s)))
16588 (if (org-pos-in-match-range pos 2)
16589 (setq h (+ h n))
16590 (setq n (* dm (org-no-warnings (signum n))))
16591 (when (not (= 0 (setq rem (% m dm))))
16592 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16593 (setq m (+ m n)))
16594 (if (< m 0) (setq m (+ m 60) h (1- h)))
16595 (if (> m 59) (setq m (- m 60) h (1+ h)))
16596 (setq h (min 24 (max 0 h)))
16597 (setq ng 1 new (format "-%02d:%02d" h m)))
16598 ((org-pos-in-match-range pos 6)
16599 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16600 ((org-pos-in-match-range pos 5)
16601 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16603 ((org-pos-in-match-range pos 9)
16604 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16605 ((org-pos-in-match-range pos 8)
16606 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16608 (when ng
16609 (setq s (concat
16610 (substring s 0 (match-beginning ng))
16612 (substring s (match-end ng))))))
16615 (defun org-recenter-calendar (date)
16616 "If the calendar is visible, recenter it to DATE."
16617 (let ((cwin (get-buffer-window "*Calendar*" t)))
16618 (when cwin
16619 (let ((calendar-move-hook nil))
16620 (with-selected-window cwin
16621 (calendar-goto-date (if (listp date) date
16622 (calendar-gregorian-from-absolute date))))))))
16624 (defun org-goto-calendar (&optional arg)
16625 "Go to the Emacs calendar at the current date.
16626 If there is a time stamp in the current line, go to that date.
16627 A prefix ARG can be used to force the current date."
16628 (interactive "P")
16629 (let ((tsr org-ts-regexp) diff
16630 (calendar-move-hook nil)
16631 (calendar-view-holidays-initially-flag nil)
16632 (calendar-view-diary-initially-flag nil))
16633 (if (or (org-at-timestamp-p)
16634 (save-excursion
16635 (beginning-of-line 1)
16636 (looking-at (concat ".*" tsr))))
16637 (let ((d1 (time-to-days (current-time)))
16638 (d2 (time-to-days
16639 (org-time-string-to-time (match-string 1)))))
16640 (setq diff (- d2 d1))))
16641 (calendar)
16642 (calendar-goto-today)
16643 (if (and diff (not arg)) (calendar-forward-day diff))))
16645 (defun org-get-date-from-calendar ()
16646 "Return a list (month day year) of date at point in calendar."
16647 (with-current-buffer "*Calendar*"
16648 (save-match-data
16649 (calendar-cursor-to-date))))
16651 (defun org-date-from-calendar ()
16652 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16653 If there is already a time stamp at the cursor position, update it."
16654 (interactive)
16655 (if (org-at-timestamp-p t)
16656 (org-timestamp-change 0 'calendar)
16657 (let ((cal-date (org-get-date-from-calendar)))
16658 (org-insert-time-stamp
16659 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16661 (defun org-minutes-to-hh:mm-string (m)
16662 "Compute H:MM from a number of minutes."
16663 (let ((h (/ m 60)))
16664 (setq m (- m (* 60 h)))
16665 (format org-time-clocksum-format h m)))
16667 (defun org-hh:mm-string-to-minutes (s)
16668 "Convert a string H:MM to a number of minutes.
16669 If the string is just a number, interpret it as minutes.
16670 In fact, the first hh:mm or number in the string will be taken,
16671 there can be extra stuff in the string.
16672 If no number is found, the return value is 0."
16673 (cond
16674 ((integerp s) s)
16675 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16676 (+ (* (string-to-number (match-string 1 s)) 60)
16677 (string-to-number (match-string 2 s))))
16678 ((string-match "\\([0-9]+\\)" s)
16679 (string-to-number (match-string 1 s)))
16680 (t 0)))
16682 (defcustom org-effort-durations
16683 `(("h" . 60)
16684 ("d" . ,(* 60 8))
16685 ("w" . ,(* 60 8 5))
16686 ("m" . ,(* 60 8 5 4))
16687 ("y" . ,(* 60 8 5 40)))
16688 "Conversion factor to minutes for an effort modifier.
16690 Each entry has the form (MODIFIER . MINUTES).
16692 In an effort string, a number followed by MODIFIER is multiplied
16693 by the specified number of MINUTES to obtain an effort in
16694 minutes.
16696 For example, if the value of this variable is ((\"hours\" . 60)), then an
16697 effort string \"2hours\" is equivalent to 120 minutes."
16698 :group 'org-agenda
16699 :version "24.1"
16700 :type '(alist :key-type (string :tag "Modifier")
16701 :value-type (number :tag "Minutes")))
16703 (defun org-duration-string-to-minutes (s &optional output-to-string)
16704 "Convert a duration string S to minutes.
16706 A bare number is interpreted as minutes, modifiers can be set by
16707 customizing `org-effort-durations' (which see).
16709 Entries containing a colon are interpreted as H:MM by
16710 `org-hh:mm-string-to-minutes'."
16711 (let ((result 0)
16712 (re (concat "\\([0-9.]+\\) *\\("
16713 (regexp-opt (mapcar 'car org-effort-durations))
16714 "\\)")))
16715 (while (string-match re s)
16716 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16717 (string-to-number (match-string 1 s))))
16718 (setq s (replace-match "" nil t s)))
16719 (setq result (floor result))
16720 (incf result (org-hh:mm-string-to-minutes s))
16721 (if output-to-string (number-to-string result) result)))
16723 ;;;; Files
16725 (defun org-save-all-org-buffers ()
16726 "Save all Org-mode buffers without user confirmation."
16727 (interactive)
16728 (message "Saving all Org-mode buffers...")
16729 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16730 (when (featurep 'org-id) (org-id-locations-save))
16731 (message "Saving all Org-mode buffers... done"))
16733 (defun org-revert-all-org-buffers ()
16734 "Revert all Org-mode buffers.
16735 Prompt for confirmation when there are unsaved changes.
16736 Be sure you know what you are doing before letting this function
16737 overwrite your changes.
16739 This function is useful in a setup where one tracks org files
16740 with a version control system, to revert on one machine after pulling
16741 changes from another. I believe the procedure must be like this:
16743 1. M-x org-save-all-org-buffers
16744 2. Pull changes from the other machine, resolve conflicts
16745 3. M-x org-revert-all-org-buffers"
16746 (interactive)
16747 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16748 (error "Abort"))
16749 (save-excursion
16750 (save-window-excursion
16751 (mapc
16752 (lambda (b)
16753 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16754 (with-current-buffer b buffer-file-name))
16755 (org-pop-to-buffer-same-window b)
16756 (revert-buffer t 'no-confirm)))
16757 (buffer-list))
16758 (when (and (featurep 'org-id) org-id-track-globally)
16759 (org-id-locations-load)))))
16761 ;;;; Agenda files
16763 ;;;###autoload
16764 (defun org-switchb (&optional arg)
16765 "Switch between Org buffers.
16766 With one prefix argument, restrict available buffers to files.
16767 With two prefix arguments, restrict available buffers to agenda files.
16769 Defaults to `iswitchb' for buffer name completion.
16770 Set `org-completion-use-ido' to make it use ido instead."
16771 (interactive "P")
16772 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16773 ((equal arg '(16)) (org-buffer-list 'agenda))
16774 (t (org-buffer-list))))
16775 (org-completion-use-iswitchb org-completion-use-iswitchb)
16776 (org-completion-use-ido org-completion-use-ido))
16777 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16778 (setq org-completion-use-iswitchb t))
16779 (org-pop-to-buffer-same-window
16780 (org-icompleting-read "Org buffer: "
16781 (mapcar 'list (mapcar 'buffer-name blist))
16782 nil t))))
16784 ;;; Define some older names previously used for this functionality
16785 ;;;###autoload
16786 (defalias 'org-ido-switchb 'org-switchb)
16787 ;;;###autoload
16788 (defalias 'org-iswitchb 'org-switchb)
16790 (defun org-buffer-list (&optional predicate exclude-tmp)
16791 "Return a list of Org buffers.
16792 PREDICATE can be `export', `files' or `agenda'.
16794 export restrict the list to Export buffers.
16795 files restrict the list to buffers visiting Org files.
16796 agenda restrict the list to buffers visiting agenda files.
16798 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16799 (let* ((bfn nil)
16800 (agenda-files (and (eq predicate 'agenda)
16801 (mapcar 'file-truename (org-agenda-files t))))
16802 (filter
16803 (cond
16804 ((eq predicate 'files)
16805 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16806 ((eq predicate 'export)
16807 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16808 ((eq predicate 'agenda)
16809 (lambda (b)
16810 (with-current-buffer b
16811 (and (derived-mode-p 'org-mode)
16812 (setq bfn (buffer-file-name b))
16813 (member (file-truename bfn) agenda-files)))))
16814 (t (lambda (b) (with-current-buffer b
16815 (or (derived-mode-p 'org-mode)
16816 (string-match "\*Org .*Export"
16817 (buffer-name b)))))))))
16818 (delq nil
16819 (mapcar
16820 (lambda(b)
16821 (if (and (funcall filter b)
16822 (or (not exclude-tmp)
16823 (not (string-match "tmp" (buffer-name b)))))
16825 nil))
16826 (buffer-list)))))
16828 (defun org-agenda-files (&optional unrestricted archives)
16829 "Get the list of agenda files.
16830 Optional UNRESTRICTED means return the full list even if a restriction
16831 is currently in place.
16832 When ARCHIVES is t, include all archive files that are really being
16833 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16834 `org-agenda-archives-mode' is t."
16835 (let ((files
16836 (cond
16837 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16838 ((stringp org-agenda-files) (org-read-agenda-file-list))
16839 ((listp org-agenda-files) org-agenda-files)
16840 (t (error "Invalid value of `org-agenda-files'")))))
16841 (setq files (apply 'append
16842 (mapcar (lambda (f)
16843 (if (file-directory-p f)
16844 (directory-files
16845 f t org-agenda-file-regexp)
16846 (list f)))
16847 files)))
16848 (when org-agenda-skip-unavailable-files
16849 (setq files (delq nil
16850 (mapcar (function
16851 (lambda (file)
16852 (and (file-readable-p file) file)))
16853 files))))
16854 (when (or (eq archives t)
16855 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16856 (setq files (org-add-archive-files files)))
16857 files))
16859 (defun org-agenda-file-p (&optional file)
16860 "Return non-nil, if FILE is an agenda file.
16861 If FILE is omitted, use the file associated with the current
16862 buffer."
16863 (member (or file (buffer-file-name))
16864 (org-agenda-files t)))
16866 (defun org-edit-agenda-file-list ()
16867 "Edit the list of agenda files.
16868 Depending on setup, this either uses customize to edit the variable
16869 `org-agenda-files', or it visits the file that is holding the list. In the
16870 latter case, the buffer is set up in a way that saving it automatically kills
16871 the buffer and restores the previous window configuration."
16872 (interactive)
16873 (if (stringp org-agenda-files)
16874 (let ((cw (current-window-configuration)))
16875 (find-file org-agenda-files)
16876 (org-set-local 'org-window-configuration cw)
16877 (org-add-hook 'after-save-hook
16878 (lambda ()
16879 (set-window-configuration
16880 (prog1 org-window-configuration
16881 (kill-buffer (current-buffer))))
16882 (org-install-agenda-files-menu)
16883 (message "New agenda file list installed"))
16884 nil 'local)
16885 (message "%s" (substitute-command-keys
16886 "Edit list and finish with \\[save-buffer]")))
16887 (customize-variable 'org-agenda-files)))
16889 (defun org-store-new-agenda-file-list (list)
16890 "Set new value for the agenda file list and save it correctly."
16891 (if (stringp org-agenda-files)
16892 (let ((fe (org-read-agenda-file-list t)) b u)
16893 (while (setq b (find-buffer-visiting org-agenda-files))
16894 (kill-buffer b))
16895 (with-temp-file org-agenda-files
16896 (insert
16897 (mapconcat
16898 (lambda (f) ;; Keep un-expanded entries.
16899 (if (setq u (assoc f fe))
16900 (cdr u)
16902 list "\n")
16903 "\n")))
16904 (let ((org-mode-hook nil) (org-inhibit-startup t)
16905 (org-insert-mode-line-in-empty-file nil))
16906 (setq org-agenda-files list)
16907 (customize-save-variable 'org-agenda-files org-agenda-files))))
16909 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16910 "Read the list of agenda files from a file.
16911 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16912 filenames, used by `org-store-new-agenda-file-list' to write back
16913 un-expanded file names."
16914 (when (file-directory-p org-agenda-files)
16915 (error "`org-agenda-files' cannot be a single directory"))
16916 (when (stringp org-agenda-files)
16917 (with-temp-buffer
16918 (insert-file-contents org-agenda-files)
16919 (mapcar
16920 (lambda (f)
16921 (let ((e (expand-file-name (substitute-in-file-name f)
16922 org-directory)))
16923 (if pair-with-expansion
16924 (cons e f)
16925 e)))
16926 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16928 ;;;###autoload
16929 (defun org-cycle-agenda-files ()
16930 "Cycle through the files in `org-agenda-files'.
16931 If the current buffer visits an agenda file, find the next one in the list.
16932 If the current buffer does not, find the first agenda file."
16933 (interactive)
16934 (let* ((fs (org-agenda-files t))
16935 (files (append fs (list (car fs))))
16936 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16937 file)
16938 (unless files (error "No agenda files"))
16939 (catch 'exit
16940 (while (setq file (pop files))
16941 (if (equal (file-truename file) tcf)
16942 (when (car files)
16943 (find-file (car files))
16944 (throw 'exit t))))
16945 (find-file (car fs)))
16946 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16948 (defun org-agenda-file-to-front (&optional to-end)
16949 "Move/add the current file to the top of the agenda file list.
16950 If the file is not present in the list, it is added to the front. If it is
16951 present, it is moved there. With optional argument TO-END, add/move to the
16952 end of the list."
16953 (interactive "P")
16954 (let ((org-agenda-skip-unavailable-files nil)
16955 (file-alist (mapcar (lambda (x)
16956 (cons (file-truename x) x))
16957 (org-agenda-files t)))
16958 (ctf (file-truename buffer-file-name))
16959 x had)
16960 (setq x (assoc ctf file-alist) had x)
16962 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16963 (if to-end
16964 (setq file-alist (append (delq x file-alist) (list x)))
16965 (setq file-alist (cons x (delq x file-alist))))
16966 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16967 (org-install-agenda-files-menu)
16968 (message "File %s to %s of agenda file list"
16969 (if had "moved" "added") (if to-end "end" "front"))))
16971 (defun org-remove-file (&optional file)
16972 "Remove current file from the list of files in variable `org-agenda-files'.
16973 These are the files which are being checked for agenda entries.
16974 Optional argument FILE means use this file instead of the current."
16975 (interactive)
16976 (let* ((org-agenda-skip-unavailable-files nil)
16977 (file (or file buffer-file-name))
16978 (true-file (file-truename file))
16979 (afile (abbreviate-file-name file))
16980 (files (delq nil (mapcar
16981 (lambda (x)
16982 (if (equal true-file
16983 (file-truename x))
16984 nil x))
16985 (org-agenda-files t)))))
16986 (if (not (= (length files) (length (org-agenda-files t))))
16987 (progn
16988 (org-store-new-agenda-file-list files)
16989 (org-install-agenda-files-menu)
16990 (message "Removed file: %s" afile))
16991 (message "File was not in list: %s (not removed)" afile))))
16993 (defun org-file-menu-entry (file)
16994 (vector file (list 'find-file file) t))
16996 (defun org-check-agenda-file (file)
16997 "Make sure FILE exists. If not, ask user what to do."
16998 (when (not (file-exists-p file))
16999 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17000 (abbreviate-file-name file))
17001 (let ((r (downcase (read-char-exclusive))))
17002 (cond
17003 ((equal r ?r)
17004 (org-remove-file file)
17005 (throw 'nextfile t))
17006 (t (error "Abort"))))))
17008 (defun org-get-agenda-file-buffer (file)
17009 "Get a buffer visiting FILE. If the buffer needs to be created, add
17010 it to the list of buffers which might be released later."
17011 (let ((buf (org-find-base-buffer-visiting file)))
17012 (if buf
17013 buf ; just return it
17014 ;; Make a new buffer and remember it
17015 (setq buf (find-file-noselect file))
17016 (if buf (push buf org-agenda-new-buffers))
17017 buf)))
17019 (defun org-release-buffers (blist)
17020 "Release all buffers in list, asking the user for confirmation when needed.
17021 When a buffer is unmodified, it is just killed. When modified, it is saved
17022 \(if the user agrees) and then killed."
17023 (let (buf file)
17024 (while (setq buf (pop blist))
17025 (setq file (buffer-file-name buf))
17026 (when (and (buffer-modified-p buf)
17027 file
17028 (y-or-n-p (format "Save file %s? " file)))
17029 (with-current-buffer buf (save-buffer)))
17030 (kill-buffer buf))))
17032 (defun org-agenda-prepare-buffers (files)
17033 "Create buffers for all agenda files, protect archived trees and comments."
17034 (interactive)
17035 (let ((pa '(:org-archived t))
17036 (pc '(:org-comment t))
17037 (pall '(:org-archived t :org-comment t))
17038 (inhibit-read-only t)
17039 (rea (concat ":" org-archive-tag ":"))
17040 bmp file re)
17041 (save-excursion
17042 (save-restriction
17043 (while (setq file (pop files))
17044 (catch 'nextfile
17045 (if (bufferp file)
17046 (set-buffer file)
17047 (org-check-agenda-file file)
17048 (set-buffer (org-get-agenda-file-buffer file)))
17049 (widen)
17050 (setq bmp (buffer-modified-p))
17051 (org-refresh-category-properties)
17052 (setq org-todo-keywords-for-agenda
17053 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17054 (setq org-done-keywords-for-agenda
17055 (append org-done-keywords-for-agenda org-done-keywords))
17056 (setq org-todo-keyword-alist-for-agenda
17057 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17058 (setq org-drawers-for-agenda
17059 (append org-drawers-for-agenda org-drawers))
17060 (setq org-tag-alist-for-agenda
17061 (append org-tag-alist-for-agenda org-tag-alist))
17063 (save-excursion
17064 (remove-text-properties (point-min) (point-max) pall)
17065 (when org-agenda-skip-archived-trees
17066 (goto-char (point-min))
17067 (while (re-search-forward rea nil t)
17068 (if (org-at-heading-p t)
17069 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17070 (goto-char (point-min))
17071 (setq re (format org-heading-keyword-regexp-format
17072 org-comment-string))
17073 (while (re-search-forward re nil t)
17074 (add-text-properties
17075 (match-beginning 0) (org-end-of-subtree t) pc)))
17076 (set-buffer-modified-p bmp)))))
17077 (setq org-todo-keywords-for-agenda
17078 (org-uniquify org-todo-keywords-for-agenda))
17079 (setq org-todo-keyword-alist-for-agenda
17080 (org-uniquify org-todo-keyword-alist-for-agenda)
17081 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17083 ;;;; Embedded LaTeX
17085 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17086 "Keymap for the minor `org-cdlatex-mode'.")
17088 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17089 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17090 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17091 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17092 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17094 (defvar org-cdlatex-texmathp-advice-is-done nil
17095 "Flag remembering if we have applied the advice to texmathp already.")
17097 (define-minor-mode org-cdlatex-mode
17098 "Toggle the minor `org-cdlatex-mode'.
17099 This mode supports entering LaTeX environment and math in LaTeX fragments
17100 in Org-mode.
17101 \\{org-cdlatex-mode-map}"
17102 nil " OCDL" nil
17103 (when org-cdlatex-mode
17104 (require 'cdlatex)
17105 (run-hooks 'cdlatex-mode-hook)
17106 (cdlatex-compute-tables))
17107 (unless org-cdlatex-texmathp-advice-is-done
17108 (setq org-cdlatex-texmathp-advice-is-done t)
17109 (defadvice texmathp (around org-math-always-on activate)
17110 "Always return t in org-mode buffers.
17111 This is because we want to insert math symbols without dollars even outside
17112 the LaTeX math segments. If Orgmode thinks that point is actually inside
17113 an embedded LaTeX fragment, let texmathp do its job.
17114 \\[org-cdlatex-mode-map]"
17115 (interactive)
17116 (let (p)
17117 (cond
17118 ((not (derived-mode-p 'org-mode)) ad-do-it)
17119 ((eq this-command 'cdlatex-math-symbol)
17120 (setq ad-return-value t
17121 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17123 (let ((p (org-inside-LaTeX-fragment-p)))
17124 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17125 (setq ad-return-value t
17126 texmathp-why '("Org-mode embedded math" . 0))
17127 (if p ad-do-it)))))))))
17129 (defun turn-on-org-cdlatex ()
17130 "Unconditionally turn on `org-cdlatex-mode'."
17131 (org-cdlatex-mode 1))
17133 (defun org-inside-LaTeX-fragment-p ()
17134 "Test if point is inside a LaTeX fragment.
17135 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17136 sequence appearing also before point.
17137 Even though the matchers for math are configurable, this function assumes
17138 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17139 delimiters are skipped when they have been removed by customization.
17140 The return value is nil, or a cons cell with the delimiter and the
17141 position of this delimiter.
17143 This function does a reasonably good job, but can locally be fooled by
17144 for example currency specifications. For example it will assume being in
17145 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17146 fragments that are properly closed, but during editing, we have to live
17147 with the uncertainty caused by missing closing delimiters. This function
17148 looks only before point, not after."
17149 (catch 'exit
17150 (let ((pos (point))
17151 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17152 (lim (progn
17153 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17154 (point)))
17155 dd-on str (start 0) m re)
17156 (goto-char pos)
17157 (when dodollar
17158 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17159 re (nth 1 (assoc "$" org-latex-regexps)))
17160 (while (string-match re str start)
17161 (cond
17162 ((= (match-end 0) (length str))
17163 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17164 ((= (match-end 0) (- (length str) 5))
17165 (throw 'exit nil))
17166 (t (setq start (match-end 0))))))
17167 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17168 (goto-char pos)
17169 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17170 (and (match-beginning 2) (throw 'exit nil))
17171 ;; count $$
17172 (while (re-search-backward "\\$\\$" lim t)
17173 (setq dd-on (not dd-on)))
17174 (goto-char pos)
17175 (if dd-on (cons "$$" m))))))
17177 (defun org-inside-latex-macro-p ()
17178 "Is point inside a LaTeX macro or its arguments?"
17179 (save-match-data
17180 (org-in-regexp
17181 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17183 (defun org-try-cdlatex-tab ()
17184 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17185 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17186 - inside a LaTeX fragment, or
17187 - after the first word in a line, where an abbreviation expansion could
17188 insert a LaTeX environment."
17189 (when org-cdlatex-mode
17190 (cond
17191 ;; Before any word on the line: No expansion possible.
17192 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17193 ;; Just after first word on the line: Expand it. Make sure it
17194 ;; cannot happen on headlines, though.
17195 ((save-excursion
17196 (skip-chars-backward "a-zA-Z0-9*")
17197 (skip-chars-backward " \t")
17198 (and (bolp) (not (org-at-heading-p))))
17199 (cdlatex-tab) t)
17200 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17202 (defun org-cdlatex-underscore-caret (&optional arg)
17203 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17204 Revert to the normal definition outside of these fragments."
17205 (interactive "P")
17206 (if (org-inside-LaTeX-fragment-p)
17207 (call-interactively 'cdlatex-sub-superscript)
17208 (let (org-cdlatex-mode)
17209 (call-interactively (key-binding (vector last-input-event))))))
17211 (defun org-cdlatex-math-modify (&optional arg)
17212 "Execute `cdlatex-math-modify' in LaTeX fragments.
17213 Revert to the normal definition outside of these fragments."
17214 (interactive "P")
17215 (if (org-inside-LaTeX-fragment-p)
17216 (call-interactively 'cdlatex-math-modify)
17217 (let (org-cdlatex-mode)
17218 (call-interactively (key-binding (vector last-input-event))))))
17220 (defvar org-latex-fragment-image-overlays nil
17221 "List of overlays carrying the images of latex fragments.")
17222 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17224 (defun org-remove-latex-fragment-image-overlays ()
17225 "Remove all overlays with LaTeX fragment images in current buffer."
17226 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17227 (setq org-latex-fragment-image-overlays nil))
17229 (defun org-preview-latex-fragment (&optional subtree)
17230 "Preview the LaTeX fragment at point, or all locally or globally.
17231 If the cursor is in a LaTeX fragment, create the image and overlay
17232 it over the source code. If there is no fragment at point, display
17233 all fragments in the current text, from one headline to the next. With
17234 prefix SUBTREE, display all fragments in the current subtree. With a
17235 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17236 the cursor is before the first headline,
17237 display all fragments in the buffer.
17238 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17239 (interactive "P")
17240 (unless buffer-file-name
17241 (error "Can't preview LaTeX fragment in a non-file buffer"))
17242 (org-remove-latex-fragment-image-overlays)
17243 (save-excursion
17244 (save-restriction
17245 (let (beg end at msg)
17246 (cond
17247 ((or (equal subtree '(16))
17248 (not (save-excursion
17249 (re-search-backward org-outline-regexp-bol nil t))))
17250 (setq beg (point-min) end (point-max)
17251 msg "Creating images for buffer...%s"))
17252 ((equal subtree '(4))
17253 (org-back-to-heading)
17254 (setq beg (point) end (org-end-of-subtree t)
17255 msg "Creating images for subtree...%s"))
17257 (if (setq at (org-inside-LaTeX-fragment-p))
17258 (goto-char (max (point-min) (- (cdr at) 2)))
17259 (org-back-to-heading))
17260 (setq beg (point) end (progn (outline-next-heading) (point))
17261 msg (if at "Creating image...%s"
17262 "Creating images for entry...%s"))))
17263 (message msg "")
17264 (narrow-to-region beg end)
17265 (goto-char beg)
17266 (org-format-latex
17267 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17268 (file-name-nondirectory
17269 buffer-file-name)))
17270 default-directory 'overlays msg at 'forbuffer
17271 org-latex-create-formula-image-program)
17272 (message msg "done. Use `C-c C-c' to remove images.")))))
17274 (defvar org-latex-regexps
17275 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17276 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17277 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17278 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17279 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17280 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17281 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17282 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17283 "Regular expressions for matching embedded LaTeX.")
17285 (defvar org-export-have-math nil) ;; dynamic scoping
17286 (defun org-format-latex (prefix &optional dir overlays msg at
17287 forbuffer processing-type)
17288 "Replace LaTeX fragments with links to an image, and produce images.
17289 Some of the options can be changed using the variable
17290 `org-format-latex-options'."
17291 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17292 (let* ((prefixnodir (file-name-nondirectory prefix))
17293 (absprefix (expand-file-name prefix dir))
17294 (todir (file-name-directory absprefix))
17295 (opt org-format-latex-options)
17296 (matchers (plist-get opt :matchers))
17297 (re-list org-latex-regexps)
17298 (org-format-latex-header-extra
17299 (plist-get (org-infile-export-plist) :latex-header-extra))
17300 (cnt 0) txt hash link beg end re e checkdir
17301 executables-checked string
17302 m n block-type block linkfile movefile ov)
17303 ;; Check the different regular expressions
17304 (while (setq e (pop re-list))
17305 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17306 block (if block-type "\n\n" ""))
17307 (when (member m matchers)
17308 (goto-char (point-min))
17309 (while (re-search-forward re nil t)
17310 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17311 (not (get-text-property (match-beginning n)
17312 'org-protected))
17313 (or (not overlays)
17314 (not (eq (get-char-property (match-beginning n)
17315 'org-overlay-type)
17316 'org-latex-overlay))))
17317 (setq org-export-have-math t)
17318 (cond
17319 ((eq processing-type 'verbatim)
17320 ;; Leave the text verbatim, just protect it
17321 (add-text-properties (match-beginning n) (match-end n)
17322 '(org-protected t)))
17323 ((eq processing-type 'mathjax)
17324 ;; Prepare for MathJax processing
17325 (setq string (match-string n))
17326 (if (member m '("$" "$1"))
17327 (save-excursion
17328 (delete-region (match-beginning n) (match-end n))
17329 (goto-char (match-beginning n))
17330 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17331 "\\)")
17332 '(org-protected t))))
17333 (add-text-properties (match-beginning n) (match-end n)
17334 '(org-protected t))))
17335 ((or (eq processing-type 'dvipng)
17336 (eq processing-type 'imagemagick))
17337 ;; Process to an image
17338 (setq txt (match-string n)
17339 beg (match-beginning n) end (match-end n)
17340 cnt (1+ cnt))
17341 (let (print-length print-level) ; make sure full list is printed
17342 (setq hash (sha1 (prin1-to-string
17343 (list org-format-latex-header
17344 org-format-latex-header-extra
17345 org-export-latex-default-packages-alist
17346 org-export-latex-packages-alist
17347 org-format-latex-options
17348 forbuffer txt)))
17349 linkfile (format "%s_%s.png" prefix hash)
17350 movefile (format "%s_%s.png" absprefix hash)))
17351 (setq link (concat block "[[file:" linkfile "]]" block))
17352 (if msg (message msg cnt))
17353 (goto-char beg)
17354 (unless checkdir ; make sure the directory exists
17355 (setq checkdir t)
17356 (or (file-directory-p todir) (make-directory todir t)))
17357 (cond
17358 ((eq processing-type 'dvipng)
17359 (unless executables-checked
17360 (org-check-external-command
17361 "latex" "needed to convert LaTeX fragments to images")
17362 (org-check-external-command
17363 "dvipng" "needed to convert LaTeX fragments to images")
17364 (setq executables-checked t))
17365 (unless (file-exists-p movefile)
17366 (org-create-formula-image-with-dvipng
17367 txt movefile opt forbuffer)))
17368 ((eq processing-type 'imagemagick)
17369 (unless executables-checked
17370 (org-check-external-command
17371 "convert" "you need to install imagemagick")
17372 (setq executables-checked t))
17373 (unless (file-exists-p movefile)
17374 (org-create-formula-image-with-imagemagick
17375 txt movefile opt forbuffer))))
17376 (if overlays
17377 (progn
17378 (mapc (lambda (o)
17379 (if (eq (overlay-get o 'org-overlay-type)
17380 'org-latex-overlay)
17381 (delete-overlay o)))
17382 (overlays-in beg end))
17383 (setq ov (make-overlay beg end))
17384 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17385 (if (featurep 'xemacs)
17386 (progn
17387 (overlay-put ov 'invisible t)
17388 (overlay-put
17389 ov 'end-glyph
17390 (make-glyph (vector 'png :file movefile))))
17391 (overlay-put
17392 ov 'display
17393 (list 'image :type 'png :file movefile :ascent 'center)))
17394 (push ov org-latex-fragment-image-overlays)
17395 (goto-char end))
17396 (delete-region beg end)
17397 (insert (org-add-props link
17398 (list 'org-latex-src
17399 (replace-regexp-in-string
17400 "\"" "" txt)
17401 'org-latex-src-embed-type
17402 (if block-type 'paragraph 'character))))))
17403 ((eq processing-type 'mathml)
17404 ;; Process to MathML
17405 (unless executables-checked
17406 (unless (save-match-data (org-format-latex-mathml-available-p))
17407 (error "LaTeX to MathML converter not configured"))
17408 (setq executables-checked t))
17409 (setq txt (match-string n)
17410 beg (match-beginning n) end (match-end n)
17411 cnt (1+ cnt))
17412 (if msg (message msg cnt))
17413 (goto-char beg)
17414 (delete-region beg end)
17415 (insert (org-format-latex-as-mathml
17416 txt block-type prefix dir)))
17418 (error "Unknown conversion type %s for latex fragments"
17419 processing-type)))))))))
17421 (defun org-create-math-formula (latex-frag &optional mathml-file)
17422 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17423 Use `org-latex-to-mathml-convert-command'. If the conversion is
17424 sucessful, return the portion between \"<math...> </math>\"
17425 elements otherwise return nil. When MATHML-FILE is specified,
17426 write the results in to that file. When invoked as an
17427 interactive command, prompt for LATEX-FRAG, with initial value
17428 set to the current active region and echo the results for user
17429 inspection."
17430 (interactive (list (let ((frag (when (org-region-active-p)
17431 (buffer-substring-no-properties
17432 (region-beginning) (region-end)))))
17433 (read-string "LaTeX Fragment: " frag nil frag))))
17434 (unless latex-frag (error "Invalid latex-frag"))
17435 (let* ((tmp-in-file (file-relative-name
17436 (make-temp-name (expand-file-name "ltxmathml-in"))))
17437 (ignore (write-region latex-frag nil tmp-in-file))
17438 (tmp-out-file (file-relative-name
17439 (make-temp-name (expand-file-name "ltxmathml-out"))))
17440 (cmd (format-spec
17441 org-latex-to-mathml-convert-command
17442 `((?j . ,(shell-quote-argument
17443 (expand-file-name org-latex-to-mathml-jar-file)))
17444 (?I . ,(shell-quote-argument tmp-in-file))
17445 (?o . ,(shell-quote-argument tmp-out-file)))))
17446 mathml shell-command-output)
17447 (when (org-called-interactively-p 'any)
17448 (unless (org-format-latex-mathml-available-p)
17449 (error "LaTeX to MathML converter not configured")))
17450 (message "Running %s" cmd)
17451 (setq shell-command-output (shell-command-to-string cmd))
17452 (setq mathml
17453 (when (file-readable-p tmp-out-file)
17454 (with-current-buffer (find-file-noselect tmp-out-file t)
17455 (goto-char (point-min))
17456 (when (re-search-forward
17457 (concat
17458 (regexp-quote
17459 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17460 "\\(.\\|\n\\)*"
17461 (regexp-quote "</math>")) nil t)
17462 (prog1 (match-string 0) (kill-buffer))))))
17463 (cond
17464 (mathml
17465 (setq mathml
17466 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17467 (when mathml-file
17468 (write-region mathml nil mathml-file))
17469 (when (org-called-interactively-p 'any)
17470 (message mathml)))
17471 ((message "LaTeX to MathML conversion failed")
17472 (message shell-command-output)))
17473 (delete-file tmp-in-file)
17474 (when (file-exists-p tmp-out-file)
17475 (delete-file tmp-out-file))
17476 mathml))
17478 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17479 prefix &optional dir)
17480 "Use `org-create-math-formula' but check local cache first."
17481 (let* ((absprefix (expand-file-name prefix dir))
17482 (print-length nil) (print-level nil)
17483 (formula-id (concat
17484 "formula-"
17485 (sha1
17486 (prin1-to-string
17487 (list latex-frag
17488 org-latex-to-mathml-convert-command)))))
17489 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17490 (formula-cache-dir (file-name-directory formula-cache)))
17492 (unless (file-directory-p formula-cache-dir)
17493 (make-directory formula-cache-dir t))
17495 (unless (file-exists-p formula-cache)
17496 (org-create-math-formula latex-frag formula-cache))
17498 (if (file-exists-p formula-cache)
17499 ;; Successful conversion. Return the link to MathML file.
17500 (org-add-props
17501 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17502 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17503 'org-latex-src-embed-type (if latex-frag-type
17504 'paragraph 'character)))
17505 ;; Failed conversion. Return the LaTeX fragment verbatim
17506 (add-text-properties
17507 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17508 latex-frag)))
17510 ;; This function borrows from Ganesh Swami's latex2png.el
17511 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17512 "This calls dvipng."
17513 (require 'org-latex)
17514 (let* ((tmpdir (if (featurep 'xemacs)
17515 (temp-directory)
17516 temporary-file-directory))
17517 (texfilebase (make-temp-name
17518 (expand-file-name "orgtex" tmpdir)))
17519 (texfile (concat texfilebase ".tex"))
17520 (dvifile (concat texfilebase ".dvi"))
17521 (pngfile (concat texfilebase ".png"))
17522 (fnh (if (featurep 'xemacs)
17523 (font-height (face-font 'default))
17524 (face-attribute 'default :height nil)))
17525 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17526 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17527 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17528 "Black"))
17529 (bg (or (plist-get options (if buffer :background :html-background))
17530 "Transparent")))
17531 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17532 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17533 (with-temp-file texfile
17534 (insert (org-splice-latex-header
17535 org-format-latex-header
17536 org-export-latex-default-packages-alist
17537 org-export-latex-packages-alist t
17538 org-format-latex-header-extra))
17539 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17540 (require 'org-latex)
17541 (org-export-latex-fix-inputenc))
17542 (let ((dir default-directory))
17543 (condition-case nil
17544 (progn
17545 (cd tmpdir)
17546 (call-process "latex" nil nil nil texfile))
17547 (error nil))
17548 (cd dir))
17549 (if (not (file-exists-p dvifile))
17550 (progn (message "Failed to create dvi file from %s" texfile) nil)
17551 (condition-case nil
17552 (if (featurep 'xemacs)
17553 (call-process "dvipng" nil nil nil
17554 "-fg" fg "-bg" bg
17555 "-T" "tight"
17556 "-o" pngfile
17557 dvifile)
17558 (call-process "dvipng" nil nil nil
17559 "-fg" fg "-bg" bg
17560 "-D" dpi
17561 ;;"-x" scale "-y" scale
17562 "-T" "tight"
17563 "-o" pngfile
17564 dvifile))
17565 (error nil))
17566 (if (not (file-exists-p pngfile))
17567 (if org-format-latex-signal-error
17568 (error "Failed to create png file from %s" texfile)
17569 (message "Failed to create png file from %s" texfile)
17570 nil)
17571 ;; Use the requested file name and clean up
17572 (copy-file pngfile tofile 'replace)
17573 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17574 (if (file-exists-p (concat texfilebase e))
17575 (delete-file (concat texfilebase e))))
17576 pngfile))))
17578 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17579 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17580 "This calls convert, which is included into imagemagick."
17581 (require 'org-latex)
17582 (let* ((tmpdir (if (featurep 'xemacs)
17583 (temp-directory)
17584 temporary-file-directory))
17585 (texfilebase (make-temp-name
17586 (expand-file-name "orgtex" tmpdir)))
17587 (texfile (concat texfilebase ".tex"))
17588 (pdffile (concat texfilebase ".pdf"))
17589 (pngfile (concat texfilebase ".png"))
17590 (fnh (if (featurep 'xemacs)
17591 (font-height (face-font 'default))
17592 (face-attribute 'default :height nil)))
17593 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17594 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17595 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17596 "black"))
17597 (bg (or (plist-get options (if buffer :background :html-background))
17598 "white")))
17599 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17600 (setq fg (org-latex-color-format fg)))
17601 (if (eq bg 'default) (setq bg (org-latex-color :background))
17602 (setq bg (org-latex-color-format
17603 (if (string= bg "Transparent")(setq bg "white")))))
17604 (with-temp-file texfile
17605 (insert (org-splice-latex-header
17606 org-format-latex-header
17607 org-export-latex-default-packages-alist
17608 org-export-latex-packages-alist t
17609 org-format-latex-header-extra))
17610 (insert "\n\\begin{document}\n"
17611 "\\definecolor{fg}{rgb}{" fg "}\n"
17612 "\\definecolor{bg}{rgb}{" bg "}\n"
17613 "\n\\pagecolor{bg}\n"
17614 "\n{\\color{fg}\n"
17615 string
17616 "\n}\n"
17617 "\n\\end{document}\n" )
17618 (require 'org-latex)
17619 (org-export-latex-fix-inputenc))
17620 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17621 (condition-case nil
17622 (progn
17623 (cd tmpdir)
17624 (setq cmds org-latex-to-pdf-process)
17625 (while cmds
17626 (setq latex-frags-cmds (pop cmds))
17627 (if (listp latex-frags-cmds)
17628 (setq cmds nil)
17629 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17630 (while latex-frags-cmds
17631 (setq cmd (pop latex-frags-cmds))
17632 (while (string-match "%b" cmd)
17633 (setq cmd (replace-match
17634 (save-match-data
17635 (shell-quote-argument texfile))
17636 t t cmd)))
17637 (while (string-match "%f" cmd)
17638 (setq cmd (replace-match
17639 (save-match-data
17640 (shell-quote-argument (file-name-nondirectory texfile)))
17641 t t cmd)))
17642 (while (string-match "%o" cmd)
17643 (setq cmd (replace-match
17644 (save-match-data
17645 (shell-quote-argument (file-name-directory texfile)))
17646 t t cmd)))
17647 (setq cmd (split-string cmd))
17648 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17649 (error nil))
17650 (cd dir))
17651 (if (not (file-exists-p pdffile))
17652 (progn (message "Failed to create pdf file from %s" texfile) nil)
17653 (condition-case nil
17654 (if (featurep 'xemacs)
17655 (call-process "convert" nil nil nil
17656 "-density" "96"
17657 "-trim"
17658 "-antialias"
17659 pdffile
17660 "-quality" "100"
17661 ;; "-sharpen" "0x1.0"
17662 pngfile)
17663 (call-process "convert" nil nil nil
17664 "-density" dpi
17665 "-trim"
17666 "-antialias"
17667 pdffile
17668 "-quality" "100"
17669 ; "-sharpen" "0x1.0"
17670 pngfile))
17671 (error nil))
17672 (if (not (file-exists-p pngfile))
17673 (if org-format-latex-signal-error
17674 (error "Failed to create png file from %s" texfile)
17675 (message "Failed to create png file from %s" texfile)
17676 nil)
17677 ;; Use the requested file name and clean up
17678 (copy-file pngfile tofile 'replace)
17679 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17680 (if (file-exists-p (concat texfilebase e))
17681 (delete-file (concat texfilebase e))))
17682 pngfile))))
17684 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17685 "Fill a LaTeX header template TPL.
17686 In the template, the following place holders will be recognized:
17688 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17689 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17690 [PACKAGES] \\usepackage statements for PKG
17691 [NO-PACKAGES] do not include PKG
17692 [EXTRA] the string EXTRA
17693 [NO-EXTRA] do not include EXTRA
17695 For backward compatibility, if both the positive and the negative place
17696 holder is missing, the positive one (without the \"NO-\") will be
17697 assumed to be present at the end of the template.
17698 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17699 EXTRA is a string.
17700 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17701 (let (rpl (end ""))
17702 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17703 (setq rpl (if (or (match-end 1) (not def-pkg))
17704 "" (org-latex-packages-to-string def-pkg snippets-p t))
17705 tpl (replace-match rpl t t tpl))
17706 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17708 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17709 (setq rpl (if (or (match-end 1) (not pkg))
17710 "" (org-latex-packages-to-string pkg snippets-p t))
17711 tpl (replace-match rpl t t tpl))
17712 (if pkg (setq end
17713 (concat end "\n"
17714 (org-latex-packages-to-string pkg snippets-p)))))
17716 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17717 (setq rpl (if (or (match-end 1) (not extra))
17718 "" (concat extra "\n"))
17719 tpl (replace-match rpl t t tpl))
17720 (if (and extra (string-match "\\S-" extra))
17721 (setq end (concat end "\n" extra))))
17723 (if (string-match "\\S-" end)
17724 (concat tpl "\n" end)
17725 tpl)))
17727 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17728 "Turn an alist of packages into a string with the \\usepackage macros."
17729 (setq pkg (mapconcat (lambda(p)
17730 (cond
17731 ((stringp p) p)
17732 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17733 (format "%% Package %s omitted" (cadr p)))
17734 ((equal "" (car p))
17735 (format "\\usepackage{%s}" (cadr p)))
17737 (format "\\usepackage[%s]{%s}"
17738 (car p) (cadr p)))))
17740 "\n"))
17741 (if newline (concat pkg "\n") pkg))
17743 (defun org-dvipng-color (attr)
17744 "Return a RGB color specification for dvipng."
17745 (apply 'format "rgb %s %s %s"
17746 (mapcar 'org-normalize-color
17747 (if (featurep 'xemacs)
17748 (color-rgb-components
17749 (face-property 'default
17750 (cond ((eq attr :foreground) 'foreground)
17751 ((eq attr :background) 'background))))
17752 (color-values (face-attribute 'default attr nil))))))
17754 (defun org-latex-color (attr)
17755 "Return a RGB color for the LaTeX color package."
17756 (apply 'format "%s,%s,%s"
17757 (mapcar 'org-normalize-color
17758 (if (featurep 'xemacs)
17759 (color-rgb-components
17760 (face-property 'default
17761 (cond ((eq attr :foreground) 'foreground)
17762 ((eq attr :background) 'background))))
17763 (color-values (face-attribute 'default attr nil))))))
17765 (defun org-latex-color-format (color-name)
17766 "Convert COLOR-NAME to a RGB color value."
17767 (apply 'format "%s,%s,%s"
17768 (mapcar 'org-normalize-color
17769 (color-values color-name))))
17771 (defun org-normalize-color (value)
17772 "Return string to be used as color value for an RGB component."
17773 (format "%g" (/ value 65535.0)))
17775 ;; Image display
17778 (defvar org-inline-image-overlays nil)
17779 (make-variable-buffer-local 'org-inline-image-overlays)
17781 (defun org-toggle-inline-images (&optional include-linked)
17782 "Toggle the display of inline images.
17783 INCLUDE-LINKED is passed to `org-display-inline-images'."
17784 (interactive "P")
17785 (if org-inline-image-overlays
17786 (progn
17787 (org-remove-inline-images)
17788 (message "Inline image display turned off"))
17789 (org-display-inline-images include-linked)
17790 (if org-inline-image-overlays
17791 (message "%d images displayed inline"
17792 (length org-inline-image-overlays))
17793 (message "No images to display inline"))))
17795 (defun org-redisplay-inline-images ()
17796 "Refresh the display of inline images."
17797 (interactive)
17798 (if (not org-inline-image-overlays)
17799 (org-toggle-inline-images)
17800 (org-toggle-inline-images)
17801 (org-toggle-inline-images)))
17803 (defun org-display-inline-images (&optional include-linked refresh beg end)
17804 "Display inline images.
17805 Normally only links without a description part are inlined, because this
17806 is how it will work for export. When INCLUDE-LINKED is set, also links
17807 with a description part will be inlined. This can be nice for a quick
17808 look at those images, but it does not reflect what exported files will look
17809 like.
17810 When REFRESH is set, refresh existing images between BEG and END.
17811 This will create new image displays only if necessary.
17812 BEG and END default to the buffer boundaries."
17813 (interactive "P")
17814 (unless refresh
17815 (org-remove-inline-images)
17816 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17817 (save-excursion
17818 (save-restriction
17819 (widen)
17820 (setq beg (or beg (point-min)) end (or end (point-max)))
17821 (goto-char beg)
17822 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17823 (substring (org-image-file-name-regexp) 0 -2)
17824 "\\)\\]" (if include-linked "" "\\]")))
17825 old file ov img)
17826 (while (re-search-forward re end t)
17827 (setq old (get-char-property-and-overlay (match-beginning 1)
17828 'org-image-overlay))
17829 (setq file (expand-file-name
17830 (concat (or (match-string 3) "") (match-string 4))))
17831 (when (file-exists-p file)
17832 (if (and (car-safe old) refresh)
17833 (image-refresh (overlay-get (cdr old) 'display))
17834 (setq img (save-match-data (create-image file)))
17835 (when img
17836 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17837 (overlay-put ov 'display img)
17838 (overlay-put ov 'face 'default)
17839 (overlay-put ov 'org-image-overlay t)
17840 (overlay-put ov 'modification-hooks
17841 (list 'org-display-inline-modification-hook))
17842 (push ov org-inline-image-overlays)))))))))
17844 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17845 "Remove inline-display overlay if a corresponding region is modified."
17846 (let ((inhibit-modification-hooks t))
17847 (when (and ov after)
17848 (delete ov org-inline-image-overlays)
17849 (delete-overlay ov))))
17851 (defun org-remove-inline-images ()
17852 "Remove inline display of images."
17853 (interactive)
17854 (mapc 'delete-overlay org-inline-image-overlays)
17855 (setq org-inline-image-overlays nil))
17857 ;;;; Key bindings
17859 ;; Outline functions from `outline-mode-prefix-map'
17860 ;; that can be remapped in Org:
17861 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17862 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17863 (define-key org-mode-map [remap outline-forward-same-level]
17864 'org-forward-heading-same-level)
17865 (define-key org-mode-map [remap outline-backward-same-level]
17866 'org-backward-heading-same-level)
17867 (define-key org-mode-map [remap show-branches]
17868 'org-kill-note-or-show-branches)
17869 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17870 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17871 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17873 ;; Outline functions from `outline-mode-prefix-map' that can not
17874 ;; be remapped in Org:
17876 ;; - the column "key binding" shows whether the Outline function is still
17877 ;; available in Org mode on the same key that it has been bound to in
17878 ;; Outline mode:
17879 ;; - "overridden": key used for a different functionality in Org mode
17880 ;; - else: key still bound to the same Outline function in Org mode
17882 ;; | Outline function | key binding | Org replacement |
17883 ;; |------------------------------------+-------------+-----------------------|
17884 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17885 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17886 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17887 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17888 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17889 ;; | `show-entry' | overridden | no replacement |
17890 ;; | `show-children' | `C-c C-i' | visibility cycling |
17891 ;; | `show-branches' | `C-c C-k' | still same function |
17892 ;; | `show-subtree' | overridden | visibility cycling |
17893 ;; | `show-all' | overridden | no replacement |
17894 ;; | `hide-subtree' | overridden | visibility cycling |
17895 ;; | `hide-body' | overridden | no replacement |
17896 ;; | `hide-entry' | overridden | visibility cycling |
17897 ;; | `hide-leaves' | overridden | no replacement |
17898 ;; | `hide-sublevels' | overridden | no replacement |
17899 ;; | `hide-other' | overridden | no replacement |
17901 ;; Make `C-c C-x' a prefix key
17902 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17904 ;; TAB key with modifiers
17905 (org-defkey org-mode-map "\C-i" 'org-cycle)
17906 (org-defkey org-mode-map [(tab)] 'org-cycle)
17907 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17908 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17909 ;; The following line is necessary under Suse GNU/Linux
17910 (unless (featurep 'xemacs)
17911 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17912 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17913 (define-key org-mode-map [backtab] 'org-shifttab)
17915 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17916 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17917 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17919 ;; Cursor keys with modifiers
17920 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17921 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17922 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17923 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17925 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17926 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17927 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17928 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17930 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17931 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17932 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17933 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17935 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17936 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17937 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17938 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17940 ;; Babel keys
17941 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17942 (mapc (lambda (pair)
17943 (define-key org-babel-map (car pair) (cdr pair)))
17944 org-babel-key-bindings)
17946 ;;; Extra keys for tty access.
17947 ;; We only set them when really needed because otherwise the
17948 ;; menus don't show the simple keys
17950 (when (or org-use-extra-keys
17951 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17952 (not window-system))
17953 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17954 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17955 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17956 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17957 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17958 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17959 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17960 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17961 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17962 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17963 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17964 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17965 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17966 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17967 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17968 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17969 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17970 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17971 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17972 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17973 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17974 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17975 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17976 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17977 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17978 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17979 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17980 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17982 ;; All the other keys
17984 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17985 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17986 (if (boundp 'narrow-map)
17987 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17988 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17989 (if (boundp 'narrow-map)
17990 (org-defkey narrow-map "b" 'org-narrow-to-block)
17991 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17992 (if (boundp 'narrow-map)
17993 (org-defkey narrow-map "e" 'org-narrow-to-element)
17994 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17995 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17996 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17997 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17998 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17999 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18000 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18001 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18002 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18003 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18004 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18005 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18006 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18007 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18008 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18009 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18010 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18011 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18012 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18013 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18014 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18015 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18016 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18017 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18018 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18019 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18020 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18021 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18022 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18023 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18024 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18025 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18026 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18027 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18028 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18029 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18030 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18031 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18032 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18033 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18034 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18035 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18036 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18037 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18038 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18039 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18040 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18041 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18042 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18043 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18044 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18045 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18046 (org-defkey org-mode-map "\C-c^" 'org-sort)
18047 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18048 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18049 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18050 (org-defkey org-mode-map "\C-m" 'org-return)
18051 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18052 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18053 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18054 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18055 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18056 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18057 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18058 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18059 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18060 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18061 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18062 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18063 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18064 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18065 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18066 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18067 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18068 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18069 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18070 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18071 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18072 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18073 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18075 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18076 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18077 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18078 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18080 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18081 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18082 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18083 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18084 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18085 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18086 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18087 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18088 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18089 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18090 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18091 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18092 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18093 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18094 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18095 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18096 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18097 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18098 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18099 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18100 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18101 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18103 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18104 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18105 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18106 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18107 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18109 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18111 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18113 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18114 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18116 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18119 (when (featurep 'xemacs)
18120 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18123 (defconst org-speed-commands-default
18125 ("Outline Navigation")
18126 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18127 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18128 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18129 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18130 ("u" . (org-speed-move-safe 'outline-up-heading))
18131 ("j" . org-goto)
18132 ("g" . (org-refile t))
18133 ("Outline Visibility")
18134 ("c" . org-cycle)
18135 ("C" . org-shifttab)
18136 (" " . org-display-outline-path)
18137 (":" . org-columns)
18138 ("Outline Structure Editing")
18139 ("U" . org-shiftmetaup)
18140 ("D" . org-shiftmetadown)
18141 ("r" . org-metaright)
18142 ("l" . org-metaleft)
18143 ("R" . org-shiftmetaright)
18144 ("L" . org-shiftmetaleft)
18145 ("i" . (progn (forward-char 1) (call-interactively
18146 'org-insert-heading-respect-content)))
18147 ("^" . org-sort)
18148 ("w" . org-refile)
18149 ("a" . org-archive-subtree-default-with-confirmation)
18150 ("." . org-mark-subtree)
18151 ("#" . org-toggle-comment)
18152 ("Clock Commands")
18153 ("I" . org-clock-in)
18154 ("O" . org-clock-out)
18155 ("Meta Data Editing")
18156 ("t" . org-todo)
18157 ("0" . (org-priority ?\ ))
18158 ("1" . (org-priority ?A))
18159 ("2" . (org-priority ?B))
18160 ("3" . (org-priority ?C))
18161 (";" . org-set-tags-command)
18162 ("e" . org-set-effort)
18163 ("E" . org-inc-effort)
18164 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18165 (org-entry-put (point) "APPT_WARNTIME" m)))
18166 ("Agenda Views etc")
18167 ("v" . org-agenda)
18168 ("/" . org-sparse-tree)
18169 ("Misc")
18170 ("o" . org-open-at-point)
18171 ("?" . org-speed-command-help)
18172 ("<" . (org-agenda-set-restriction-lock 'subtree))
18173 (">" . (org-agenda-remove-restriction-lock))
18175 "The default speed commands.")
18177 (defun org-print-speed-command (e)
18178 (if (> (length (car e)) 1)
18179 (progn
18180 (princ "\n")
18181 (princ (car e))
18182 (princ "\n")
18183 (princ (make-string (length (car e)) ?-))
18184 (princ "\n"))
18185 (princ (car e))
18186 (princ " ")
18187 (if (symbolp (cdr e))
18188 (princ (symbol-name (cdr e)))
18189 (prin1 (cdr e)))
18190 (princ "\n")))
18192 (defun org-speed-command-help ()
18193 "Show the available speed commands."
18194 (interactive)
18195 (if (not org-use-speed-commands)
18196 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18197 (with-output-to-temp-buffer "*Help*"
18198 (princ "User-defined Speed commands\n===========================\n")
18199 (mapc 'org-print-speed-command org-speed-commands-user)
18200 (princ "\n")
18201 (princ "Built-in Speed commands\n=======================\n")
18202 (mapc 'org-print-speed-command org-speed-commands-default))
18203 (with-current-buffer "*Help*"
18204 (setq truncate-lines t))))
18206 (defun org-speed-move-safe (cmd)
18207 "Execute CMD, but make sure that the cursor always ends up in a headline.
18208 If not, return to the original position and throw an error."
18209 (interactive)
18210 (let ((pos (point)))
18211 (call-interactively cmd)
18212 (unless (and (bolp) (org-at-heading-p))
18213 (goto-char pos)
18214 (error "Boundary reached while executing %s" cmd))))
18216 (defvar org-self-insert-command-undo-counter 0)
18218 (defvar org-table-auto-blank-field) ; defined in org-table.el
18219 (defvar org-speed-command nil)
18221 (defun org-speed-command-default-hook (keys)
18222 "Hook for activating single-letter speed commands.
18223 `org-speed-commands-default' specifies a minimal command set.
18224 Use `org-speed-commands-user' for further customization."
18225 (when (or (and (bolp) (looking-at org-outline-regexp))
18226 (and (functionp org-use-speed-commands)
18227 (funcall org-use-speed-commands)))
18228 (cdr (assoc keys (append org-speed-commands-user
18229 org-speed-commands-default)))))
18231 (defun org-babel-speed-command-hook (keys)
18232 "Hook for activating single-letter code block commands."
18233 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18234 (cdr (assoc keys org-babel-key-bindings))))
18236 (defcustom org-speed-command-hook
18237 '(org-speed-command-default-hook org-babel-speed-command-hook)
18238 "Hook for activating speed commands at strategic locations.
18239 Hook functions are called in sequence until a valid handler is
18240 found.
18242 Each hook takes a single argument, a user-pressed command key
18243 which is also a `self-insert-command' from the global map.
18245 Within the hook, examine the cursor position and the command key
18246 and return nil or a valid handler as appropriate. Handler could
18247 be one of an interactive command, a function, or a form.
18249 Set `org-use-speed-commands' to non-nil value to enable this
18250 hook. The default setting is `org-speed-command-default-hook'."
18251 :group 'org-structure
18252 :version "24.1"
18253 :type 'hook)
18255 (defun org-self-insert-command (N)
18256 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18257 If the cursor is in a table looking at whitespace, the whitespace is
18258 overwritten, and the table is not marked as requiring realignment."
18259 (interactive "p")
18260 (org-check-before-invisible-edit 'insert)
18261 (cond
18262 ((and org-use-speed-commands
18263 (setq org-speed-command
18264 (run-hook-with-args-until-success
18265 'org-speed-command-hook (this-command-keys))))
18266 (cond
18267 ((commandp org-speed-command)
18268 (setq this-command org-speed-command)
18269 (call-interactively org-speed-command))
18270 ((functionp org-speed-command)
18271 (funcall org-speed-command))
18272 ((and org-speed-command (listp org-speed-command))
18273 (eval org-speed-command))
18274 (t (let (org-use-speed-commands)
18275 (call-interactively 'org-self-insert-command)))))
18276 ((and
18277 (org-table-p)
18278 (progn
18279 ;; check if we blank the field, and if that triggers align
18280 (and (featurep 'org-table) org-table-auto-blank-field
18281 (member last-command
18282 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18283 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18284 ;; got extra space, this field does not determine column width
18285 (let (org-table-may-need-update) (org-table-blank-field))
18286 ;; no extra space, this field may determine column width
18287 (org-table-blank-field)))
18289 (eq N 1)
18290 (looking-at "[^|\n]* |"))
18291 (let (org-table-may-need-update)
18292 (goto-char (1- (match-end 0)))
18293 (backward-delete-char 1)
18294 (goto-char (match-beginning 0))
18295 (self-insert-command N)))
18297 (setq org-table-may-need-update t)
18298 (self-insert-command N)
18299 (org-fix-tags-on-the-fly)
18300 (if org-self-insert-cluster-for-undo
18301 (if (not (eq last-command 'org-self-insert-command))
18302 (setq org-self-insert-command-undo-counter 1)
18303 (if (>= org-self-insert-command-undo-counter 20)
18304 (setq org-self-insert-command-undo-counter 1)
18305 (and (> org-self-insert-command-undo-counter 0)
18306 buffer-undo-list (listp buffer-undo-list)
18307 (not (cadr buffer-undo-list)) ; remove nil entry
18308 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18309 (setq org-self-insert-command-undo-counter
18310 (1+ org-self-insert-command-undo-counter))))))))
18312 (defun org-check-before-invisible-edit (kind)
18313 "Check is editing if kind KIND would be dangerous with invisible text around.
18314 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18315 ;; First, try to get out of here as quickly as possible, to reduce overhead
18316 (if (and org-catch-invisible-edits
18317 (or (not (boundp 'visible-mode)) (not visible-mode))
18318 (or (get-char-property (point) 'invisible)
18319 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18320 ;; OK, we need to take a closer look
18321 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18322 (invisible-before-point (if (bobp) nil (get-char-property
18323 (1- (point)) 'invisible)))
18324 (border-and-ok-direction
18326 ;; Check if we are acting predictably before invisible text
18327 (and invisible-at-point (not invisible-before-point)
18328 (memq kind '(insert delete-backward)))
18329 ;; Check if we are acting predictably after invisible text
18330 ;; This works not well, and I have turned it off. It seems
18331 ;; better to always show and stop after invisible text.
18332 ;; (and (not invisible-at-point) invisible-before-point
18333 ;; (memq kind '(insert delete)))
18335 (when (or (memq invisible-at-point '(outline org-hide-block t))
18336 (memq invisible-before-point '(outline org-hide-block t)))
18337 (if (eq org-catch-invisible-edits 'error)
18338 (error "Editing in invisible areas is prohibited - make visible first"))
18339 (if (and org-custom-properties-overlays
18340 (y-or-n-p "Display invisible properties in this buffer? "))
18341 (org-toggle-custom-properties-visibility)
18342 ;; Make the area visible
18343 (save-excursion
18344 (if invisible-before-point
18345 (goto-char (previous-single-char-property-change
18346 (point) 'invisible)))
18347 (org-cycle))
18348 (cond
18349 ((eq org-catch-invisible-edits 'show)
18350 ;; That's it, we do the edit after showing
18351 (message
18352 "Unfolding invisible region around point before editing")
18353 (sit-for 1))
18354 ((and (eq org-catch-invisible-edits 'smart)
18355 border-and-ok-direction)
18356 (message "Unfolding invisible region around point before editing"))
18358 ;; Don't do the edit, make the user repeat it in full visibility
18359 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18361 (defun org-fix-tags-on-the-fly ()
18362 (when (and (equal (char-after (point-at-bol)) ?*)
18363 (org-at-heading-p))
18364 (org-align-tags-here org-tags-column)))
18366 (defun org-delete-backward-char (N)
18367 "Like `delete-backward-char', insert whitespace at field end in tables.
18368 When deleting backwards, in tables this function will insert whitespace in
18369 front of the next \"|\" separator, to keep the table aligned. The table will
18370 still be marked for re-alignment if the field did fill the entire column,
18371 because, in this case the deletion might narrow the column."
18372 (interactive "p")
18373 (org-check-before-invisible-edit 'delete-backward)
18374 (if (and (org-table-p)
18375 (eq N 1)
18376 (string-match "|" (buffer-substring (point-at-bol) (point)))
18377 (looking-at ".*?|"))
18378 (let ((pos (point))
18379 (noalign (looking-at "[^|\n\r]* |"))
18380 (c org-table-may-need-update))
18381 (backward-delete-char N)
18382 (if (not overwrite-mode)
18383 (progn
18384 (skip-chars-forward "^|")
18385 (insert " ")
18386 (goto-char (1- pos))))
18387 ;; noalign: if there were two spaces at the end, this field
18388 ;; does not determine the width of the column.
18389 (if noalign (setq org-table-may-need-update c)))
18390 (backward-delete-char N)
18391 (org-fix-tags-on-the-fly)))
18393 (defun org-delete-char (N)
18394 "Like `delete-char', but insert whitespace at field end in tables.
18395 When deleting characters, in tables this function will insert whitespace in
18396 front of the next \"|\" separator, to keep the table aligned. The table will
18397 still be marked for re-alignment if the field did fill the entire column,
18398 because, in this case the deletion might narrow the column."
18399 (interactive "p")
18400 (org-check-before-invisible-edit 'delete)
18401 (if (and (org-table-p)
18402 (not (bolp))
18403 (not (= (char-after) ?|))
18404 (eq N 1))
18405 (if (looking-at ".*?|")
18406 (let ((pos (point))
18407 (noalign (looking-at "[^|\n\r]* |"))
18408 (c org-table-may-need-update))
18409 (replace-match (concat
18410 (substring (match-string 0) 1 -1)
18411 " |"))
18412 (goto-char pos)
18413 ;; noalign: if there were two spaces at the end, this field
18414 ;; does not determine the width of the column.
18415 (if noalign (setq org-table-may-need-update c)))
18416 (delete-char N))
18417 (delete-char N)
18418 (org-fix-tags-on-the-fly)))
18420 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18421 (put 'org-self-insert-command 'delete-selection t)
18422 (put 'orgtbl-self-insert-command 'delete-selection t)
18423 (put 'org-delete-char 'delete-selection 'supersede)
18424 (put 'org-delete-backward-char 'delete-selection 'supersede)
18425 (put 'org-yank 'delete-selection 'yank)
18427 ;; Make `flyspell-mode' delay after some commands
18428 (put 'org-self-insert-command 'flyspell-delayed t)
18429 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18430 (put 'org-delete-char 'flyspell-delayed t)
18431 (put 'org-delete-backward-char 'flyspell-delayed t)
18433 ;; Make pabbrev-mode expand after org-mode commands
18434 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18435 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18437 ;; How to do this: Measure non-white length of current string
18438 ;; If equal to column width, we should realign.
18440 (defun org-remap (map &rest commands)
18441 "In MAP, remap the functions given in COMMANDS.
18442 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18443 (let (new old)
18444 (while commands
18445 (setq old (pop commands) new (pop commands))
18446 (if (fboundp 'command-remapping)
18447 (org-defkey map (vector 'remap old) new)
18448 (substitute-key-definition old new map global-map)))))
18450 (when (eq org-enable-table-editor 'optimized)
18451 ;; If the user wants maximum table support, we need to hijack
18452 ;; some standard editing functions
18453 (org-remap org-mode-map
18454 'self-insert-command 'org-self-insert-command
18455 'delete-char 'org-delete-char
18456 'delete-backward-char 'org-delete-backward-char)
18457 (org-defkey org-mode-map "|" 'org-force-self-insert))
18459 (defvar org-ctrl-c-ctrl-c-hook nil
18460 "Hook for functions attaching themselves to `C-c C-c'.
18462 This can be used to add additional functionality to the C-c C-c
18463 key which executes context-dependent commands. This hook is run
18464 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18465 run after the last test.
18467 Each function will be called with no arguments. The function
18468 must check if the context is appropriate for it to act. If yes,
18469 it should do its thing and then return a non-nil value. If the
18470 context is wrong, just do nothing and return nil.")
18472 (defvar org-ctrl-c-ctrl-c-final-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 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18478 before the first 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-tab-first-hook nil
18486 "Hook for functions to attach themselves to TAB.
18487 See `org-ctrl-c-ctrl-c-hook' for more information.
18488 This hook runs as the first action when TAB is pressed, even before
18489 `org-cycle' messes around with the `outline-regexp' to cater for
18490 inline tasks and plain list item folding.
18491 If any function in this hook returns t, any other actions that
18492 would have been caused by TAB (such as table field motion or visibility
18493 cycling) will not occur.")
18495 (defvar org-tab-after-check-for-table-hook nil
18496 "Hook for functions to attach themselves to TAB.
18497 See `org-ctrl-c-ctrl-c-hook' for more information.
18498 This hook runs after it has been established that the cursor is not in a
18499 table, but before checking if the cursor is in a headline or if global cycling
18500 should be done.
18501 If any function in this hook returns t, not other actions like visibility
18502 cycling will be done.")
18504 (defvar org-tab-after-check-for-cycling-hook nil
18505 "Hook for functions to attach themselves to TAB.
18506 See `org-ctrl-c-ctrl-c-hook' for more information.
18507 This hook runs after it has been established that not table field motion and
18508 not visibility should be done because of current context. This is probably
18509 the place where a package like yasnippets can hook in.")
18511 (defvar org-tab-before-tab-emulation-hook nil
18512 "Hook for functions to attach themselves to TAB.
18513 See `org-ctrl-c-ctrl-c-hook' for more information.
18514 This hook runs after every other options for TAB have been exhausted, but
18515 before indentation and \t insertion takes place.")
18517 (defvar org-metaleft-hook nil
18518 "Hook for functions attaching themselves to `M-left'.
18519 See `org-ctrl-c-ctrl-c-hook' for more information.")
18520 (defvar org-metaright-hook nil
18521 "Hook for functions attaching themselves to `M-right'.
18522 See `org-ctrl-c-ctrl-c-hook' for more information.")
18523 (defvar org-metaup-hook nil
18524 "Hook for functions attaching themselves to `M-up'.
18525 See `org-ctrl-c-ctrl-c-hook' for more information.")
18526 (defvar org-metadown-hook nil
18527 "Hook for functions attaching themselves to `M-down'.
18528 See `org-ctrl-c-ctrl-c-hook' for more information.")
18529 (defvar org-shiftmetaleft-hook nil
18530 "Hook for functions attaching themselves to `M-S-left'.
18531 See `org-ctrl-c-ctrl-c-hook' for more information.")
18532 (defvar org-shiftmetaright-hook nil
18533 "Hook for functions attaching themselves to `M-S-right'.
18534 See `org-ctrl-c-ctrl-c-hook' for more information.")
18535 (defvar org-shiftmetaup-hook nil
18536 "Hook for functions attaching themselves to `M-S-up'.
18537 See `org-ctrl-c-ctrl-c-hook' for more information.")
18538 (defvar org-shiftmetadown-hook nil
18539 "Hook for functions attaching themselves to `M-S-down'.
18540 See `org-ctrl-c-ctrl-c-hook' for more information.")
18541 (defvar org-metareturn-hook nil
18542 "Hook for functions attaching themselves to `M-RET'.
18543 See `org-ctrl-c-ctrl-c-hook' for more information.")
18544 (defvar org-shiftup-hook nil
18545 "Hook for functions attaching themselves to `S-up'.
18546 See `org-ctrl-c-ctrl-c-hook' for more information.")
18547 (defvar org-shiftup-final-hook nil
18548 "Hook for functions attaching themselves to `S-up'.
18549 This one runs after all other options except shift-select have been excluded.
18550 See `org-ctrl-c-ctrl-c-hook' for more information.")
18551 (defvar org-shiftdown-hook nil
18552 "Hook for functions attaching themselves to `S-down'.
18553 See `org-ctrl-c-ctrl-c-hook' for more information.")
18554 (defvar org-shiftdown-final-hook nil
18555 "Hook for functions attaching themselves to `S-down'.
18556 This one runs after all other options except shift-select have been excluded.
18557 See `org-ctrl-c-ctrl-c-hook' for more information.")
18558 (defvar org-shiftleft-hook nil
18559 "Hook for functions attaching themselves to `S-left'.
18560 See `org-ctrl-c-ctrl-c-hook' for more information.")
18561 (defvar org-shiftleft-final-hook nil
18562 "Hook for functions attaching themselves to `S-left'.
18563 This one runs after all other options except shift-select have been excluded.
18564 See `org-ctrl-c-ctrl-c-hook' for more information.")
18565 (defvar org-shiftright-hook nil
18566 "Hook for functions attaching themselves to `S-right'.
18567 See `org-ctrl-c-ctrl-c-hook' for more information.")
18568 (defvar org-shiftright-final-hook nil
18569 "Hook for functions attaching themselves to `S-right'.
18570 This one runs after all other options except shift-select have been excluded.
18571 See `org-ctrl-c-ctrl-c-hook' for more information.")
18573 (defun org-modifier-cursor-error ()
18574 "Throw an error, a modified cursor command was applied in wrong context."
18575 (error "This command is active in special context like tables, headlines or items"))
18577 (defun org-shiftselect-error ()
18578 "Throw an error because Shift-Cursor command was applied in wrong context."
18579 (if (and (boundp 'shift-select-mode) shift-select-mode)
18580 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18581 (error "This command works only in special context like headlines or timestamps")))
18583 (defun org-call-for-shift-select (cmd)
18584 (let ((this-command-keys-shift-translated t))
18585 (call-interactively cmd)))
18587 (defun org-shifttab (&optional arg)
18588 "Global visibility cycling or move to previous table field.
18589 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18590 on context.
18591 See the individual commands for more information."
18592 (interactive "P")
18593 (cond
18594 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18595 ((integerp arg)
18596 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18597 (message "Content view to level: %d" arg)
18598 (org-content (prefix-numeric-value arg2))
18599 (setq org-cycle-global-status 'overview)))
18600 (t (call-interactively 'org-global-cycle))))
18602 (defun org-shiftmetaleft ()
18603 "Promote subtree or delete table column.
18604 Calls `org-promote-subtree', `org-outdent-item-tree', or
18605 `org-table-delete-column', depending on context. See the
18606 individual commands for more information."
18607 (interactive)
18608 (cond
18609 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18610 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18611 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18612 ((if (not (org-region-active-p)) (org-at-item-p)
18613 (save-excursion (goto-char (region-beginning))
18614 (org-at-item-p)))
18615 (call-interactively 'org-outdent-item-tree))
18616 (t (org-modifier-cursor-error))))
18618 (defun org-shiftmetaright ()
18619 "Demote subtree or insert table column.
18620 Calls `org-demote-subtree', `org-indent-item-tree', or
18621 `org-table-insert-column', depending on context. See the
18622 individual commands for more information."
18623 (interactive)
18624 (cond
18625 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18626 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18627 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18628 ((if (not (org-region-active-p)) (org-at-item-p)
18629 (save-excursion (goto-char (region-beginning))
18630 (org-at-item-p)))
18631 (call-interactively 'org-indent-item-tree))
18632 (t (org-modifier-cursor-error))))
18634 (defun org-shiftmetaup (&optional arg)
18635 "Move subtree up or kill table row.
18636 Calls `org-move-subtree-up' or `org-table-kill-row' or
18637 `org-move-item-up' or `org-timestamp-up', depending on context.
18638 See the individual commands for more information."
18639 (interactive "P")
18640 (cond
18641 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18642 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18643 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18644 ((org-at-item-p) (call-interactively 'org-move-item-up))
18645 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18646 (call-interactively 'org-timestamp-up)))
18647 (t (org-modifier-cursor-error))))
18649 (defun org-shiftmetadown (&optional arg)
18650 "Move subtree down or insert table row.
18651 Calls `org-move-subtree-down' or `org-table-insert-row' or
18652 `org-move-item-down' or `org-timestamp-up', depending on context.
18653 See the individual commands for more information."
18654 (interactive "P")
18655 (cond
18656 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18657 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18658 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18659 ((org-at-item-p) (call-interactively 'org-move-item-down))
18660 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18661 (call-interactively 'org-timestamp-down)))
18662 (t (org-modifier-cursor-error))))
18664 (defsubst org-hidden-tree-error ()
18665 (error
18666 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18668 (defun org-metaleft (&optional arg)
18669 "Promote heading or move table column to left.
18670 Calls `org-do-promote' or `org-table-move-column', depending on context.
18671 With no specific context, calls the Emacs default `backward-word'.
18672 See the individual commands for more information."
18673 (interactive "P")
18674 (cond
18675 ((run-hook-with-args-until-success 'org-metaleft-hook))
18676 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18677 ((org-with-limited-levels
18678 (or (org-at-heading-p)
18679 (and (org-region-active-p)
18680 (save-excursion
18681 (goto-char (region-beginning))
18682 (org-at-heading-p)))))
18683 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18684 (call-interactively 'org-do-promote))
18685 ;; At an inline task.
18686 ((org-at-heading-p)
18687 (call-interactively 'org-inlinetask-promote))
18688 ((or (org-at-item-p)
18689 (and (org-region-active-p)
18690 (save-excursion
18691 (goto-char (region-beginning))
18692 (org-at-item-p))))
18693 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18694 (call-interactively 'org-outdent-item))
18695 (t (call-interactively 'backward-word))))
18697 (defun org-metaright (&optional arg)
18698 "Demote a subtree, a list item or move table column to right.
18699 In front of a drawer or a block keyword, indent it correctly.
18700 With no specific context, calls the Emacs default `forward-word'.
18701 See the individual commands for more information."
18702 (interactive "P")
18703 (cond
18704 ((run-hook-with-args-until-success 'org-metaright-hook))
18705 ((org-at-table-p) (call-interactively 'org-table-move-column))
18706 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18707 ((org-at-block-p) (call-interactively 'org-indent-block))
18708 ((org-with-limited-levels
18709 (or (org-at-heading-p)
18710 (and (org-region-active-p)
18711 (save-excursion
18712 (goto-char (region-beginning))
18713 (org-at-heading-p)))))
18714 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18715 (call-interactively 'org-do-demote))
18716 ;; At an inline task.
18717 ((org-at-heading-p)
18718 (call-interactively 'org-inlinetask-demote))
18719 ((or (org-at-item-p)
18720 (and (org-region-active-p)
18721 (save-excursion
18722 (goto-char (region-beginning))
18723 (org-at-item-p))))
18724 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18725 (call-interactively 'org-indent-item))
18726 (t (call-interactively 'forward-word))))
18728 (defun org-check-for-hidden (what)
18729 "Check if there are hidden headlines/items in the current visual line.
18730 WHAT can be either `headlines' or `items'. If the current line is
18731 an outline or item heading and it has a folded subtree below it,
18732 this function returns t, nil otherwise."
18733 (let ((re (cond
18734 ((eq what 'headlines) org-outline-regexp-bol)
18735 ((eq what 'items) (org-item-beginning-re))
18736 (t (error "This should not happen"))))
18737 beg end)
18738 (save-excursion
18739 (catch 'exit
18740 (unless (org-region-active-p)
18741 (setq beg (point-at-bol))
18742 (beginning-of-line 2)
18743 (while (and (not (eobp)) ;; this is like `next-line'
18744 (get-char-property (1- (point)) 'invisible))
18745 (beginning-of-line 2))
18746 (setq end (point))
18747 (goto-char beg)
18748 (goto-char (point-at-eol))
18749 (setq end (max end (point)))
18750 (while (re-search-forward re end t)
18751 (if (get-char-property (match-beginning 0) 'invisible)
18752 (throw 'exit t))))
18753 nil))))
18755 (autoload 'org-element-at-point "org-element")
18757 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18758 (declare-function org-element-type "org-element" (element))
18759 (declare-function org-element-context "org-element" ())
18760 (declare-function org-element-contents "org-element" (element))
18761 (declare-function org-element-property "org-element" (property element))
18762 (declare-function org-element-paragraph-parser "org-element" (limit))
18763 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18764 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18765 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18766 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18767 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18769 (defun org-metaup (&optional arg)
18770 "Move subtree up or move table row up.
18771 Calls `org-move-subtree-up' or `org-table-move-row' or
18772 `org-move-item-up', depending on context. See the individual commands
18773 for more information."
18774 (interactive "P")
18775 (cond
18776 ((run-hook-with-args-until-success 'org-metaup-hook))
18777 ((org-region-active-p)
18778 (let* ((a (min (region-beginning) (region-end)))
18779 (b (1- (max (region-beginning) (region-end))))
18780 (c (save-excursion (goto-char a)
18781 (move-beginning-of-line 0)))
18782 (d (save-excursion (goto-char a)
18783 (move-end-of-line 0) (point))))
18784 (transpose-regions a b c d)
18785 (goto-char c)))
18786 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18787 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18788 ((org-at-item-p) (call-interactively 'org-move-item-up))
18789 (t (org-drag-element-backward))))
18791 (defun org-metadown (&optional arg)
18792 "Move subtree down or move table row down.
18793 Calls `org-move-subtree-down' or `org-table-move-row' or
18794 `org-move-item-down', depending on context. See the individual
18795 commands for more information."
18796 (interactive "P")
18797 (cond
18798 ((run-hook-with-args-until-success 'org-metadown-hook))
18799 ((org-region-active-p)
18800 (let* ((a (min (region-beginning) (region-end)))
18801 (b (max (region-beginning) (region-end)))
18802 (c (save-excursion (goto-char b)
18803 (move-beginning-of-line 1)))
18804 (d (save-excursion (goto-char b)
18805 (move-end-of-line 1) (1+ (point)))))
18806 (transpose-regions a b c d)
18807 (goto-char d)))
18808 ((org-at-table-p) (call-interactively 'org-table-move-row))
18809 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18810 ((org-at-item-p) (call-interactively 'org-move-item-down))
18811 (t (org-drag-element-forward))))
18813 (defun org-shiftup (&optional arg)
18814 "Increase item in timestamp or increase priority of current headline.
18815 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18816 depending on context. See the individual commands for more information."
18817 (interactive "P")
18818 (cond
18819 ((run-hook-with-args-until-success 'org-shiftup-hook))
18820 ((and org-support-shift-select (org-region-active-p))
18821 (org-call-for-shift-select 'previous-line))
18822 ((org-at-timestamp-p t)
18823 (call-interactively (if org-edit-timestamp-down-means-later
18824 'org-timestamp-down 'org-timestamp-up)))
18825 ((and (not (eq org-support-shift-select 'always))
18826 org-enable-priority-commands
18827 (org-at-heading-p))
18828 (call-interactively 'org-priority-up))
18829 ((and (not org-support-shift-select) (org-at-item-p))
18830 (call-interactively 'org-previous-item))
18831 ((org-clocktable-try-shift 'up arg))
18832 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18833 (org-support-shift-select
18834 (org-call-for-shift-select 'previous-line))
18835 (t (org-shiftselect-error))))
18837 (defun org-shiftdown (&optional arg)
18838 "Decrease item in timestamp or decrease priority of current headline.
18839 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18840 depending on context. See the individual commands for more information."
18841 (interactive "P")
18842 (cond
18843 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18844 ((and org-support-shift-select (org-region-active-p))
18845 (org-call-for-shift-select 'next-line))
18846 ((org-at-timestamp-p t)
18847 (call-interactively (if org-edit-timestamp-down-means-later
18848 'org-timestamp-up 'org-timestamp-down)))
18849 ((and (not (eq org-support-shift-select 'always))
18850 org-enable-priority-commands
18851 (org-at-heading-p))
18852 (call-interactively 'org-priority-down))
18853 ((and (not org-support-shift-select) (org-at-item-p))
18854 (call-interactively 'org-next-item))
18855 ((org-clocktable-try-shift 'down arg))
18856 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18857 (org-support-shift-select
18858 (org-call-for-shift-select 'next-line))
18859 (t (org-shiftselect-error))))
18861 (defun org-shiftright (&optional arg)
18862 "Cycle the thing at point or in the current line, depending on context.
18863 Depending on context, this does one of the following:
18865 - switch a timestamp at point one day into the future
18866 - on a headline, switch to the next TODO keyword.
18867 - on an item, switch entire list to the next bullet type
18868 - on a property line, switch to the next allowed value
18869 - on a clocktable definition line, move time block into the future"
18870 (interactive "P")
18871 (cond
18872 ((run-hook-with-args-until-success 'org-shiftright-hook))
18873 ((and org-support-shift-select (org-region-active-p))
18874 (org-call-for-shift-select 'forward-char))
18875 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18876 ((and (not (eq org-support-shift-select 'always))
18877 (org-at-heading-p))
18878 (let ((org-inhibit-logging
18879 (not org-treat-S-cursor-todo-selection-as-state-change))
18880 (org-inhibit-blocking
18881 (not org-treat-S-cursor-todo-selection-as-state-change)))
18882 (org-call-with-arg 'org-todo 'right)))
18883 ((or (and org-support-shift-select
18884 (not (eq org-support-shift-select 'always))
18885 (org-at-item-bullet-p))
18886 (and (not org-support-shift-select) (org-at-item-p)))
18887 (org-call-with-arg 'org-cycle-list-bullet nil))
18888 ((and (not (eq org-support-shift-select 'always))
18889 (org-at-property-p))
18890 (call-interactively 'org-property-next-allowed-value))
18891 ((org-clocktable-try-shift 'right arg))
18892 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18893 (org-support-shift-select
18894 (org-call-for-shift-select 'forward-char))
18895 (t (org-shiftselect-error))))
18897 (defun org-shiftleft (&optional arg)
18898 "Cycle the thing at point or in the current line, depending on context.
18899 Depending on context, this does one of the following:
18901 - switch a timestamp at point one day into the past
18902 - on a headline, switch to the previous TODO keyword.
18903 - on an item, switch entire list to the previous bullet type
18904 - on a property line, switch to the previous allowed value
18905 - on a clocktable definition line, move time block into the past"
18906 (interactive "P")
18907 (cond
18908 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18909 ((and org-support-shift-select (org-region-active-p))
18910 (org-call-for-shift-select 'backward-char))
18911 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18912 ((and (not (eq org-support-shift-select 'always))
18913 (org-at-heading-p))
18914 (let ((org-inhibit-logging
18915 (not org-treat-S-cursor-todo-selection-as-state-change))
18916 (org-inhibit-blocking
18917 (not org-treat-S-cursor-todo-selection-as-state-change)))
18918 (org-call-with-arg 'org-todo 'left)))
18919 ((or (and org-support-shift-select
18920 (not (eq org-support-shift-select 'always))
18921 (org-at-item-bullet-p))
18922 (and (not org-support-shift-select) (org-at-item-p)))
18923 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18924 ((and (not (eq org-support-shift-select 'always))
18925 (org-at-property-p))
18926 (call-interactively 'org-property-previous-allowed-value))
18927 ((org-clocktable-try-shift 'left arg))
18928 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18929 (org-support-shift-select
18930 (org-call-for-shift-select 'backward-char))
18931 (t (org-shiftselect-error))))
18933 (defun org-shiftcontrolright ()
18934 "Switch to next TODO set."
18935 (interactive)
18936 (cond
18937 ((and org-support-shift-select (org-region-active-p))
18938 (org-call-for-shift-select 'forward-word))
18939 ((and (not (eq org-support-shift-select 'always))
18940 (org-at-heading-p))
18941 (org-call-with-arg 'org-todo 'nextset))
18942 (org-support-shift-select
18943 (org-call-for-shift-select 'forward-word))
18944 (t (org-shiftselect-error))))
18946 (defun org-shiftcontrolleft ()
18947 "Switch to previous TODO set."
18948 (interactive)
18949 (cond
18950 ((and org-support-shift-select (org-region-active-p))
18951 (org-call-for-shift-select 'backward-word))
18952 ((and (not (eq org-support-shift-select 'always))
18953 (org-at-heading-p))
18954 (org-call-with-arg 'org-todo 'previousset))
18955 (org-support-shift-select
18956 (org-call-for-shift-select 'backward-word))
18957 (t (org-shiftselect-error))))
18959 (defun org-shiftcontrolup ()
18960 "Change timestamps synchronously up in CLOCK log lines."
18961 (interactive)
18962 (cond ((and (not org-support-shift-select)
18963 (org-at-clock-log-p)
18964 (org-at-timestamp-p t))
18965 (org-clock-timestamps-up))
18966 (t (org-shiftselect-error))))
18968 (defun org-shiftcontroldown ()
18969 "Change timestamps synchronously down in CLOCK log lines."
18970 (interactive)
18971 (cond ((and (not org-support-shift-select)
18972 (org-at-clock-log-p)
18973 (org-at-timestamp-p t))
18974 (org-clock-timestamps-down))
18975 (t (org-shiftselect-error))))
18977 (defun org-ctrl-c-ret ()
18978 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18979 (interactive)
18980 (cond
18981 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18982 (t (call-interactively 'org-insert-heading))))
18984 (defun org-find-visible ()
18985 (let ((s (point)))
18986 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18987 (get-char-property s 'invisible)))
18989 (defun org-find-invisible ()
18990 (let ((s (point)))
18991 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18992 (not (get-char-property s 'invisible))))
18995 (defun org-copy-visible (beg end)
18996 "Copy the visible parts of the region."
18997 (interactive "r")
18998 (let (snippets s)
18999 (save-excursion
19000 (save-restriction
19001 (narrow-to-region beg end)
19002 (setq s (goto-char (point-min)))
19003 (while (not (= (point) (point-max)))
19004 (goto-char (org-find-invisible))
19005 (push (buffer-substring s (point)) snippets)
19006 (setq s (goto-char (org-find-visible))))))
19007 (kill-new (apply 'concat (nreverse snippets)))))
19009 (defun org-copy-special ()
19010 "Copy region in table or copy current subtree.
19011 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19012 See the individual commands for more information."
19013 (interactive)
19014 (call-interactively
19015 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19017 (defun org-cut-special ()
19018 "Cut region in table or cut current subtree.
19019 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19020 See the individual commands for more information."
19021 (interactive)
19022 (call-interactively
19023 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19025 (defun org-paste-special (arg)
19026 "Paste rectangular region into table, or past subtree relative to level.
19027 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19028 See the individual commands for more information."
19029 (interactive "P")
19030 (if (org-at-table-p)
19031 (org-table-paste-rectangle)
19032 (org-paste-subtree arg)))
19034 (defun org-edit-special (&optional arg)
19035 "Call a special editor for the stuff at point.
19036 When at a table, call the formula editor with `org-table-edit-formulas'.
19037 When at the first line of an src example, call `org-edit-src-code'.
19038 When in an #+include line, visit the include file. Otherwise call
19039 `ffap' to visit the file at point."
19040 (interactive)
19041 ;; possibly prep session before editing source
19042 (when arg
19043 (let* ((info (org-babel-get-src-block-info))
19044 (lang (nth 0 info))
19045 (params (nth 2 info))
19046 (session (cdr (assoc :session params))))
19047 (when (and info session) ;; we are in a source-code block with a session
19048 (funcall
19049 (intern (concat "org-babel-prep-session:" lang)) session params))))
19050 (cond ;; proceed with `org-edit-special'
19051 ((save-excursion
19052 (beginning-of-line 1)
19053 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19054 (find-file (org-trim (match-string 1))))
19055 ((org-edit-src-code))
19056 ((org-edit-fixed-width-region))
19057 ((org-at-table.el-p)
19058 (org-edit-src-code))
19059 ((or (org-at-table-p)
19060 (save-excursion
19061 (beginning-of-line 1)
19062 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19063 (call-interactively 'org-table-edit-formulas))
19064 (t (call-interactively 'ffap))))
19066 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19067 (defun org-ctrl-c-ctrl-c (&optional arg)
19068 "Set tags in headline, or update according to changed information at point.
19070 This command does many different things, depending on context:
19072 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19073 this is what we do.
19075 - If the cursor is on a statistics cookie, update it.
19077 - If the cursor is in a headline, prompt for tags and insert them
19078 into the current line, aligned to `org-tags-column'. When called
19079 with prefix arg, realign all tags in the current buffer.
19081 - If the cursor is in one of the special #+KEYWORD lines, this
19082 triggers scanning the buffer for these lines and updating the
19083 information.
19085 - If the cursor is inside a table, realign the table. This command
19086 works even if the automatic table editor has been turned off.
19088 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19089 the entire table.
19091 - If the cursor is at a footnote reference or definition, jump to
19092 the corresponding definition or references, respectively.
19094 - If the cursor is a the beginning of a dynamic block, update it.
19096 - If the current buffer is a capture buffer, close note and file it.
19098 - If the cursor is on a <<<target>>>, update radio targets and
19099 corresponding links in this buffer.
19101 - If the cursor is on a numbered item in a plain list, renumber the
19102 ordered list.
19104 - If the cursor is on a checkbox, toggle it.
19106 - If the cursor is on a code block, evaluate it. The variable
19107 `org-confirm-babel-evaluate' can be used to control prompting
19108 before code block evaluation, by default every code block
19109 evaluation requires confirmation. Code block evaluation can be
19110 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19111 (interactive "P")
19112 (let ((org-enable-table-editor t))
19113 (cond
19114 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19115 org-occur-highlights
19116 org-latex-fragment-image-overlays)
19117 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19118 (org-remove-occur-highlights)
19119 (org-remove-latex-fragment-image-overlays)
19120 (message "Temporary highlights/overlays removed from current buffer"))
19121 ((and (local-variable-p 'org-finish-function (current-buffer))
19122 (fboundp org-finish-function))
19123 (funcall org-finish-function))
19124 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19125 ((org-in-regexp org-ts-regexp-both)
19126 (org-timestamp-change 0 'day))
19127 ((or (looking-at org-property-start-re)
19128 (org-at-property-p))
19129 (call-interactively 'org-property-action))
19130 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19131 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19132 (or (org-at-heading-p) (org-at-item-p)))
19133 (call-interactively 'org-update-statistics-cookies))
19134 ((org-at-heading-p) (call-interactively 'org-set-tags))
19135 ((org-at-table.el-p)
19136 (message "Use C-c ' to edit table.el tables"))
19137 ((org-at-table-p)
19138 (org-table-maybe-eval-formula)
19139 (if arg
19140 (call-interactively 'org-table-recalculate)
19141 (org-table-maybe-recalculate-line))
19142 (call-interactively 'org-table-align)
19143 (orgtbl-send-table 'maybe))
19144 ((or (org-footnote-at-reference-p)
19145 (org-footnote-at-definition-p))
19146 (call-interactively 'org-footnote-action))
19147 ((org-at-item-checkbox-p)
19148 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19149 ;; list only if at top item.
19150 (let* ((cbox (match-string 1))
19151 (struct (org-list-struct))
19152 (old-struct (copy-tree struct))
19153 (parents (org-list-parents-alist struct))
19154 (orderedp (org-entry-get nil "ORDERED"))
19155 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19156 block-item)
19157 ;; Use a light version of `org-toggle-checkbox' to avoid
19158 ;; computing list structure twice.
19159 (let ((new-box (cond
19160 ((equal arg '(16)) "[-]")
19161 ((equal arg '(4)) nil)
19162 ((equal "[X]" cbox) "[ ]")
19163 (t "[X]"))))
19164 (if (and firstp arg)
19165 ;; If at first item of sub-list, remove check-box from
19166 ;; every item at the same level.
19167 (mapc
19168 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19169 (org-list-get-all-items
19170 (point-at-bol) struct (org-list-prevs-alist struct)))
19171 (org-list-set-checkbox (point-at-bol) struct new-box)))
19172 ;; Replicate `org-list-write-struct', while grabbing a return
19173 ;; value from `org-list-struct-fix-box'.
19174 (org-list-struct-fix-ind struct parents 2)
19175 (org-list-struct-fix-item-end struct)
19176 (let ((prevs (org-list-prevs-alist struct)))
19177 (org-list-struct-fix-bul struct prevs)
19178 (org-list-struct-fix-ind struct parents)
19179 (setq block-item
19180 (org-list-struct-fix-box struct parents prevs orderedp)))
19181 (org-list-struct-apply-struct struct old-struct)
19182 (org-update-checkbox-count-maybe)
19183 (when block-item
19184 (message
19185 "Checkboxes were removed due to unchecked box at line %d"
19186 (org-current-line block-item)))
19187 (when firstp (org-list-send-list 'maybe))))
19188 ((org-at-item-p)
19189 ;; Cursor at an item: repair list. Do checkbox related actions
19190 ;; only if function was called with an argument. Send list only
19191 ;; if at top item.
19192 (let* ((struct (org-list-struct))
19193 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19194 old-struct)
19195 (when arg
19196 (setq old-struct (copy-tree struct))
19197 (if firstp
19198 ;; If at first item of sub-list, add check-box to every
19199 ;; item at the same level.
19200 (mapc
19201 (lambda (pos)
19202 (unless (org-list-get-checkbox pos struct)
19203 (org-list-set-checkbox pos struct "[ ]")))
19204 (org-list-get-all-items
19205 (point-at-bol) struct (org-list-prevs-alist struct)))
19206 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19207 (org-list-write-struct
19208 struct (org-list-parents-alist struct) old-struct)
19209 (when arg (org-update-checkbox-count-maybe))
19210 (when firstp (org-list-send-list 'maybe))))
19211 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19212 ;; Dynamic block
19213 (beginning-of-line 1)
19214 (save-excursion (org-update-dblock)))
19215 ((save-excursion
19216 (let ((case-fold-search t))
19217 (beginning-of-line 1)
19218 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19219 (cond
19220 ((or (equal (match-string 1) "TBLFM")
19221 (equal (match-string 1) "tblfm"))
19222 ;; Recalculate the table before this line
19223 (save-excursion
19224 (beginning-of-line 1)
19225 (skip-chars-backward " \r\n\t")
19226 (if (org-at-table-p)
19227 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19229 (let ((org-inhibit-startup-visibility-stuff t)
19230 (org-startup-align-all-tables nil))
19231 (when (boundp 'org-table-coordinate-overlays)
19232 (mapc 'delete-overlay org-table-coordinate-overlays)
19233 (setq org-table-coordinate-overlays nil))
19234 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19235 (message "Local setup has been refreshed"))))
19236 ((org-clock-update-time-maybe))
19238 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19239 (error "C-c C-c can do nothing useful at this location"))))))
19241 (defun org-mode-restart ()
19242 "Restart Org-mode, to scan again for special lines.
19243 Also updates the keyword regular expressions."
19244 (interactive)
19245 (org-mode)
19246 (message "Org-mode restarted"))
19248 (defun org-kill-note-or-show-branches ()
19249 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19250 (interactive)
19251 (if (not org-finish-function)
19252 (progn
19253 (hide-subtree)
19254 (call-interactively 'show-branches))
19255 (let ((org-note-abort t))
19256 (funcall org-finish-function))))
19258 (defun org-return (&optional indent)
19259 "Goto next table row or insert a newline.
19260 Calls `org-table-next-row' or `newline', depending on context.
19261 See the individual commands for more information."
19262 (interactive)
19263 (let (org-ts-what)
19264 (cond
19265 ((or (bobp) (org-in-src-block-p))
19266 (if indent (newline-and-indent) (newline)))
19267 ((org-at-table-p)
19268 (org-table-justify-field-maybe)
19269 (call-interactively 'org-table-next-row))
19270 ;; when `newline-and-indent' is called within a list, make sure
19271 ;; text moved stays inside the item.
19272 ((and (org-in-item-p) indent)
19273 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19274 (progn
19275 (save-match-data (newline))
19276 (org-indent-line-to (length (match-string 0))))
19277 (let ((ind (org-get-indentation)))
19278 (newline)
19279 (if (org-looking-back org-list-end-re)
19280 (org-indent-line)
19281 (org-indent-line-to ind)))))
19282 ((and org-return-follows-link
19283 (org-at-timestamp-p t)
19284 (not (eq org-ts-what 'after)))
19285 (org-follow-timestamp-link))
19286 ((and org-return-follows-link
19287 (let ((tprop (get-text-property (point) 'face)))
19288 (or (eq tprop 'org-link)
19289 (and (listp tprop) (memq 'org-link tprop)))))
19290 (call-interactively 'org-open-at-point))
19291 ((and (org-at-heading-p)
19292 (looking-at
19293 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19294 (org-show-entry)
19295 (end-of-line 1)
19296 (newline))
19297 (t (if indent (newline-and-indent) (newline))))))
19299 (defun org-return-indent ()
19300 "Goto next table row or insert a newline and indent.
19301 Calls `org-table-next-row' or `newline-and-indent', depending on
19302 context. See the individual commands for more information."
19303 (interactive)
19304 (org-return t))
19306 (defun org-ctrl-c-star ()
19307 "Compute table, or change heading status of lines.
19308 Calls `org-table-recalculate' or `org-toggle-heading',
19309 depending on context."
19310 (interactive)
19311 (cond
19312 ((org-at-table-p)
19313 (call-interactively 'org-table-recalculate))
19315 ;; Convert all lines in region to list items
19316 (call-interactively 'org-toggle-heading))))
19318 (defun org-ctrl-c-minus ()
19319 "Insert separator line in table or modify bullet status of line.
19320 Also turns a plain line or a region of lines into list items.
19321 Calls `org-table-insert-hline', `org-toggle-item', or
19322 `org-cycle-list-bullet', depending on context."
19323 (interactive)
19324 (cond
19325 ((org-at-table-p)
19326 (call-interactively 'org-table-insert-hline))
19327 ((org-region-active-p)
19328 (call-interactively 'org-toggle-item))
19329 ((org-in-item-p)
19330 (call-interactively 'org-cycle-list-bullet))
19332 (call-interactively 'org-toggle-item))))
19334 (defun org-toggle-item (arg)
19335 "Convert headings or normal lines to items, items to normal lines.
19336 If there is no active region, only the current line is considered.
19338 If the first non blank line in the region is an headline, convert
19339 all headlines to items, shifting text accordingly.
19341 If it is an item, convert all items to normal lines.
19343 If it is normal text, change region into an item. With a prefix
19344 argument ARG, change each line in region into an item."
19345 (interactive "P")
19346 (let ((shift-text
19347 (function
19348 ;; Shift text in current section to IND, from point to END.
19349 ;; The function leaves point to END line.
19350 (lambda (ind end)
19351 (let ((min-i 1000) (end (copy-marker end)))
19352 ;; First determine the minimum indentation (MIN-I) of
19353 ;; the text.
19354 (save-excursion
19355 (catch 'exit
19356 (while (< (point) end)
19357 (let ((i (org-get-indentation)))
19358 (cond
19359 ;; Skip blank lines and inline tasks.
19360 ((looking-at "^[ \t]*$"))
19361 ((looking-at org-outline-regexp-bol))
19362 ;; We can't find less than 0 indentation.
19363 ((zerop i) (throw 'exit (setq min-i 0)))
19364 ((< i min-i) (setq min-i i))))
19365 (forward-line))))
19366 ;; Then indent each line so that a line indented to
19367 ;; MIN-I becomes indented to IND. Ignore blank lines
19368 ;; and inline tasks in the process.
19369 (let ((delta (- ind min-i)))
19370 (while (< (point) end)
19371 (unless (or (looking-at "^[ \t]*$")
19372 (looking-at org-outline-regexp-bol))
19373 (org-indent-line-to (+ (org-get-indentation) delta)))
19374 (forward-line)))))))
19375 (skip-blanks
19376 (function
19377 ;; Return beginning of first non-blank line, starting from
19378 ;; line at POS.
19379 (lambda (pos)
19380 (save-excursion
19381 (goto-char pos)
19382 (skip-chars-forward " \r\t\n")
19383 (point-at-bol)))))
19384 beg end)
19385 ;; Determine boundaries of changes.
19386 (if (org-region-active-p)
19387 (setq beg (funcall skip-blanks (region-beginning))
19388 end (copy-marker (region-end)))
19389 (setq beg (funcall skip-blanks (point-at-bol))
19390 end (copy-marker (point-at-eol))))
19391 ;; Depending on the starting line, choose an action on the text
19392 ;; between BEG and END.
19393 (org-with-limited-levels
19394 (save-excursion
19395 (goto-char beg)
19396 (cond
19397 ;; Case 1. Start at an item: de-itemize. Note that it only
19398 ;; happens when a region is active: `org-ctrl-c-minus'
19399 ;; would call `org-cycle-list-bullet' otherwise.
19400 ((org-at-item-p)
19401 (while (< (point) end)
19402 (when (org-at-item-p)
19403 (skip-chars-forward " \t")
19404 (delete-region (point) (match-end 0)))
19405 (forward-line)))
19406 ;; Case 2. Start at an heading: convert to items.
19407 ((org-at-heading-p)
19408 (let* ((bul (org-list-bullet-string "-"))
19409 (bul-len (length bul))
19410 ;; Indentation of the first heading. It should be
19411 ;; relative to the indentation of its parent, if any.
19412 (start-ind (save-excursion
19413 (cond
19414 ((not org-adapt-indentation) 0)
19415 ((not (outline-previous-heading)) 0)
19416 (t (length (match-string 0))))))
19417 ;; Level of first heading. Further headings will be
19418 ;; compared to it to determine hierarchy in the list.
19419 (ref-level (org-reduced-level (org-outline-level))))
19420 (while (< (point) end)
19421 (let* ((level (org-reduced-level (org-outline-level)))
19422 (delta (max 0 (- level ref-level))))
19423 ;; If current headline is less indented than the first
19424 ;; one, set it as reference, in order to preserve
19425 ;; subtrees.
19426 (when (< level ref-level) (setq ref-level level))
19427 (replace-match bul t t)
19428 (org-indent-line-to (+ start-ind (* delta bul-len)))
19429 ;; Ensure all text down to END (or SECTION-END) belongs
19430 ;; to the newly created item.
19431 (let ((section-end (save-excursion
19432 (or (outline-next-heading) (point)))))
19433 (forward-line)
19434 (funcall shift-text
19435 (+ start-ind (* (1+ delta) bul-len))
19436 (min end section-end)))))))
19437 ;; Case 3. Normal line with ARG: turn each non-item line into
19438 ;; an item.
19439 (arg
19440 (while (< (point) end)
19441 (unless (or (org-at-heading-p) (org-at-item-p))
19442 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19443 (replace-match
19444 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19445 (forward-line)))
19446 ;; Case 4. Normal line without ARG: make the first line of
19447 ;; region an item, and shift indentation of others
19448 ;; lines to set them as item's body.
19449 (t (let* ((bul (org-list-bullet-string "-"))
19450 (bul-len (length bul))
19451 (ref-ind (org-get-indentation)))
19452 (skip-chars-forward " \t")
19453 (insert bul)
19454 (forward-line)
19455 (while (< (point) end)
19456 ;; Ensure that lines less indented than first one
19457 ;; still get included in item body.
19458 (funcall shift-text
19459 (+ ref-ind bul-len)
19460 (min end (save-excursion (or (outline-next-heading)
19461 (point)))))
19462 (forward-line)))))))))
19464 (defun org-toggle-heading (&optional nstars)
19465 "Convert headings to normal text, or items or text to headings.
19466 If there is no active region, only the current line is considered.
19468 With a \\[universal-argument] prefix, convert the whole list at
19469 point into heading.
19471 In a region:
19473 - If the first non blank line is an headline, remove the stars
19474 from all headlines in the region.
19476 - If it is a normal line turn each and every normal line (i.e. not an
19477 heading or an item) in the region into a heading.
19479 - If it is a plain list item, turn all plain list items into headings.
19481 When converting a line into a heading, the number of stars is chosen
19482 such that the lines become children of the current entry. However,
19483 when a prefix argument is given, its value determines the number of
19484 stars to add."
19485 (interactive "P")
19486 (let ((skip-blanks
19487 (function
19488 ;; Return beginning of first non-blank line, starting from
19489 ;; line at POS.
19490 (lambda (pos)
19491 (save-excursion
19492 (goto-char pos)
19493 (while (org-at-comment-p) (forward-line))
19494 (skip-chars-forward " \r\t\n")
19495 (point-at-bol)))))
19496 beg end toggled)
19497 ;; Determine boundaries of changes. If a universal prefix has
19498 ;; been given, put the list in a region. If region ends at a bol,
19499 ;; do not consider the last line to be in the region.
19501 (when (and current-prefix-arg (org-at-item-p))
19502 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19503 (org-mark-element))
19505 (if (org-region-active-p)
19506 (setq beg (funcall skip-blanks (region-beginning))
19507 end (copy-marker (save-excursion
19508 (goto-char (region-end))
19509 (if (bolp) (point) (point-at-eol)))))
19510 (setq beg (funcall skip-blanks (point-at-bol))
19511 end (copy-marker (point-at-eol))))
19512 ;; Ensure inline tasks don't count as headings.
19513 (org-with-limited-levels
19514 (save-excursion
19515 (goto-char beg)
19516 (cond
19517 ;; Case 1. Started at an heading: de-star headings.
19518 ((org-at-heading-p)
19519 (while (< (point) end)
19520 (when (org-at-heading-p t)
19521 (looking-at org-outline-regexp) (replace-match "")
19522 (setq toggled t))
19523 (forward-line)))
19524 ;; Case 2. Started at an item: change items into headlines.
19525 ;; One star will be added by `org-list-to-subtree'.
19526 ((org-at-item-p)
19527 (let* ((stars (make-string
19528 (if nstars
19529 ;; subtract the star that will be added again by
19530 ;; `org-list-to-subtree'
19531 (1- (prefix-numeric-value current-prefix-arg))
19532 (or (org-current-level) 0))
19533 ?*))
19534 (add-stars
19535 (cond (nstars "") ; stars from prefix only
19536 ((equal stars "") "") ; before first heading
19537 (org-odd-levels-only "*") ; inside heading, odd
19538 (t "")))) ; inside heading, oddeven
19539 (while (< (point) end)
19540 (when (org-at-item-p)
19541 ;; Pay attention to cases when region ends before list.
19542 (let* ((struct (org-list-struct))
19543 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19544 (save-restriction
19545 (narrow-to-region (point) list-end)
19546 (insert
19547 (org-list-to-subtree
19548 (org-list-parse-list t)
19549 '(:istart (concat stars add-stars (funcall get-stars depth))
19550 :icount (concat stars add-stars (funcall get-stars depth)))))))
19551 (setq toggled t))
19552 (forward-line))))
19553 ;; Case 3. Started at normal text: make every line an heading,
19554 ;; skipping headlines and items.
19555 (t (let* ((stars (make-string
19556 (if nstars
19557 (prefix-numeric-value current-prefix-arg)
19558 (or (org-current-level) 0))
19559 ?*))
19560 (add-stars
19561 (cond (nstars "") ; stars from prefix only
19562 ((equal stars "") "*") ; before first heading
19563 (org-odd-levels-only "**") ; inside heading, odd
19564 (t "*"))) ; inside heading, oddeven
19565 (rpl (concat stars add-stars " ")))
19566 (while (< (point) end)
19567 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19568 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19569 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19570 (forward-line)))))))
19571 (unless toggled (message "Cannot toggle heading from here"))))
19573 (defun org-meta-return (&optional arg)
19574 "Insert a new heading or wrap a region in a table.
19575 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19576 See the individual commands for more information."
19577 (interactive "P")
19578 (cond
19579 ((run-hook-with-args-until-success 'org-metareturn-hook))
19580 ((or (org-at-drawer-p) (org-at-property-p))
19581 (newline-and-indent))
19582 ((org-at-table-p)
19583 (call-interactively 'org-table-wrap-region))
19584 (t (call-interactively 'org-insert-heading))))
19586 ;;; Menu entries
19588 (defsubst org-in-subtree-not-table-p ()
19589 "Are we in a subtree and not in a table?"
19590 (and (not (org-before-first-heading-p))
19591 (not (org-at-table-p))))
19593 ;; Define the Org-mode menus
19594 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19595 '("Tbl"
19596 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19597 ["Next Field" org-cycle (org-at-table-p)]
19598 ["Previous Field" org-shifttab (org-at-table-p)]
19599 ["Next Row" org-return (org-at-table-p)]
19600 "--"
19601 ["Blank Field" org-table-blank-field (org-at-table-p)]
19602 ["Edit Field" org-table-edit-field (org-at-table-p)]
19603 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19604 "--"
19605 ("Column"
19606 ["Move Column Left" org-metaleft (org-at-table-p)]
19607 ["Move Column Right" org-metaright (org-at-table-p)]
19608 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19609 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19610 ("Row"
19611 ["Move Row Up" org-metaup (org-at-table-p)]
19612 ["Move Row Down" org-metadown (org-at-table-p)]
19613 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19614 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19615 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19616 "--"
19617 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19618 ("Rectangle"
19619 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19620 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19621 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19622 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19623 "--"
19624 ("Calculate"
19625 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19626 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19627 ["Edit Formulas" org-edit-special (org-at-table-p)]
19628 "--"
19629 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19630 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19631 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19632 "--"
19633 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19634 "--"
19635 ["Sum Column/Rectangle" org-table-sum
19636 (or (org-at-table-p) (org-region-active-p))]
19637 ["Which Column?" org-table-current-column (org-at-table-p)])
19638 ["Debug Formulas"
19639 org-table-toggle-formula-debugger
19640 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19641 ["Show Col/Row Numbers"
19642 org-table-toggle-coordinate-overlays
19643 :style toggle
19644 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19645 "--"
19646 ["Create" org-table-create (and (not (org-at-table-p))
19647 org-enable-table-editor)]
19648 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19649 ["Import from File" org-table-import (not (org-at-table-p))]
19650 ["Export to File" org-table-export (org-at-table-p)]
19651 "--"
19652 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19654 (easy-menu-define org-org-menu org-mode-map "Org menu"
19655 '("Org"
19656 ("Show/Hide"
19657 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19658 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19659 ["Sparse Tree..." org-sparse-tree t]
19660 ["Reveal Context" org-reveal t]
19661 ["Show All" show-all t]
19662 "--"
19663 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19664 "--"
19665 ["New Heading" org-insert-heading t]
19666 ("Navigate Headings"
19667 ["Up" outline-up-heading t]
19668 ["Next" outline-next-visible-heading t]
19669 ["Previous" outline-previous-visible-heading t]
19670 ["Next Same Level" outline-forward-same-level t]
19671 ["Previous Same Level" outline-backward-same-level t]
19672 "--"
19673 ["Jump" org-goto t])
19674 ("Edit Structure"
19675 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19676 "--"
19677 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19678 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19679 "--"
19680 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19681 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19682 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19683 "--"
19684 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19685 "--"
19686 ["Copy visible text" org-copy-visible t]
19687 "--"
19688 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19689 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19690 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19691 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19692 "--"
19693 ["Sort Region/Children" org-sort t]
19694 "--"
19695 ["Convert to odd levels" org-convert-to-odd-levels t]
19696 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19697 ("Editing"
19698 ["Emphasis..." org-emphasize t]
19699 ["Edit Source Example" org-edit-special t]
19700 "--"
19701 ["Footnote new/jump" org-footnote-action t]
19702 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19703 ("Archive"
19704 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19705 "--"
19706 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19707 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19708 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19710 "--"
19711 ("Hyperlinks"
19712 ["Store Link (Global)" org-store-link t]
19713 ["Find existing link to here" org-occur-link-in-agenda-files t]
19714 ["Insert Link" org-insert-link t]
19715 ["Follow Link" org-open-at-point t]
19716 "--"
19717 ["Next link" org-next-link t]
19718 ["Previous link" org-previous-link t]
19719 "--"
19720 ["Descriptive Links"
19721 org-toggle-link-display
19722 :style radio
19723 :selected org-descriptive-links
19725 ["Literal Links"
19726 org-toggle-link-display
19727 :style radio
19728 :selected (not org-descriptive-links)])
19729 "--"
19730 ("TODO Lists"
19731 ["TODO/DONE/-" org-todo t]
19732 ("Select keyword"
19733 ["Next keyword" org-shiftright (org-at-heading-p)]
19734 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19735 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19736 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19737 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19738 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19739 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19740 "--"
19741 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19742 :selected org-enforce-todo-dependencies :style toggle :active t]
19743 "Settings for tree at point"
19744 ["Do Children sequentially" org-toggle-ordered-property :style radio
19745 :selected (org-entry-get nil "ORDERED")
19746 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19747 ["Do Children parallel" org-toggle-ordered-property :style radio
19748 :selected (not (org-entry-get nil "ORDERED"))
19749 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19750 "--"
19751 ["Set Priority" org-priority t]
19752 ["Priority Up" org-shiftup t]
19753 ["Priority Down" org-shiftdown t]
19754 "--"
19755 ["Get news from all feeds" org-feed-update-all t]
19756 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19757 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19758 ("TAGS and Properties"
19759 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19760 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19761 "--"
19762 ["Set property" org-set-property (not (org-before-first-heading-p))]
19763 ["Column view of properties" org-columns t]
19764 ["Insert Column View DBlock" org-insert-columns-dblock t])
19765 ("Dates and Scheduling"
19766 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19767 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19768 ("Change Date"
19769 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19770 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19771 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19772 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19773 ["Compute Time Range" org-evaluate-time-range t]
19774 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19775 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19776 "--"
19777 ["Custom time format" org-toggle-time-stamp-overlays
19778 :style radio :selected org-display-custom-times]
19779 "--"
19780 ["Goto Calendar" org-goto-calendar t]
19781 ["Date from Calendar" org-date-from-calendar t]
19782 "--"
19783 ["Start/Restart Timer" org-timer-start t]
19784 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19785 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19786 ["Insert Timer String" org-timer t]
19787 ["Insert Timer Item" org-timer-item t])
19788 ("Logging work"
19789 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19790 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19791 ["Clock out" org-clock-out t]
19792 ["Clock cancel" org-clock-cancel t]
19793 "--"
19794 ["Mark as default task" org-clock-mark-default-task t]
19795 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19796 ["Goto running clock" org-clock-goto t]
19797 "--"
19798 ["Display times" org-clock-display t]
19799 ["Create clock table" org-clock-report t]
19800 "--"
19801 ["Record DONE time"
19802 (progn (setq org-log-done (not org-log-done))
19803 (message "Switching to %s will %s record a timestamp"
19804 (car org-done-keywords)
19805 (if org-log-done "automatically" "not")))
19806 :style toggle :selected org-log-done])
19807 "--"
19808 ["Agenda Command..." org-agenda t]
19809 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19810 ("File List for Agenda")
19811 ("Special views current file"
19812 ["TODO Tree" org-show-todo-tree t]
19813 ["Check Deadlines" org-check-deadlines t]
19814 ["Timeline" org-timeline t]
19815 ["Tags/Property tree" org-match-sparse-tree t])
19816 "--"
19817 ["Export/Publish..." org-export t]
19818 ("LaTeX"
19819 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19820 :selected org-cdlatex-mode]
19821 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19822 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19823 ["Modify math symbol" org-cdlatex-math-modify
19824 (org-inside-LaTeX-fragment-p)]
19825 ["Insert citation" org-reftex-citation t]
19826 "--"
19827 ["Template for BEAMER" (progn (require 'org-beamer)
19828 (org-insert-beamer-options-template)) t])
19829 "--"
19830 ("MobileOrg"
19831 ["Push Files and Views" org-mobile-push t]
19832 ["Get Captured and Flagged" org-mobile-pull t]
19833 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19834 "--"
19835 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19836 "--"
19837 ("Documentation"
19838 ["Show Version" org-version t]
19839 ["Info Documentation" org-info t])
19840 ("Customize"
19841 ["Browse Org Group" org-customize t]
19842 "--"
19843 ["Expand This Menu" org-create-customize-menu
19844 (fboundp 'customize-menu-create)])
19845 ["Send bug report" org-submit-bug-report t]
19846 "--"
19847 ("Refresh/Reload"
19848 ["Refresh setup current buffer" org-mode-restart t]
19849 ["Reload Org (after update)" org-reload t]
19850 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19853 (defun org-info (&optional node)
19854 "Read documentation for Org-mode in the info system.
19855 With optional NODE, go directly to that node."
19856 (interactive)
19857 (info (format "(org)%s" (or node ""))))
19859 ;;;###autoload
19860 (defun org-submit-bug-report ()
19861 "Submit a bug report on Org-mode via mail.
19863 Don't hesitate to report any problems or inaccurate documentation.
19865 If you don't have setup sending mail from (X)Emacs, please copy the
19866 output buffer into your mail program, as it gives us important
19867 information about your Org-mode version and configuration."
19868 (interactive)
19869 (require 'reporter)
19870 (org-load-modules-maybe)
19871 (org-require-autoloaded-modules)
19872 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19873 (reporter-submit-bug-report
19874 "emacs-orgmode@gnu.org"
19875 (org-version nil 'full)
19876 (let (list)
19877 (save-window-excursion
19878 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19879 (delete-other-windows)
19880 (erase-buffer)
19881 (insert "You are about to submit a bug report to the Org-mode mailing list.
19883 We would like to add your full Org-mode and Outline configuration to the
19884 bug report. This greatly simplifies the work of the maintainer and
19885 other experts on the mailing list.
19887 HOWEVER, some variables you have customized may contain private
19888 information. The names of customers, colleagues, or friends, might
19889 appear in the form of file names, tags, todo states, or search strings.
19890 If you answer yes to the prompt, you might want to check and remove
19891 such private information before sending the email.")
19892 (add-text-properties (point-min) (point-max) '(face org-warning))
19893 (when (yes-or-no-p "Include your Org-mode configuration ")
19894 (mapatoms
19895 (lambda (v)
19896 (and (boundp v)
19897 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19898 (or (and (symbol-value v)
19899 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19900 (and
19901 (get v 'custom-type) (get v 'standard-value)
19902 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19903 (push v list)))))
19904 (kill-buffer (get-buffer "*Warn about privacy*"))
19905 list))
19906 nil nil
19907 "Remember to cover the basics, that is, what you expected to happen and
19908 what in fact did happen. You don't know how to make a good report? See
19910 http://orgmode.org/manual/Feedback.html#Feedback
19912 Your bug report will be posted to the Org-mode mailing list.
19913 ------------------------------------------------------------------------")
19914 (save-excursion
19915 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19916 (replace-match "\\1Bug: \\3 [\\2]")))))
19919 (defun org-install-agenda-files-menu ()
19920 (let ((bl (buffer-list)))
19921 (save-excursion
19922 (while bl
19923 (set-buffer (pop bl))
19924 (if (derived-mode-p 'org-mode) (setq bl nil)))
19925 (when (derived-mode-p 'org-mode)
19926 (easy-menu-change
19927 '("Org") "File List for Agenda"
19928 (append
19929 (list
19930 ["Edit File List" (org-edit-agenda-file-list) t]
19931 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19932 ["Remove Current File from List" org-remove-file t]
19933 ["Cycle through agenda files" org-cycle-agenda-files t]
19934 ["Occur in all agenda files" org-occur-in-agenda-files t]
19935 "--")
19936 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19938 ;;;; Documentation
19940 ;;;###autoload
19941 (defun org-require-autoloaded-modules ()
19942 (interactive)
19943 (mapc 'require
19944 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19945 org-docbook org-exp org-html org-icalendar
19946 org-id org-latex
19947 org-publish org-remember org-table
19948 org-timer org-xoxo)))
19950 ;;;###autoload
19951 (defun org-reload (&optional uncompiled)
19952 "Reload all org lisp files.
19953 With prefix arg UNCOMPILED, load the uncompiled versions."
19954 (interactive "P")
19955 (require 'find-func)
19956 (let* ((file-re "^org\\(-.*\\)?\\.el")
19957 (dir-org (file-name-directory (org-find-library-dir "org")))
19958 (dir-org-contrib (ignore-errors
19959 (file-name-directory
19960 (org-find-library-dir "org-contribdir"))))
19961 (babel-files
19962 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19963 (append (list nil "comint" "eval" "exp" "keys"
19964 "lob" "ref" "table" "tangle")
19965 (delq nil
19966 (mapcar
19967 (lambda (lang)
19968 (when (cdr lang) (symbol-name (car lang))))
19969 org-babel-load-languages)))))
19970 (files
19971 (append babel-files
19972 (and dir-org-contrib
19973 (directory-files dir-org-contrib t file-re))
19974 (directory-files dir-org t file-re)))
19975 (remove-re (concat (if (featurep 'xemacs)
19976 "org-colview" "org-colview-xemacs")
19977 "\\'")))
19978 (setq files (mapcar 'file-name-sans-extension files))
19979 (setq files (mapcar
19980 (lambda (x) (if (string-match remove-re x) nil x))
19981 files))
19982 (setq files (delq nil files))
19983 (mapc
19984 (lambda (f)
19985 (when (featurep (intern (file-name-nondirectory f)))
19986 (if (and (not uncompiled)
19987 (file-exists-p (concat f ".elc")))
19988 (load (concat f ".elc") nil nil 'nosuffix)
19989 (load (concat f ".el") nil nil 'nosuffix))))
19990 files)
19991 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19992 (org-version nil 'full 'message))
19994 ;;;###autoload
19995 (defun org-customize ()
19996 "Call the customize function with org as argument."
19997 (interactive)
19998 (org-load-modules-maybe)
19999 (org-require-autoloaded-modules)
20000 (customize-browse 'org))
20002 (defun org-create-customize-menu ()
20003 "Create a full customization menu for Org-mode, insert it into the menu."
20004 (interactive)
20005 (org-load-modules-maybe)
20006 (org-require-autoloaded-modules)
20007 (if (fboundp 'customize-menu-create)
20008 (progn
20009 (easy-menu-change
20010 '("Org") "Customize"
20011 `(["Browse Org group" org-customize t]
20012 "--"
20013 ,(customize-menu-create 'org)
20014 ["Set" Custom-set t]
20015 ["Save" Custom-save t]
20016 ["Reset to Current" Custom-reset-current t]
20017 ["Reset to Saved" Custom-reset-saved t]
20018 ["Reset to Standard Settings" Custom-reset-standard t]))
20019 (message "\"Org\"-menu now contains full customization menu"))
20020 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20022 ;;;; Miscellaneous stuff
20024 ;;; Generally useful functions
20026 (defun org-get-at-bol (property)
20027 "Get text property PROPERTY at beginning of line."
20028 (get-text-property (point-at-bol) property))
20030 (defun org-find-text-property-in-string (prop s)
20031 "Return the first non-nil value of property PROP in string S."
20032 (or (get-text-property 0 prop s)
20033 (get-text-property (or (next-single-property-change 0 prop s) 0)
20034 prop s)))
20036 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20037 "Display the given MESSAGE as a warning."
20038 (if (fboundp 'display-warning)
20039 (display-warning 'org message
20040 (if (featurep 'xemacs) 'warning :warning))
20041 (let ((buf (get-buffer-create "*Org warnings*")))
20042 (with-current-buffer buf
20043 (goto-char (point-max))
20044 (insert "Warning (Org): " message)
20045 (unless (bolp)
20046 (newline)))
20047 (display-buffer buf)
20048 (sit-for 0))))
20050 (defun org-eval (form)
20051 "Eval FORM and return result."
20052 (condition-case error
20053 (eval form)
20054 (error (format "%%![Error: %s]" error))))
20056 (defun org-in-clocktable-p ()
20057 "Check if the cursor is in a clocktable."
20058 (let ((pos (point)) start)
20059 (save-excursion
20060 (end-of-line 1)
20061 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20062 (setq start (match-beginning 0))
20063 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20064 (>= (match-end 0) pos)
20065 start))))
20067 (defun org-in-commented-line ()
20068 "Is point in a line starting with `#'?"
20069 (equal (char-after (point-at-bol)) ?#))
20071 (defun org-in-indented-comment-line ()
20072 "Is point in a line starting with `#' after some white space?"
20073 (save-excursion
20074 (save-match-data
20075 (goto-char (point-at-bol))
20076 (looking-at "[ \t]*#"))))
20078 (defun org-in-verbatim-emphasis ()
20079 (save-match-data
20080 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20082 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20083 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20084 (if (and marker (marker-buffer marker)
20085 (buffer-live-p (marker-buffer marker)))
20086 (progn
20087 (org-pop-to-buffer-same-window (marker-buffer marker))
20088 (if (or (> marker (point-max)) (< marker (point-min)))
20089 (widen))
20090 (goto-char marker)
20091 (org-show-context 'org-goto))
20092 (if bookmark
20093 (bookmark-jump bookmark)
20094 (error "Cannot find location"))))
20096 (defun org-quote-csv-field (s)
20097 "Quote field for inclusion in CSV material."
20098 (if (string-match "[\",]" s)
20099 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20102 (defun org-force-self-insert (N)
20103 "Needed to enforce self-insert under remapping."
20104 (interactive "p")
20105 (self-insert-command N))
20107 (defun org-string-width (s)
20108 "Compute width of string, ignoring invisible characters.
20109 This ignores character with invisibility property `org-link', and also
20110 characters with property `org-cwidth', because these will become invisible
20111 upon the next fontification round."
20112 (let (b l)
20113 (when (or (eq t buffer-invisibility-spec)
20114 (assq 'org-link buffer-invisibility-spec))
20115 (while (setq b (text-property-any 0 (length s)
20116 'invisible 'org-link s))
20117 (setq s (concat (substring s 0 b)
20118 (substring s (or (next-single-property-change
20119 b 'invisible s) (length s)))))))
20120 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20121 (setq s (concat (substring s 0 b)
20122 (substring s (or (next-single-property-change
20123 b 'org-cwidth s) (length s))))))
20124 (setq l (string-width s) b -1)
20125 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20126 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20129 (defun org-shorten-string (s maxlength)
20130 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20131 If the string is shorter or has length MAXLENGTH, just return the
20132 original string. If it is longer, the functions finds a space in the
20133 string, breaks this string off at that locations and adds three dots
20134 as ellipsis. Including the ellipsis, the string will not be longer
20135 than MAXLENGTH. If finding a good breaking point in the string does
20136 not work, the string is just chopped off in the middle of a word
20137 if necessary."
20138 (if (<= (length s) maxlength)
20140 (let* ((n (max (- maxlength 4) 1))
20141 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20142 (if (string-match re s)
20143 (concat (match-string 1 s) "...")
20144 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20146 (defun org-get-indentation (&optional line)
20147 "Get the indentation of the current line, interpreting tabs.
20148 When LINE is given, assume it represents a line and compute its indentation."
20149 (if line
20150 (if (string-match "^ *" (org-remove-tabs line))
20151 (match-end 0))
20152 (save-excursion
20153 (beginning-of-line 1)
20154 (skip-chars-forward " \t")
20155 (current-column))))
20157 (defun org-get-string-indentation (s)
20158 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20159 (let ((n -1) (i 0) (w tab-width) c)
20160 (catch 'exit
20161 (while (< (setq n (1+ n)) (length s))
20162 (setq c (aref s n))
20163 (cond ((= c ?\ ) (setq i (1+ i)))
20164 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20165 (t (throw 'exit t)))))
20168 (defun org-remove-tabs (s &optional width)
20169 "Replace tabulators in S with spaces.
20170 Assumes that s is a single line, starting in column 0."
20171 (setq width (or width tab-width))
20172 (while (string-match "\t" s)
20173 (setq s (replace-match
20174 (make-string
20175 (- (* width (/ (+ (match-beginning 0) width) width))
20176 (match-beginning 0)) ?\ )
20177 t t s)))
20180 (defun org-fix-indentation (line ind)
20181 "Fix indentation in LINE.
20182 IND is a cons cell with target and minimum indentation.
20183 If the current indentation in LINE is smaller than the minimum,
20184 leave it alone. If it is larger than ind, set it to the target."
20185 (let* ((l (org-remove-tabs line))
20186 (i (org-get-indentation l))
20187 (i1 (car ind)) (i2 (cdr ind)))
20188 (if (>= i i2) (setq l (substring line i2)))
20189 (if (> i1 0)
20190 (concat (make-string i1 ?\ ) l)
20191 l)))
20193 (defun org-remove-indentation (code &optional n)
20194 "Remove the maximum common indentation from the lines in CODE.
20195 N may optionally be the number of spaces to remove."
20196 (with-temp-buffer
20197 (insert code)
20198 (org-do-remove-indentation n)
20199 (buffer-string)))
20201 (defun org-do-remove-indentation (&optional n)
20202 "Remove the maximum common indentation from the buffer."
20203 (untabify (point-min) (point-max))
20204 (let ((min 10000) re)
20205 (if n
20206 (setq min n)
20207 (goto-char (point-min))
20208 (while (re-search-forward "^ *[^ \n]" nil t)
20209 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20210 (unless (or (= min 0) (= min 10000))
20211 (setq re (format "^ \\{%d\\}" min))
20212 (goto-char (point-min))
20213 (while (re-search-forward re nil t)
20214 (replace-match "")
20215 (end-of-line 1))
20216 min)))
20218 (defun org-fill-template (template alist)
20219 "Find each %key of ALIST in TEMPLATE and replace it."
20220 (let ((case-fold-search nil)
20221 entry key value)
20222 (setq alist (sort (copy-sequence alist)
20223 (lambda (a b) (< (length (car a)) (length (car b))))))
20224 (while (setq entry (pop alist))
20225 (setq template
20226 (replace-regexp-in-string
20227 (concat "%" (regexp-quote (car entry)))
20228 (or (cdr entry) "") template t t)))
20229 template))
20231 (defun org-base-buffer (buffer)
20232 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20233 (if (not buffer)
20234 buffer
20235 (or (buffer-base-buffer buffer)
20236 buffer)))
20238 (defun org-trim (s)
20239 "Remove whitespace at beginning and end of string."
20240 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20241 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20244 (defun org-wrap (string &optional width lines)
20245 "Wrap string to either a number of lines, or a width in characters.
20246 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20247 that costs. If there is a word longer than WIDTH, the text is actually
20248 wrapped to the length of that word.
20249 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20250 many lines, whatever width that takes.
20251 The return value is a list of lines, without newlines at the end."
20252 (let* ((words (org-split-string string "[ \t\n]+"))
20253 (maxword (apply 'max (mapcar 'org-string-width words)))
20254 w ll)
20255 (cond (width
20256 (org-do-wrap words (max maxword width)))
20257 (lines
20258 (setq w maxword)
20259 (setq ll (org-do-wrap words maxword))
20260 (if (<= (length ll) lines)
20262 (setq ll words)
20263 (while (> (length ll) lines)
20264 (setq w (1+ w))
20265 (setq ll (org-do-wrap words w)))
20266 ll))
20267 (t (error "Cannot wrap this")))))
20269 (defun org-do-wrap (words width)
20270 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20271 (let (lines line)
20272 (while words
20273 (setq line (pop words))
20274 (while (and words (< (+ (length line) (length (car words))) width))
20275 (setq line (concat line " " (pop words))))
20276 (setq lines (push line lines)))
20277 (nreverse lines)))
20279 (defun org-split-string (string &optional separators)
20280 "Splits STRING into substrings at SEPARATORS.
20281 No empty strings are returned if there are matches at the beginning
20282 and end of string."
20283 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20284 (start 0)
20285 notfirst
20286 (list nil))
20287 (while (and (string-match rexp string
20288 (if (and notfirst
20289 (= start (match-beginning 0))
20290 (< start (length string)))
20291 (1+ start) start))
20292 (< (match-beginning 0) (length string)))
20293 (setq notfirst t)
20294 (or (eq (match-beginning 0) 0)
20295 (and (eq (match-beginning 0) (match-end 0))
20296 (eq (match-beginning 0) start))
20297 (setq list
20298 (cons (substring string start (match-beginning 0))
20299 list)))
20300 (setq start (match-end 0)))
20301 (or (eq start (length string))
20302 (setq list
20303 (cons (substring string start)
20304 list)))
20305 (nreverse list)))
20307 (defun org-quote-vert (s)
20308 "Replace \"|\" with \"\\vert\"."
20309 (while (string-match "|" s)
20310 (setq s (replace-match "\\vert" t t s)))
20313 (defun org-uuidgen-p (s)
20314 "Is S an ID created by UUIDGEN?"
20315 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20317 (defun org-in-src-block-p nil
20318 "Whether point is in a code source block."
20319 (let (ov)
20320 (when (setq ov (overlays-at (point)))
20321 (memq 'org-block-background
20322 (overlay-properties
20323 (car ov))))))
20325 (defun org-context ()
20326 "Return a list of contexts of the current cursor position.
20327 If several contexts apply, all are returned.
20328 Each context entry is a list with a symbol naming the context, and
20329 two positions indicating start and end of the context. Possible
20330 contexts are:
20332 :headline anywhere in a headline
20333 :headline-stars on the leading stars in a headline
20334 :todo-keyword on a TODO keyword (including DONE) in a headline
20335 :tags on the TAGS in a headline
20336 :priority on the priority cookie in a headline
20337 :item on the first line of a plain list item
20338 :item-bullet on the bullet/number of a plain list item
20339 :checkbox on the checkbox in a plain list item
20340 :table in an org-mode table
20341 :table-special on a special filed in a table
20342 :table-table in a table.el table
20343 :clocktable in a clocktable
20344 :src-block in a source block
20345 :link on a hyperlink
20346 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20347 :target on a <<target>>
20348 :radio-target on a <<<radio-target>>>
20349 :latex-fragment on a LaTeX fragment
20350 :latex-preview on a LaTeX fragment with overlaid preview image
20352 This function expects the position to be visible because it uses font-lock
20353 faces as a help to recognize the following contexts: :table-special, :link,
20354 and :keyword."
20355 (let* ((f (get-text-property (point) 'face))
20356 (faces (if (listp f) f (list f)))
20357 (case-fold-search t)
20358 (p (point)) clist o)
20359 ;; First the large context
20360 (cond
20361 ((org-at-heading-p t)
20362 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20363 (when (progn
20364 (beginning-of-line 1)
20365 (looking-at org-todo-line-tags-regexp))
20366 (push (org-point-in-group p 1 :headline-stars) clist)
20367 (push (org-point-in-group p 2 :todo-keyword) clist)
20368 (push (org-point-in-group p 4 :tags) clist))
20369 (goto-char p)
20370 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20371 (if (looking-at "\\[#[A-Z0-9]\\]")
20372 (push (org-point-in-group p 0 :priority) clist)))
20374 ((org-at-item-p)
20375 (push (org-point-in-group p 2 :item-bullet) clist)
20376 (push (list :item (point-at-bol)
20377 (save-excursion (org-end-of-item) (point)))
20378 clist)
20379 (and (org-at-item-checkbox-p)
20380 (push (org-point-in-group p 0 :checkbox) clist)))
20382 ((org-at-table-p)
20383 (push (list :table (org-table-begin) (org-table-end)) clist)
20384 (if (memq 'org-formula faces)
20385 (push (list :table-special
20386 (previous-single-property-change p 'face)
20387 (next-single-property-change p 'face)) clist)))
20388 ((org-at-table-p 'any)
20389 (push (list :table-table) clist)))
20390 (goto-char p)
20392 (let ((case-fold-search t))
20393 ;; New the "medium" contexts: clocktables, source blocks
20394 (cond ((org-in-clocktable-p)
20395 (push (list :clocktable
20396 (and (or (looking-at "#\\+BEGIN: clocktable")
20397 (search-backward "#+BEGIN: clocktable" nil t))
20398 (match-beginning 0))
20399 (and (re-search-forward "#\\+END:?" nil t)
20400 (match-end 0))) clist))
20401 ((org-in-src-block-p)
20402 (push (list :src-block
20403 (and (or (looking-at "#\\+BEGIN_SRC")
20404 (search-backward "#+BEGIN_SRC" nil t))
20405 (match-beginning 0))
20406 (and (search-forward "#+END_SRC" nil t)
20407 (match-beginning 0))) clist))))
20408 (goto-char p)
20410 ;; Now the small context
20411 (cond
20412 ((org-at-timestamp-p)
20413 (push (org-point-in-group p 0 :timestamp) clist))
20414 ((memq 'org-link faces)
20415 (push (list :link
20416 (previous-single-property-change p 'face)
20417 (next-single-property-change p 'face)) clist))
20418 ((memq 'org-special-keyword faces)
20419 (push (list :keyword
20420 (previous-single-property-change p 'face)
20421 (next-single-property-change p 'face)) clist))
20422 ((org-at-target-p)
20423 (push (org-point-in-group p 0 :target) clist)
20424 (goto-char (1- (match-beginning 0)))
20425 (if (looking-at org-radio-target-regexp)
20426 (push (org-point-in-group p 0 :radio-target) clist))
20427 (goto-char p))
20428 ((setq o (car (delq nil
20429 (mapcar
20430 (lambda (x)
20431 (if (memq x org-latex-fragment-image-overlays) x))
20432 (overlays-at (point))))))
20433 (push (list :latex-fragment
20434 (overlay-start o) (overlay-end o)) clist)
20435 (push (list :latex-preview
20436 (overlay-start o) (overlay-end o)) clist))
20437 ((org-inside-LaTeX-fragment-p)
20438 ;; FIXME: positions wrong.
20439 (push (list :latex-fragment (point) (point)) clist)))
20441 (setq clist (nreverse (delq nil clist)))
20442 clist))
20444 ;; FIXME: Compare with at-regexp-p Do we need both?
20445 (defun org-in-regexp (re &optional nlines visually)
20446 "Check if point is inside a match of regexp.
20447 Normally only the current line is checked, but you can include NLINES extra
20448 lines both before and after point into the search.
20449 If VISUALLY is set, require that the cursor is not after the match but
20450 really on, so that the block visually is on the match."
20451 (catch 'exit
20452 (let ((pos (point))
20453 (eol (point-at-eol (+ 1 (or nlines 0))))
20454 (inc (if visually 1 0)))
20455 (save-excursion
20456 (beginning-of-line (- 1 (or nlines 0)))
20457 (while (re-search-forward re eol t)
20458 (if (and (<= (match-beginning 0) pos)
20459 (>= (+ inc (match-end 0)) pos))
20460 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20462 (defun org-at-regexp-p (regexp)
20463 "Is point inside a match of REGEXP in the current line?"
20464 (catch 'exit
20465 (save-excursion
20466 (let ((pos (point)) (end (point-at-eol)))
20467 (beginning-of-line 1)
20468 (while (re-search-forward regexp end t)
20469 (if (and (<= (match-beginning 0) pos)
20470 (>= (match-end 0) pos))
20471 (throw 'exit t)))
20472 nil))))
20474 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20475 "Non-nil when point is between matches of START-RE and END-RE.
20477 Also return a non-nil value when point is on one of the matches.
20479 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20480 buffer positions. Default values are the positions of headlines
20481 surrounding the point.
20483 The functions returns a cons cell whose car (resp. cdr) is the
20484 position before START-RE (resp. after END-RE)."
20485 (save-match-data
20486 (let ((pos (point))
20487 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20488 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20489 beg end)
20490 (save-excursion
20491 ;; Point is on a block when on START-RE or if START-RE can be
20492 ;; found before it...
20493 (and (or (org-at-regexp-p start-re)
20494 (re-search-backward start-re limit-up t))
20495 (setq beg (match-beginning 0))
20496 ;; ... and END-RE after it...
20497 (goto-char (match-end 0))
20498 (re-search-forward end-re limit-down t)
20499 (> (setq end (match-end 0)) pos)
20500 ;; ... without another START-RE in-between.
20501 (goto-char (match-beginning 0))
20502 (not (re-search-backward start-re (1+ beg) t))
20503 ;; Return value.
20504 (cons beg end))))))
20506 (defun org-in-block-p (names)
20507 "Non-nil when point belongs to a block whose name belongs to NAMES.
20509 NAMES is a list of strings containing names of blocks.
20511 Return first block name matched, or nil. Beware that in case of
20512 nested blocks, the returned name may not belong to the closest
20513 block from point."
20514 (save-match-data
20515 (catch 'exit
20516 (let ((case-fold-search t)
20517 (lim-up (save-excursion (outline-previous-heading)))
20518 (lim-down (save-excursion (outline-next-heading))))
20519 (mapc (lambda (name)
20520 (let ((n (regexp-quote name)))
20521 (when (org-between-regexps-p
20522 (concat "^[ \t]*#\\+begin_" n)
20523 (concat "^[ \t]*#\\+end_" n)
20524 lim-up lim-down)
20525 (throw 'exit n))))
20526 names))
20527 nil)))
20529 (defun org-occur-in-agenda-files (regexp &optional nlines)
20530 "Call `multi-occur' with buffers for all agenda files."
20531 (interactive "sOrg-files matching: \np")
20532 (let* ((files (org-agenda-files))
20533 (tnames (mapcar 'file-truename files))
20534 (extra org-agenda-text-search-extra-files)
20536 (when (eq (car extra) 'agenda-archives)
20537 (setq extra (cdr extra))
20538 (setq files (org-add-archive-files files)))
20539 (while (setq f (pop extra))
20540 (unless (member (file-truename f) tnames)
20541 (add-to-list 'files f 'append)
20542 (add-to-list 'tnames (file-truename f) 'append)))
20543 (multi-occur
20544 (mapcar (lambda (x)
20545 (with-current-buffer
20546 (or (get-file-buffer x) (find-file-noselect x))
20547 (widen)
20548 (current-buffer)))
20549 files)
20550 regexp)))
20552 (if (boundp 'occur-mode-find-occurrence-hook)
20553 ;; Emacs 23
20554 (add-hook 'occur-mode-find-occurrence-hook
20555 (lambda ()
20556 (when (derived-mode-p 'org-mode)
20557 (org-reveal))))
20558 ;; Emacs 22
20559 (defadvice occur-mode-goto-occurrence
20560 (after org-occur-reveal activate)
20561 (and (derived-mode-p 'org-mode) (org-reveal)))
20562 (defadvice occur-mode-goto-occurrence-other-window
20563 (after org-occur-reveal activate)
20564 (and (derived-mode-p 'org-mode) (org-reveal)))
20565 (defadvice occur-mode-display-occurrence
20566 (after org-occur-reveal activate)
20567 (when (derived-mode-p 'org-mode)
20568 (let ((pos (occur-mode-find-occurrence)))
20569 (with-current-buffer (marker-buffer pos)
20570 (save-excursion
20571 (goto-char pos)
20572 (org-reveal)))))))
20574 (defun org-occur-link-in-agenda-files ()
20575 "Create a link and search for it in the agendas.
20576 The link is not stored in `org-stored-links', it is just created
20577 for the search purpose."
20578 (interactive)
20579 (let ((link (condition-case nil
20580 (org-store-link nil)
20581 (error "Unable to create a link to here"))))
20582 (org-occur-in-agenda-files (regexp-quote link))))
20584 (defun org-uniquify (list)
20585 "Remove duplicate elements from LIST."
20586 (let (res)
20587 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20588 res))
20590 (defun org-delete-all (elts list)
20591 "Remove all elements in ELTS from LIST."
20592 (while elts
20593 (setq list (delete (pop elts) list)))
20594 list)
20596 (defun org-count (cl-item cl-seq)
20597 "Count the number of occurrences of ITEM in SEQ.
20598 Taken from `count' in cl-seq.el with all keyword arguments removed."
20599 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20600 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20601 (while (< cl-start cl-end)
20602 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20603 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20604 (setq cl-start (1+ cl-start)))
20605 cl-count))
20607 (defun org-remove-if (predicate seq)
20608 "Remove everything from SEQ that fulfills PREDICATE."
20609 (let (res e)
20610 (while seq
20611 (setq e (pop seq))
20612 (if (not (funcall predicate e)) (push e res)))
20613 (nreverse res)))
20615 (defun org-remove-if-not (predicate seq)
20616 "Remove everything from SEQ that does not fulfill PREDICATE."
20617 (let (res e)
20618 (while seq
20619 (setq e (pop seq))
20620 (if (funcall predicate e) (push e res)))
20621 (nreverse res)))
20623 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20624 "Reduce two-argument FUNCTION across SEQ.
20625 Taken from `reduce' in cl-seq.el with all keyword arguments but
20626 \":initial-value\" removed."
20627 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20628 (cadr (memq :initial-value cl-keys)))
20629 (cl-seq (pop cl-seq))
20630 (t (funcall cl-func)))))
20631 (while cl-seq
20632 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20633 cl-accum))
20635 (defun org-back-over-empty-lines ()
20636 "Move backwards over whitespace, to the beginning of the first empty line.
20637 Returns the number of empty lines passed."
20638 (let ((pos (point)))
20639 (if (cdr (assoc 'heading org-blank-before-new-entry))
20640 (skip-chars-backward " \t\n\r")
20641 (unless (eobp)
20642 (forward-line -1)))
20643 (beginning-of-line 2)
20644 (goto-char (min (point) pos))
20645 (count-lines (point) pos)))
20647 (defun org-skip-whitespace ()
20648 (skip-chars-forward " \t\n\r"))
20650 (defun org-point-in-group (point group &optional context)
20651 "Check if POINT is in match-group GROUP.
20652 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20653 match. If the match group does not exist or point is not inside it,
20654 return nil."
20655 (and (match-beginning group)
20656 (>= point (match-beginning group))
20657 (<= point (match-end group))
20658 (if context
20659 (list context (match-beginning group) (match-end group))
20660 t)))
20662 (defun org-switch-to-buffer-other-window (&rest args)
20663 "Switch to buffer in a second window on the current frame.
20664 In particular, do not allow pop-up frames.
20665 Returns the newly created buffer."
20666 (let (pop-up-frames special-display-buffer-names special-display-regexps
20667 special-display-function)
20668 (apply 'switch-to-buffer-other-window args)))
20670 (defun org-combine-plists (&rest plists)
20671 "Create a single property list from all plists in PLISTS.
20672 The process starts by copying the first list, and then setting properties
20673 from the other lists. Settings in the last list are the most significant
20674 ones and overrule settings in the other lists."
20675 (let ((rtn (copy-sequence (pop plists)))
20676 p v ls)
20677 (while plists
20678 (setq ls (pop plists))
20679 (while ls
20680 (setq p (pop ls) v (pop ls))
20681 (setq rtn (plist-put rtn p v))))
20682 rtn))
20684 (defun org-replace-escapes (string table)
20685 "Replace %-escapes in STRING with values in TABLE.
20686 TABLE is an association list with keys like \"%a\" and string values.
20687 The sequences in STRING may contain normal field width and padding information,
20688 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20689 so values can contain further %-escapes if they are define later in TABLE."
20690 (let ((tbl (copy-alist table))
20691 (case-fold-search nil)
20692 (pchg 0)
20693 e re rpl)
20694 (while (setq e (pop tbl))
20695 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20696 (when (and (cdr e) (string-match re (cdr e)))
20697 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20698 (safe "SREF"))
20699 (add-text-properties 0 3 (list 'sref sref) safe)
20700 (setcdr e (replace-match safe t t (cdr e)))))
20701 (while (string-match re string)
20702 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20703 (cdr e)))
20704 (setq string (replace-match rpl t t string))))
20705 (while (setq pchg (next-property-change pchg string))
20706 (let ((sref (get-text-property pchg 'sref string)))
20707 (when (and sref (string-match "SREF" string pchg))
20708 (setq string (replace-match sref t t string)))))
20709 string))
20711 (defun org-sublist (list start end)
20712 "Return a section of LIST, from START to END.
20713 Counting starts at 1."
20714 (let (rtn (c start))
20715 (setq list (nthcdr (1- start) list))
20716 (while (and list (<= c end))
20717 (push (pop list) rtn)
20718 (setq c (1+ c)))
20719 (nreverse rtn)))
20721 (defun org-find-base-buffer-visiting (file)
20722 "Like `find-buffer-visiting' but always return the base buffer and
20723 not an indirect buffer."
20724 (let ((buf (or (get-file-buffer file)
20725 (find-buffer-visiting file))))
20726 (if buf
20727 (or (buffer-base-buffer buf) buf)
20728 nil)))
20730 (defun org-image-file-name-regexp (&optional extensions)
20731 "Return regexp matching the file names of images.
20732 If EXTENSIONS is given, only match these."
20733 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20734 (image-file-name-regexp)
20735 (let ((image-file-name-extensions
20736 (or extensions
20737 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20738 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20739 (concat "\\."
20740 (regexp-opt (nconc (mapcar 'upcase
20741 image-file-name-extensions)
20742 image-file-name-extensions)
20744 "\\'"))))
20746 (defun org-file-image-p (file &optional extensions)
20747 "Return non-nil if FILE is an image."
20748 (save-match-data
20749 (string-match (org-image-file-name-regexp extensions) file)))
20751 (defun org-get-cursor-date ()
20752 "Return the date at cursor in as a time.
20753 This works in the calendar and in the agenda, anywhere else it just
20754 returns the current time."
20755 (let (date day defd)
20756 (cond
20757 ((eq major-mode 'calendar-mode)
20758 (setq date (calendar-cursor-to-date)
20759 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20760 ((eq major-mode 'org-agenda-mode)
20761 (setq day (get-text-property (point) 'day))
20762 (if day
20763 (setq date (calendar-gregorian-from-absolute day)
20764 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20765 (nth 2 date))))))
20766 (or defd (current-time))))
20768 (defvar org-agenda-action-marker (make-marker)
20769 "Marker pointing to the entry for the next agenda action.")
20771 (defun org-mark-entry-for-agenda-action ()
20772 "Mark the current entry as target of an agenda action.
20773 Agenda actions are actions executed from the agenda with the key `k',
20774 which make use of the date at the cursor."
20775 (interactive)
20776 (move-marker org-agenda-action-marker
20777 (save-excursion (org-back-to-heading t) (point))
20778 (current-buffer))
20779 (message
20780 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20782 (defun org-mark-subtree (&optional up)
20783 "Mark the current subtree.
20784 This puts point at the start of the current subtree, and mark at
20785 the end. If a numeric prefix UP is given, move up into the
20786 hierarchy of headlines by UP levels before marking the subtree."
20787 (interactive "P")
20788 (org-with-limited-levels
20789 (cond ((org-at-heading-p) (beginning-of-line))
20790 ((org-before-first-heading-p) (error "Not in a subtree"))
20791 (t (outline-previous-visible-heading 1))))
20792 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20793 (if (org-called-interactively-p 'any)
20794 (call-interactively 'org-mark-element)
20795 (org-mark-element)))
20797 ;;; Indentation
20799 (defun org-indent-line ()
20800 "Indent line depending on context."
20801 (interactive)
20802 (let* ((pos (point))
20803 (itemp (org-at-item-p))
20804 (case-fold-search t)
20805 (org-drawer-regexp (or org-drawer-regexp "\000"))
20806 (inline-task-p (and (featurep 'org-inlinetask)
20807 (org-inlinetask-in-task-p)))
20808 (inline-re (and inline-task-p
20809 (org-inlinetask-outline-regexp)))
20810 column)
20811 (if (and orgstruct-is-++ (eq pos (point)))
20812 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20813 (indent-according-to-mode))
20814 (beginning-of-line 1)
20815 (cond
20816 ;; Headings
20817 ((looking-at org-outline-regexp) (setq column 0))
20818 ;; Included files
20819 ((looking-at "#\\+include:") (setq column 0))
20820 ;; Footnote definition
20821 ((looking-at org-footnote-definition-re) (setq column 0))
20822 ;; Literal examples
20823 ((looking-at "[ \t]*:\\( \\|$\\)")
20824 (setq column (org-get-indentation))) ; do nothing
20825 ;; Lists
20826 ((ignore-errors (goto-char (org-in-item-p)))
20827 (setq column (if itemp
20828 (org-get-indentation)
20829 (org-list-item-body-column (point))))
20830 (goto-char pos))
20831 ;; Drawers
20832 ((and (looking-at "[ \t]*:END:")
20833 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20834 (save-excursion
20835 (goto-char (1- (match-beginning 1)))
20836 (setq column (current-column))))
20837 ;; Special blocks
20838 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20839 (save-excursion
20840 (re-search-backward
20841 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20842 (setq column (org-get-indentation (match-string 0))))
20843 ((and (not (looking-at "[ \t]*#\\+begin_"))
20844 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20845 (save-excursion
20846 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20847 (setq column
20848 (cond ((equal (downcase (match-string 1)) "src")
20849 ;; src blocks: let `org-edit-src-exit' handle them
20850 (org-get-indentation))
20851 ((equal (downcase (match-string 1)) "example")
20852 (max (org-get-indentation)
20853 (org-get-indentation (match-string 0))))
20855 (org-get-indentation (match-string 0))))))
20856 ;; This line has nothing special, look at the previous relevant
20857 ;; line to compute indentation
20859 (beginning-of-line 0)
20860 (while (and (not (bobp))
20861 (not (looking-at org-drawer-regexp))
20862 ;; When point started in an inline task, do not move
20863 ;; above task starting line.
20864 (not (and inline-task-p (looking-at inline-re)))
20865 ;; Skip drawers, blocks, empty lines, verbatim,
20866 ;; comments, tables, footnotes definitions, lists,
20867 ;; inline tasks.
20868 (or (and (looking-at "[ \t]*:END:")
20869 (re-search-backward org-drawer-regexp nil t))
20870 (and (looking-at "[ \t]*#\\+end_")
20871 (re-search-backward "[ \t]*#\\+begin_"nil t))
20872 (looking-at "[ \t]*[\n:#|]")
20873 (looking-at org-footnote-definition-re)
20874 (and (ignore-errors (goto-char (org-in-item-p)))
20875 (goto-char
20876 (org-list-get-top-point (org-list-struct))))
20877 (and (not inline-task-p)
20878 (featurep 'org-inlinetask)
20879 (org-inlinetask-in-task-p)
20880 (or (org-inlinetask-goto-beginning) t))))
20881 (beginning-of-line 0))
20882 (cond
20883 ;; There was an heading above.
20884 ((looking-at "\\*+[ \t]+")
20885 (if (not org-adapt-indentation)
20886 (setq column 0)
20887 (goto-char (match-end 0))
20888 (setq column (current-column))))
20889 ;; A drawer had started and is unfinished
20890 ((looking-at org-drawer-regexp)
20891 (goto-char (1- (match-beginning 1)))
20892 (setq column (current-column)))
20893 ;; Else, nothing noticeable found: get indentation and go on.
20894 (t (setq column (org-get-indentation))))))
20895 ;; Now apply indentation and move cursor accordingly
20896 (goto-char pos)
20897 (if (<= (current-column) (current-indentation))
20898 (org-indent-line-to column)
20899 (save-excursion (org-indent-line-to column)))
20900 ;; Special polishing for properties, see `org-property-format'
20901 (setq column (current-column))
20902 (beginning-of-line 1)
20903 (if (looking-at
20904 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20905 (replace-match (concat (match-string 1)
20906 (format org-property-format
20907 (match-string 2) (match-string 3)))
20908 t t))
20909 (org-move-to-column column))))
20911 (defun org-indent-drawer ()
20912 "Indent the drawer at point."
20913 (interactive)
20914 (let ((p (point))
20915 (e (and (save-excursion (re-search-forward ":END:" nil t))
20916 (match-end 0)))
20917 (folded
20918 (save-excursion
20919 (end-of-line)
20920 (when (overlays-at (point))
20921 (member 'invisible (overlay-properties
20922 (car (overlays-at (point)))))))))
20923 (when folded (org-cycle))
20924 (indent-for-tab-command)
20925 (while (and (move-beginning-of-line 2) (< (point) e))
20926 (indent-for-tab-command))
20927 (goto-char p)
20928 (when folded (org-cycle)))
20929 (message "Drawer at point indented"))
20931 (defun org-indent-block ()
20932 "Indent the block at point."
20933 (interactive)
20934 (let ((p (point))
20935 (case-fold-search t)
20936 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20937 (match-end 0)))
20938 (folded
20939 (save-excursion
20940 (end-of-line)
20941 (when (overlays-at (point))
20942 (member 'invisible (overlay-properties
20943 (car (overlays-at (point)))))))))
20944 (when folded (org-cycle))
20945 (indent-for-tab-command)
20946 (while (and (move-beginning-of-line 2) (< (point) e))
20947 (indent-for-tab-command))
20948 (goto-char p)
20949 (when folded (org-cycle)))
20950 (message "Block at point indented"))
20952 (defun org-indent-region (start end)
20953 "Indent region."
20954 (interactive "r")
20955 (save-excursion
20956 (let ((line-end (org-current-line end)))
20957 (goto-char start)
20958 (while (< (org-current-line) line-end)
20959 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20960 (t (call-interactively 'org-indent-line)))
20961 (move-beginning-of-line 2)))))
20964 ;;; Filling
20966 ;; We use our own fill-paragraph and auto-fill functions.
20968 ;; `org-fill-paragraph' relies on adaptive filling and context
20969 ;; checking. Appropriate `fill-prefix' is computed with
20970 ;; `org-adaptive-fill-function'.
20972 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20973 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20974 ;; `org-adaptive-fill-function' value. Internally,
20975 ;; `org-comment-line-break-function' breaks the line.
20977 ;; `org-setup-filling' installs filling and auto-filling related
20978 ;; variables during `org-mode' initialization.
20980 (defun org-setup-filling ()
20981 (interactive)
20982 ;; Prevent auto-fill from inserting unwanted new items.
20983 (when (boundp 'fill-nobreak-predicate)
20984 (org-set-local
20985 'fill-nobreak-predicate
20986 (org-uniquify
20987 (append fill-nobreak-predicate
20988 '(org-fill-paragraph-separate-nobreak-p
20989 org-fill-line-break-nobreak-p)))))
20990 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20991 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20992 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20993 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20995 (defvar org-element-paragraph-separate) ; org-element.el
20996 (defun org-fill-paragraph-separate-nobreak-p ()
20997 "Non-nil when a line break at point would insert a new item."
20998 (looking-at (substring org-element-paragraph-separate 1)))
21000 (defun org-fill-line-break-nobreak-p ()
21001 "Non-nil when a line break at point would create an Org line break."
21002 (save-excursion
21003 (skip-chars-backward "[ \t]")
21004 (skip-chars-backward "\\\\")
21005 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21007 (declare-function message-in-body-p "message" ())
21008 (defvar org-element--affiliated-re) ; From org-element.el
21009 (defun org-adaptive-fill-function ()
21010 "Compute a fill prefix for the current line.
21011 Return fill prefix, as a string, or nil if current line isn't
21012 meant to be filled."
21013 (org-with-wide-buffer
21014 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21015 ;; FIXME: This is really the job of orgstruct++-mode
21016 (let* ((p (line-beginning-position))
21017 (element (save-excursion (beginning-of-line)
21018 (org-element-at-point)))
21019 (type (org-element-type element))
21020 (post-affiliated
21021 (save-excursion
21022 (goto-char (org-element-property :begin element))
21023 (while (looking-at org-element--affiliated-re) (forward-line))
21024 (point))))
21025 (unless (< p post-affiliated)
21026 (case type
21027 (comment (looking-at "[ \t]*# ?") (match-string 0))
21028 (footnote-definition "")
21029 ((item plain-list)
21030 (make-string (org-list-item-body-column post-affiliated) ? ))
21031 (paragraph
21032 ;; Fill prefix is usually the same as the current line,
21033 ;; except if the paragraph is at the beginning of an item.
21034 (let ((parent (org-element-property :parent element)))
21035 (cond ((eq (org-element-type parent) 'item)
21036 (make-string (org-list-item-body-column
21037 (org-element-property :begin parent))
21038 ? ))
21039 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21040 (match-string 0))
21041 (t ""))))
21042 (comment-block
21043 ;; Only fill contents if P is within block boundaries.
21044 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21045 (forward-line)
21046 (point)))
21047 (cend (save-excursion
21048 (goto-char (org-element-property :end element))
21049 (skip-chars-backward " \r\t\n")
21050 (line-beginning-position))))
21051 (when (and (>= p cbeg) (< p cend))
21052 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21053 (match-string 0)
21054 ""))))))))))
21056 (declare-function message-goto-body "message" ())
21057 (defvar message-cite-prefix-regexp) ; From message.el
21058 (defvar org-element-all-objects) ; From org-element.el
21059 (defun org-fill-paragraph (&optional justify)
21060 "Fill element at point, when applicable.
21062 This function only applies to comment blocks, comments, example
21063 blocks and paragraphs. Also, as a special case, re-align table
21064 when point is at one.
21066 If JUSTIFY is non-nil (interactively, with prefix argument),
21067 justify as well. If `sentence-end-double-space' is non-nil, then
21068 period followed by one space does not end a sentence, so don't
21069 break a line there. The variable `fill-column' controls the
21070 width for filling.
21072 For convenience, when point is at a plain list, an item or
21073 a footnote definition, try to fill the first paragraph within."
21074 ;; Falls back on message-fill-paragraph when necessary
21075 (interactive)
21076 (if (and (derived-mode-p 'message-mode)
21077 (or (not (message-in-body-p))
21078 (save-excursion (move-beginning-of-line 1)
21079 (looking-at message-cite-prefix-regexp))))
21080 (let ((fill-paragraph-function
21081 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21082 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21083 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21084 (paragraph-separate
21085 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21086 (fill-paragraph nil))
21087 (save-excursion
21088 ;; Move to end of line in order to get the first paragraph
21089 ;; within a plain list or a footnote definition.
21090 (end-of-line)
21091 (let ((element (org-element-at-point)))
21092 ;; First check if point is in a blank line at the beginning of
21093 ;; the buffer. In that case, ignore filling.
21094 (if (< (point) (org-element-property :begin element)) t
21095 (case (org-element-type element)
21096 ;; Align Org tables, leave table.el tables as-is.
21097 (table-row (org-table-align) t)
21098 (table
21099 (when (eq (org-element-property :type element) 'org)
21100 (org-table-align))
21102 (paragraph
21103 ;; Paragraphs may contain `line-break' type objects.
21104 (let ((beg (max (point-min)
21105 (org-element-property :contents-begin element)))
21106 (end (min (point-max)
21107 (org-element-property :contents-end element))))
21108 ;; Do nothing if point is at an affiliated keyword.
21109 (if (< (point) beg) t
21110 (when (derived-mode-p 'message-mode)
21111 ;; In `message-mode', do not fill following
21112 ;; citation in current paragraph nor text before
21113 ;; message body.
21114 (let ((body-start (save-excursion (message-goto-body))))
21115 (when body-start (setq beg (max body-start beg))))
21116 (when (save-excursion
21117 (re-search-forward
21118 (concat "^" message-cite-prefix-regexp) end t))
21119 (setq end (match-beginning 0))))
21120 ;; Fill paragraph, taking line breaks into
21121 ;; consideration. For that, slice the paragraph
21122 ;; using line breaks as separators, and fill the
21123 ;; parts in reverse order to avoid messing with
21124 ;; markers.
21125 (save-excursion
21126 (goto-char end)
21127 (mapc
21128 (lambda (pos)
21129 (fill-region-as-paragraph pos (point) justify)
21130 (goto-char pos))
21131 ;; Find the list of ending positions for line
21132 ;; breaks in the current paragraph. Add paragraph
21133 ;; beginning to include first slice.
21134 (nreverse
21135 (cons
21137 (org-element-map
21138 (org-element--parse-objects
21139 beg end nil org-element-all-objects)
21140 'line-break
21141 (lambda (lb) (org-element-property :end lb)))))))
21142 t)))
21143 ;; Contents of `comment-block' type elements should be
21144 ;; filled as plain text, but only if point is within block
21145 ;; markers.
21146 (comment-block
21147 (let* ((case-fold-search t)
21148 (beg (save-excursion
21149 (goto-char (org-element-property :begin element))
21150 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21151 (forward-line)
21152 (point)))
21153 (end (save-excursion
21154 (goto-char (org-element-property :end element))
21155 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21156 (line-beginning-position))))
21157 (when (and (>= (point) beg) (< (point) end))
21158 (fill-region-as-paragraph
21159 (save-excursion
21160 (end-of-line)
21161 (re-search-backward "^[ \t]*$" beg 'move)
21162 (line-beginning-position))
21163 (save-excursion
21164 (beginning-of-line)
21165 (re-search-forward "^[ \t]*$" end 'move)
21166 (line-beginning-position))
21167 justify)))
21169 ;; Fill comments.
21170 (comment (fill-comment-paragraph justify))
21171 ;; Ignore every other element.
21172 (otherwise t)))))))
21174 (defun org-auto-fill-function ()
21175 "Auto-fill function."
21176 ;; Check if auto-filling is meaningful.
21177 (let ((fc (current-fill-column)))
21178 (when (and fc (> (current-column) fc))
21179 (let ((fill-prefix (org-adaptive-fill-function)))
21180 (when fill-prefix (do-auto-fill))))))
21182 (defun org-comment-line-break-function (&optional soft)
21183 "Break line at point and indent, continuing comment if within one.
21184 The inserted newline is marked hard if variable
21185 `use-hard-newlines' is true, unless optional argument SOFT is
21186 non-nil."
21187 (if soft (insert-and-inherit ?\n) (newline 1))
21188 (save-excursion (forward-char -1) (delete-horizontal-space))
21189 (delete-horizontal-space)
21190 (indent-to-left-margin)
21191 (insert-before-markers-and-inherit fill-prefix))
21194 ;;; Comments
21196 ;; Org comments syntax is quite complex. It requires the entire line
21197 ;; to be just a comment. Also, even with the right syntax at the
21198 ;; beginning of line, some some elements (i.e. verse-block or
21199 ;; example-block) don't accept comments. Usual Emacs comment commands
21200 ;; cannot cope with those requirements. Therefore, Org replaces them.
21202 ;; Org still relies on `comment-dwim', but cannot trust
21203 ;; `comment-only-p'. So, `comment-region-function' and
21204 ;; `uncomment-region-function' both point
21205 ;; to`org-comment-or-uncomment-region'. Eventually,
21206 ;; `org-insert-comment' takes care of insertion of comments at the
21207 ;; beginning of line.
21209 ;; `org-setup-comments-handling' install comments related variables
21210 ;; during `org-mode' initialization.
21212 (defun org-setup-comments-handling ()
21213 (interactive)
21214 (org-set-local 'comment-use-syntax nil)
21215 (org-set-local 'comment-start "# ")
21216 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21217 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21218 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21219 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21221 (defun org-insert-comment ()
21222 "Insert an empty comment above current line.
21223 If the line is empty, insert comment at its beginning."
21224 (beginning-of-line)
21225 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21226 (org-indent-line)
21227 (insert "# "))
21229 (defvar comment-empty-lines) ; From newcomment.el.
21230 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21231 "Comment or uncomment each non-blank line in the region.
21232 Uncomment each non-blank line between BEG and END if it only
21233 contains commented lines. Otherwise, comment them."
21234 (save-restriction
21235 ;; Restrict region
21236 (narrow-to-region (save-excursion (goto-char beg)
21237 (skip-chars-forward " \r\t\n" end)
21238 (line-beginning-position))
21239 (save-excursion (goto-char end)
21240 (skip-chars-backward " \r\t\n" beg)
21241 (line-end-position)))
21242 (let ((uncommentp
21243 ;; UNCOMMENTP is non-nil when every non blank line between
21244 ;; BEG and END is a comment.
21245 (save-excursion
21246 (goto-char (point-min))
21247 (while (and (not (eobp))
21248 (let ((element (org-element-at-point)))
21249 (and (eq (org-element-type element) 'comment)
21250 (goto-char (min (point-max)
21251 (org-element-property
21252 :end element)))))))
21253 (eobp))))
21254 (if uncommentp
21255 ;; Only blank lines and comments in region: uncomment it.
21256 (save-excursion
21257 (goto-char (point-min))
21258 (while (not (eobp))
21259 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21260 (replace-match "" nil nil nil 1))
21261 (forward-line)))
21262 ;; Comment each line in region.
21263 (let ((min-indent (point-max)))
21264 ;; First find the minimum indentation across all lines.
21265 (save-excursion
21266 (goto-char (point-min))
21267 (while (and (not (eobp)) (not (zerop min-indent)))
21268 (unless (looking-at "[ \t]*$")
21269 (setq min-indent (min min-indent (current-indentation))))
21270 (forward-line)))
21271 ;; Then loop over all lines.
21272 (save-excursion
21273 (goto-char (point-min))
21274 (while (not (eobp))
21275 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21276 (org-move-to-column min-indent t)
21277 (insert comment-start))
21278 (forward-line))))))))
21281 ;;; Other stuff.
21283 (defun org-toggle-fixed-width-section (arg)
21284 "Toggle the fixed-width export.
21285 If there is no active region, the QUOTE keyword at the current headline is
21286 inserted or removed. When present, it causes the text between this headline
21287 and the next to be exported as fixed-width text, and unmodified.
21288 If there is an active region, this command adds or removes a colon as the
21289 first character of this line. If the first character of a line is a colon,
21290 this line is also exported in fixed-width font."
21291 (interactive "P")
21292 (let* ((cc 0)
21293 (regionp (org-region-active-p))
21294 (beg (if regionp (region-beginning) (point)))
21295 (end (if regionp (region-end)))
21296 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21297 (case-fold-search nil)
21298 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21299 off)
21300 (if regionp
21301 (save-excursion
21302 (goto-char beg)
21303 (setq cc (current-column))
21304 (beginning-of-line 1)
21305 (setq off (looking-at re))
21306 (while (> nlines 0)
21307 (setq nlines (1- nlines))
21308 (beginning-of-line 1)
21309 (cond
21310 (arg
21311 (org-move-to-column cc t)
21312 (insert ": \n")
21313 (forward-line -1))
21314 ((and off (looking-at re))
21315 (replace-match "" t t nil 1))
21316 ((not off) (org-move-to-column cc t) (insert ": ")))
21317 (forward-line 1)))
21318 (save-excursion
21319 (org-back-to-heading)
21320 (cond
21321 ((looking-at (format org-heading-keyword-regexp-format
21322 org-quote-string))
21323 (goto-char (match-end 1))
21324 (looking-at (concat " +" org-quote-string))
21325 (replace-match "" t t)
21326 (when (eolp) (insert " ")))
21327 ((looking-at org-outline-regexp)
21328 (goto-char (match-end 0))
21329 (insert org-quote-string " ")))))))
21331 (defun org-reftex-citation ()
21332 "Use reftex-citation to insert a citation into the buffer.
21333 This looks for a line like
21335 #+BIBLIOGRAPHY: foo plain option:-d
21337 and derives from it that foo.bib is the bibliography file relevant
21338 for this document. It then installs the necessary environment for RefTeX
21339 to work in this buffer and calls `reftex-citation' to insert a citation
21340 into the buffer.
21342 Export of such citations to both LaTeX and HTML is handled by the contributed
21343 package org-exp-bibtex by Taru Karttunen."
21344 (interactive)
21345 (let ((reftex-docstruct-symbol 'rds)
21346 (reftex-cite-format "\\cite{%l}")
21347 rds bib)
21348 (save-excursion
21349 (save-restriction
21350 (widen)
21351 (let ((case-fold-search t)
21352 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21353 (if (not (save-excursion
21354 (or (re-search-forward re nil t)
21355 (re-search-backward re nil t))))
21356 (error "No bibliography defined in file")
21357 (setq bib (concat (match-string 1) ".bib")
21358 rds (list (list 'bib bib)))))))
21359 (call-interactively 'reftex-citation)))
21361 ;;;; Functions extending outline functionality
21363 (defun org-beginning-of-line (&optional arg)
21364 "Go to the beginning of the current line. If that is invisible, continue
21365 to a visible line beginning. This makes the function of C-a more intuitive.
21366 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21367 first attempt, and only move to after the tags when the cursor is already
21368 beyond the end of the headline."
21369 (interactive "P")
21370 (let ((pos (point))
21371 (special (if (consp org-special-ctrl-a/e)
21372 (car org-special-ctrl-a/e)
21373 org-special-ctrl-a/e))
21374 refpos)
21375 (if (org-bound-and-true-p line-move-visual)
21376 (beginning-of-visual-line 1)
21377 (beginning-of-line 1))
21378 (if (and arg (fboundp 'move-beginning-of-line))
21379 (call-interactively 'move-beginning-of-line)
21380 (if (bobp)
21382 (backward-char 1)
21383 (if (org-truely-invisible-p)
21384 (while (and (not (bobp)) (org-truely-invisible-p))
21385 (backward-char 1)
21386 (beginning-of-line 1))
21387 (forward-char 1))))
21388 (when special
21389 (cond
21390 ((and (looking-at org-complex-heading-regexp)
21391 (= (char-after (match-end 1)) ?\ ))
21392 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21393 (point-at-eol)))
21394 (goto-char
21395 (if (eq special t)
21396 (cond ((> pos refpos) refpos)
21397 ((= pos (point)) refpos)
21398 (t (point)))
21399 (cond ((> pos (point)) (point))
21400 ((not (eq last-command this-command)) (point))
21401 (t refpos)))))
21402 ((org-at-item-p)
21403 ;; Being at an item and not looking at an the item means point
21404 ;; was previously moved to beginning of a visual line, which
21405 ;; doesn't contain the item. Therefore, do nothing special,
21406 ;; just stay here.
21407 (when (looking-at org-list-full-item-re)
21408 ;; Set special position at first white space character after
21409 ;; bullet, and check-box, if any.
21410 (let ((after-bullet
21411 (let ((box (match-end 3)))
21412 (if (not box) (match-end 1)
21413 (let ((after (char-after box)))
21414 (if (and after (= after ? )) (1+ box) box))))))
21415 ;; Special case: Move point to special position when
21416 ;; currently after it or at beginning of line.
21417 (if (eq special t)
21418 (when (or (> pos after-bullet) (= (point) pos))
21419 (goto-char after-bullet))
21420 ;; Reversed case: Move point to special position when
21421 ;; point was already at beginning of line and command is
21422 ;; repeated.
21423 (when (and (= (point) pos) (eq last-command this-command))
21424 (goto-char after-bullet))))))))
21425 (org-no-warnings
21426 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21428 (defun org-end-of-line (&optional arg)
21429 "Go to the end of the line.
21430 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21431 first attempt, and only move to after the tags when the cursor is already
21432 beyond the end of the headline."
21433 (interactive "P")
21434 (let ((special (if (consp org-special-ctrl-a/e)
21435 (cdr org-special-ctrl-a/e)
21436 org-special-ctrl-a/e)))
21437 (cond
21438 ((or (not special) arg
21439 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21440 (call-interactively
21441 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21442 ((fboundp 'move-end-of-line) 'move-end-of-line)
21443 (t 'end-of-line))))
21444 ((org-at-heading-p)
21445 (let ((pos (point)))
21446 (beginning-of-line 1)
21447 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21448 (if (eq special t)
21449 (if (or (< pos (match-beginning 1))
21450 (= pos (match-end 0)))
21451 (goto-char (match-beginning 1))
21452 (goto-char (match-end 0)))
21453 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21454 (goto-char (match-end 0))
21455 (goto-char (match-beginning 1))))
21456 (call-interactively (if (fboundp 'move-end-of-line)
21457 'move-end-of-line
21458 'end-of-line)))))
21459 ((org-at-drawer-p)
21460 (move-end-of-line 1)
21461 (when (overlays-at (1- (point))) (backward-char 1)))
21462 ;; At an item: Move before any hidden text.
21463 (t (call-interactively
21464 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21465 ((fboundp 'move-end-of-line) 'move-end-of-line)
21466 (t 'end-of-line)))))
21467 (org-no-warnings
21468 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21470 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21471 (define-key org-mode-map "\C-e" 'org-end-of-line)
21473 (defun org-backward-sentence (&optional arg)
21474 "Go to beginning of sentence, or beginning of table field.
21475 This will call `backward-sentence' or `org-table-beginning-of-field',
21476 depending on context."
21477 (interactive "P")
21478 (cond
21479 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21480 (t (call-interactively 'backward-sentence))))
21482 (defun org-forward-sentence (&optional arg)
21483 "Go to end of sentence, or end of table field.
21484 This will call `forward-sentence' or `org-table-end-of-field',
21485 depending on context."
21486 (interactive "P")
21487 (cond
21488 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21489 (t (call-interactively 'forward-sentence))))
21491 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21492 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21494 (defun org-kill-line (&optional arg)
21495 "Kill line, to tags or end of line."
21496 (interactive "P")
21497 (cond
21498 ((or (not org-special-ctrl-k)
21499 (bolp)
21500 (not (org-at-heading-p)))
21501 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21502 org-ctrl-k-protect-subtree)
21503 (if (or (eq org-ctrl-k-protect-subtree 'error)
21504 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21505 (error "C-k aborted - would kill hidden subtree")))
21506 (call-interactively
21507 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21508 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21509 (kill-region (point) (match-beginning 1))
21510 (org-set-tags nil t))
21511 (t (kill-region (point) (point-at-eol)))))
21513 (define-key org-mode-map "\C-k" 'org-kill-line)
21515 (defun org-yank (&optional arg)
21516 "Yank. If the kill is a subtree, treat it specially.
21517 This command will look at the current kill and check if is a single
21518 subtree, or a series of subtrees[1]. If it passes the test, and if the
21519 cursor is at the beginning of a line or after the stars of a currently
21520 empty headline, then the yank is handled specially. How exactly depends
21521 on the value of the following variables, both set by default.
21523 org-yank-folded-subtrees
21524 When set, the subtree(s) will be folded after insertion, but only
21525 if doing so would now swallow text after the yanked text.
21527 org-yank-adjusted-subtrees
21528 When set, the subtree will be promoted or demoted in order to
21529 fit into the local outline tree structure, which means that the level
21530 will be adjusted so that it becomes the smaller one of the two
21531 *visible* surrounding headings.
21533 Any prefix to this command will cause `yank' to be called directly with
21534 no special treatment. In particular, a simple \\[universal-argument] prefix \
21535 will just
21536 plainly yank the text as it is.
21538 \[1] The test checks if the first non-white line is a heading
21539 and if there are no other headings with fewer stars."
21540 (interactive "P")
21541 (org-yank-generic 'yank arg))
21543 (defun org-yank-generic (command arg)
21544 "Perform some yank-like command.
21546 This function implements the behavior described in the `org-yank'
21547 documentation. However, it has been generalized to work for any
21548 interactive command with similar behavior."
21550 ;; pretend to be command COMMAND
21551 (setq this-command command)
21553 (if arg
21554 (call-interactively command)
21556 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21557 (and (org-kill-is-subtree-p)
21558 (or (bolp)
21559 (and (looking-at "[ \t]*$")
21560 (string-match
21561 "\\`\\*+\\'"
21562 (buffer-substring (point-at-bol) (point)))))))
21563 swallowp)
21564 (cond
21565 ((and subtreep org-yank-folded-subtrees)
21566 (let ((beg (point))
21567 end)
21568 (if (and subtreep org-yank-adjusted-subtrees)
21569 (org-paste-subtree nil nil 'for-yank)
21570 (call-interactively command))
21572 (setq end (point))
21573 (goto-char beg)
21574 (when (and (bolp) subtreep
21575 (not (setq swallowp
21576 (org-yank-folding-would-swallow-text beg end))))
21577 (org-with-limited-levels
21578 (or (looking-at org-outline-regexp)
21579 (re-search-forward org-outline-regexp-bol end t))
21580 (while (and (< (point) end) (looking-at org-outline-regexp))
21581 (hide-subtree)
21582 (org-cycle-show-empty-lines 'folded)
21583 (condition-case nil
21584 (outline-forward-same-level 1)
21585 (error (goto-char end))))))
21586 (when swallowp
21587 (message
21588 "Inserted text not folded because that would swallow text"))
21590 (goto-char end)
21591 (skip-chars-forward " \t\n\r")
21592 (beginning-of-line 1)
21593 (push-mark beg 'nomsg)))
21594 ((and subtreep org-yank-adjusted-subtrees)
21595 (let ((beg (point-at-bol)))
21596 (org-paste-subtree nil nil 'for-yank)
21597 (push-mark beg 'nomsg)))
21599 (call-interactively command))))))
21601 (defun org-yank-folding-would-swallow-text (beg end)
21602 "Would hide-subtree at BEG swallow any text after END?"
21603 (let (level)
21604 (org-with-limited-levels
21605 (save-excursion
21606 (goto-char beg)
21607 (when (or (looking-at org-outline-regexp)
21608 (re-search-forward org-outline-regexp-bol end t))
21609 (setq level (org-outline-level)))
21610 (goto-char end)
21611 (skip-chars-forward " \t\r\n\v\f")
21612 (if (or (eobp)
21613 (and (bolp) (looking-at org-outline-regexp)
21614 (<= (org-outline-level) level)))
21615 nil ; Nothing would be swallowed
21616 t))))) ; something would swallow
21618 (define-key org-mode-map "\C-y" 'org-yank)
21620 (defun org-truely-invisible-p ()
21621 "Check if point is at a character currently not visible.
21622 This version does not only check the character property, but also
21623 `visible-mode'."
21624 ;; Early versions of noutline don't have `outline-invisible-p'.
21625 (if (org-bound-and-true-p visible-mode)
21627 (outline-invisible-p)))
21629 (defun org-invisible-p2 ()
21630 "Check if point is at a character currently not visible."
21631 (save-excursion
21632 (if (and (eolp) (not (bobp))) (backward-char 1))
21633 ;; Early versions of noutline don't have `outline-invisible-p'.
21634 (outline-invisible-p)))
21636 (defun org-back-to-heading (&optional invisible-ok)
21637 "Call `outline-back-to-heading', but provide a better error message."
21638 (condition-case nil
21639 (outline-back-to-heading invisible-ok)
21640 (error (error "Before first headline at position %d in buffer %s"
21641 (point) (current-buffer)))))
21643 (defun org-before-first-heading-p ()
21644 "Before first heading?"
21645 (save-excursion
21646 (end-of-line)
21647 (null (re-search-backward org-outline-regexp-bol nil t))))
21649 (defun org-at-heading-p (&optional ignored)
21650 (outline-on-heading-p t))
21651 ;; Compatibility alias with Org versions < 7.8.03
21652 (defalias 'org-on-heading-p 'org-at-heading-p)
21654 (defun org-at-comment-p nil
21655 "Is cursor in a line starting with a # character?"
21656 (save-excursion
21657 (beginning-of-line)
21658 (looking-at "^#")))
21660 (defun org-at-drawer-p nil
21661 "Is cursor at a drawer keyword?"
21662 (save-excursion
21663 (move-beginning-of-line 1)
21664 (looking-at org-drawer-regexp)))
21666 (defun org-at-block-p nil
21667 "Is cursor at a block keyword?"
21668 (save-excursion
21669 (move-beginning-of-line 1)
21670 (looking-at org-block-regexp)))
21672 (defun org-point-at-end-of-empty-headline ()
21673 "If point is at the end of an empty headline, return t, else nil.
21674 If the heading only contains a TODO keyword, it is still still considered
21675 empty."
21676 (and (looking-at "[ \t]*$")
21677 (when org-todo-line-regexp
21678 (save-excursion
21679 (beginning-of-line 1)
21680 (let ((case-fold-search nil))
21681 (looking-at org-todo-line-regexp)
21682 (string= (match-string 3) ""))))))
21684 (defun org-at-heading-or-item-p ()
21685 (or (org-at-heading-p) (org-at-item-p)))
21687 (defun org-at-target-p ()
21688 (or (org-in-regexp org-radio-target-regexp)
21689 (org-in-regexp org-target-regexp)))
21690 ;; Compatibility alias with Org versions < 7.8.03
21691 (defalias 'org-on-target-p 'org-at-target-p)
21693 (defun org-up-heading-all (arg)
21694 "Move to the heading line of which the present line is a subheading.
21695 This function considers both visible and invisible heading lines.
21696 With argument, move up ARG levels."
21697 (if (fboundp 'outline-up-heading-all)
21698 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21699 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21701 (defun org-up-heading-safe ()
21702 "Move to the heading line of which the present line is a subheading.
21703 This version will not throw an error. It will return the level of the
21704 headline found, or nil if no higher level is found.
21706 Also, this function will be a lot faster than `outline-up-heading',
21707 because it relies on stars being the outline starters. This can really
21708 make a significant difference in outlines with very many siblings."
21709 (let (start-level re)
21710 (org-back-to-heading t)
21711 (setq start-level (funcall outline-level))
21712 (if (equal start-level 1)
21714 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21715 (if (re-search-backward re nil t)
21716 (funcall outline-level)))))
21718 (defun org-first-sibling-p ()
21719 "Is this heading the first child of its parents?"
21720 (interactive)
21721 (let ((re org-outline-regexp-bol)
21722 level l)
21723 (unless (org-at-heading-p t)
21724 (error "Not at a heading"))
21725 (setq level (funcall outline-level))
21726 (save-excursion
21727 (if (not (re-search-backward re nil t))
21729 (setq l (funcall outline-level))
21730 (< l level)))))
21732 (defun org-goto-sibling (&optional previous)
21733 "Goto the next sibling, even if it is invisible.
21734 When PREVIOUS is set, go to the previous sibling instead. Returns t
21735 when a sibling was found. When none is found, return nil and don't
21736 move point."
21737 (let ((fun (if previous 're-search-backward 're-search-forward))
21738 (pos (point))
21739 (re org-outline-regexp-bol)
21740 level l)
21741 (when (condition-case nil (org-back-to-heading t) (error nil))
21742 (setq level (funcall outline-level))
21743 (catch 'exit
21744 (or previous (forward-char 1))
21745 (while (funcall fun re nil t)
21746 (setq l (funcall outline-level))
21747 (when (< l level) (goto-char pos) (throw 'exit nil))
21748 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21749 (goto-char pos)
21750 nil))))
21752 (defun org-show-siblings ()
21753 "Show all siblings of the current headline."
21754 (save-excursion
21755 (while (org-goto-sibling) (org-flag-heading nil)))
21756 (save-excursion
21757 (while (org-goto-sibling 'previous)
21758 (org-flag-heading nil))))
21760 (defun org-goto-first-child ()
21761 "Goto the first child, even if it is invisible.
21762 Return t when a child was found. Otherwise don't move point and
21763 return nil."
21764 (let (level (pos (point)) (re org-outline-regexp-bol))
21765 (when (condition-case nil (org-back-to-heading t) (error nil))
21766 (setq level (outline-level))
21767 (forward-char 1)
21768 (if (and (re-search-forward re nil t) (> (outline-level) level))
21769 (progn (goto-char (match-beginning 0)) t)
21770 (goto-char pos) nil))))
21772 (defun org-show-hidden-entry ()
21773 "Show an entry where even the heading is hidden."
21774 (save-excursion
21775 (org-show-entry)))
21777 (defun org-flag-heading (flag &optional entry)
21778 "Flag the current heading. FLAG non-nil means make invisible.
21779 When ENTRY is non-nil, show the entire entry."
21780 (save-excursion
21781 (org-back-to-heading t)
21782 ;; Check if we should show the entire entry
21783 (if entry
21784 (progn
21785 (org-show-entry)
21786 (save-excursion
21787 (and (outline-next-heading)
21788 (org-flag-heading nil))))
21789 (outline-flag-region (max (point-min) (1- (point)))
21790 (save-excursion (outline-end-of-heading) (point))
21791 flag))))
21793 (defun org-get-next-sibling ()
21794 "Move to next heading of the same level, and return point.
21795 If there is no such heading, return nil.
21796 This is like outline-next-sibling, but invisible headings are ok."
21797 (let ((level (funcall outline-level)))
21798 (outline-next-heading)
21799 (while (and (not (eobp)) (> (funcall outline-level) level))
21800 (outline-next-heading))
21801 (if (or (eobp) (< (funcall outline-level) level))
21803 (point))))
21805 (defun org-get-last-sibling ()
21806 "Move to previous heading of the same level, and return point.
21807 If there is no such heading, return nil."
21808 (let ((opoint (point))
21809 (level (funcall outline-level)))
21810 (outline-previous-heading)
21811 (when (and (/= (point) opoint) (outline-on-heading-p t))
21812 (while (and (> (funcall outline-level) level)
21813 (not (bobp)))
21814 (outline-previous-heading))
21815 (if (< (funcall outline-level) level)
21817 (point)))))
21819 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21820 "Goto to the end of a subtree."
21821 ;; This contains an exact copy of the original function, but it uses
21822 ;; `org-back-to-heading', to make it work also in invisible
21823 ;; trees. And is uses an invisible-ok argument.
21824 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21825 ;; Furthermore, when used inside Org, finding the end of a large subtree
21826 ;; with many children and grandchildren etc, this can be much faster
21827 ;; than the outline version.
21828 (org-back-to-heading invisible-ok)
21829 (let ((first t)
21830 (level (funcall outline-level)))
21831 (if (and (derived-mode-p 'org-mode) (< level 1000))
21832 ;; A true heading (not a plain list item), in Org-mode
21833 ;; This means we can easily find the end by looking
21834 ;; only for the right number of stars. Using a regexp to do
21835 ;; this is so much faster than using a Lisp loop.
21836 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21837 (forward-char 1)
21838 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21839 ;; something else, do it the slow way
21840 (while (and (not (eobp))
21841 (or first (> (funcall outline-level) level)))
21842 (setq first nil)
21843 (outline-next-heading)))
21844 (unless to-heading
21845 (if (memq (preceding-char) '(?\n ?\^M))
21846 (progn
21847 ;; Go to end of line before heading
21848 (forward-char -1)
21849 (if (memq (preceding-char) '(?\n ?\^M))
21850 ;; leave blank line before heading
21851 (forward-char -1))))))
21852 (point))
21854 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21855 "Use Org version in org-mode, for dramatic speed-up."
21856 (if (derived-mode-p 'org-mode)
21857 (progn
21858 (org-end-of-subtree nil t)
21859 (unless (eobp) (backward-char 1)))
21860 ad-do-it))
21862 (defun org-end-of-meta-data-and-drawers ()
21863 "Jump to the first text after meta data and drawers in the current entry.
21864 This will move over empty lines, lines with planning time stamps,
21865 clocking lines, and drawers."
21866 (org-back-to-heading t)
21867 (let ((end (save-excursion (outline-next-heading) (point)))
21868 (re (concat "\\(" org-drawer-regexp "\\)"
21869 "\\|" "[ \t]*" org-keyword-time-regexp)))
21870 (forward-line 1)
21871 (while (re-search-forward re end t)
21872 (if (not (match-end 1))
21873 ;; empty or planning line
21874 (forward-line 1)
21875 ;; a drawer, find the end
21876 (re-search-forward "^[ \t]*:END:" end 'move)
21877 (forward-line 1)))
21878 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21879 (point)))
21881 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21882 "Move forward to the arg'th subheading at same level as this one.
21883 Stop at the first and last subheadings of a superior heading.
21884 Normally this only looks at visible headings, but when INVISIBLE-OK is
21885 non-nil it will also look at invisible ones."
21886 (interactive "p")
21887 (org-back-to-heading invisible-ok)
21888 (org-at-heading-p)
21889 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21890 (re (format "^\\*\\{1,%d\\} " level))
21892 (forward-char 1)
21893 (while (> arg 0)
21894 (while (and (re-search-forward re nil 'move)
21895 (setq l (- (match-end 0) (match-beginning 0) 1))
21896 (= l level)
21897 (not invisible-ok)
21898 (progn (backward-char 1) (outline-invisible-p)))
21899 (if (< l level) (setq arg 1)))
21900 (setq arg (1- arg)))
21901 (beginning-of-line 1)))
21903 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21904 "Move backward to the arg'th subheading at same level as this one.
21905 Stop at the first and last subheadings of a superior heading."
21906 (interactive "p")
21907 (org-back-to-heading)
21908 (org-at-heading-p)
21909 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21910 (re (format "^\\*\\{1,%d\\} " level))
21912 (while (> arg 0)
21913 (while (and (re-search-backward re nil 'move)
21914 (setq l (- (match-end 0) (match-beginning 0) 1))
21915 (= l level)
21916 (not invisible-ok)
21917 (outline-invisible-p))
21918 (if (< l level) (setq arg 1)))
21919 (setq arg (1- arg)))))
21921 ;;;###autoload
21922 (defun org-forward-element ()
21923 "Move forward by one element.
21924 Move to the next element at the same level, when possible."
21925 (interactive)
21926 (cond ((eobp) (error "Cannot move further down"))
21927 ((org-with-limited-levels (org-at-heading-p))
21928 (let ((origin (point)))
21929 (org-forward-heading-same-level 1)
21930 (unless (org-with-limited-levels (org-at-heading-p))
21931 (goto-char origin)
21932 (error "Cannot move further down"))))
21934 (let* ((elem (org-element-at-point))
21935 (end (org-element-property :end elem))
21936 (parent (org-element-property :parent elem)))
21937 (if (and parent (= (org-element-property :contents-end parent) end))
21938 (goto-char (org-element-property :end parent))
21939 (goto-char end))))))
21941 ;;;###autoload
21942 (defun org-backward-element ()
21943 "Move backward by one element.
21944 Move to the previous element at the same level, when possible."
21945 (interactive)
21946 (cond ((bobp) (error "Cannot move further up"))
21947 ((org-with-limited-levels (org-at-heading-p))
21948 ;; At an headline, move to the previous one, if any, or stay
21949 ;; here.
21950 (let ((origin (point)))
21951 (org-backward-heading-same-level 1)
21952 (unless (org-with-limited-levels (org-at-heading-p))
21953 (goto-char origin)
21954 (error "Cannot move further up"))))
21956 (let* ((trail (org-element-at-point 'keep-trail))
21957 (elem (car trail))
21958 (prev-elem (nth 1 trail))
21959 (beg (org-element-property :begin elem)))
21960 (cond
21961 ;; Move to beginning of current element if point isn't
21962 ;; there already.
21963 ((/= (point) beg) (goto-char beg))
21964 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21965 ((org-before-first-heading-p) (goto-char (point-min)))
21966 (t (org-back-to-heading)))))))
21968 ;;;###autoload
21969 (defun org-up-element ()
21970 "Move to upper element."
21971 (interactive)
21972 (if (org-with-limited-levels (org-at-heading-p))
21973 (unless (org-up-heading-safe) (error "No surrounding element"))
21974 (let* ((elem (org-element-at-point))
21975 (parent (org-element-property :parent elem)))
21976 (if parent (goto-char (org-element-property :begin parent))
21977 (if (org-with-limited-levels (org-before-first-heading-p))
21978 (error "No surrounding element")
21979 (org-with-limited-levels (org-back-to-heading)))))))
21981 ;;;###autoload
21982 (defvar org-element-greater-elements)
21983 (defun org-down-element ()
21984 "Move to inner element."
21985 (interactive)
21986 (let ((element (org-element-at-point)))
21987 (cond
21988 ((memq (org-element-type element) '(plain-list table))
21989 (goto-char (org-element-property :contents-begin element))
21990 (forward-char))
21991 ((memq (org-element-type element) org-element-greater-elements)
21992 ;; If contents are hidden, first disclose them.
21993 (when (org-element-property :hiddenp element) (org-cycle))
21994 (goto-char (or (org-element-property :contents-begin element)
21995 (error "No content for this element"))))
21996 (t (error "No inner element")))))
21998 ;;;###autoload
21999 (defun org-drag-element-backward ()
22000 "Move backward element at point."
22001 (interactive)
22002 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22003 (let* ((trail (org-element-at-point 'keep-trail))
22004 (elem (car trail))
22005 (prev-elem (nth 1 trail)))
22006 ;; Error out if no previous element or previous element is
22007 ;; a parent of the current one.
22008 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22009 (error "Cannot drag element backward")
22010 (let ((pos (point)))
22011 (org-element-swap-A-B prev-elem elem)
22012 (goto-char (+ (org-element-property :begin prev-elem)
22013 (- pos (org-element-property :begin elem)))))))))
22015 ;;;###autoload
22016 (defun org-drag-element-forward ()
22017 "Move forward element at point."
22018 (interactive)
22019 (let* ((pos (point))
22020 (elem (org-element-at-point)))
22021 (when (= (point-max) (org-element-property :end elem))
22022 (error "Cannot drag element forward"))
22023 (goto-char (org-element-property :end elem))
22024 (let ((next-elem (org-element-at-point)))
22025 (when (or (org-element-nested-p elem next-elem)
22026 (and (eq (org-element-type next-elem) 'headline)
22027 (not (eq (org-element-type elem) 'headline))))
22028 (goto-char pos)
22029 (error "Cannot drag element forward"))
22030 ;; Compute new position of point: it's shifted by NEXT-ELEM
22031 ;; body's length (without final blanks) and by the length of
22032 ;; blanks between ELEM and NEXT-ELEM.
22033 (let ((size-next (- (save-excursion
22034 (goto-char (org-element-property :end next-elem))
22035 (skip-chars-backward " \r\t\n")
22036 (forward-line)
22037 ;; Small correction if buffer doesn't end
22038 ;; with a newline character.
22039 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22040 (org-element-property :begin next-elem)))
22041 (size-blank (- (org-element-property :end elem)
22042 (save-excursion
22043 (goto-char (org-element-property :end elem))
22044 (skip-chars-backward " \r\t\n")
22045 (forward-line)
22046 (point)))))
22047 (org-element-swap-A-B elem next-elem)
22048 (goto-char (+ pos size-next size-blank))))))
22050 ;;;###autoload
22051 (defun org-mark-element ()
22052 "Put point at beginning of this element, mark at end.
22054 Interactively, if this command is repeated or (in Transient Mark
22055 mode) if the mark is active, it marks the next element after the
22056 ones already marked."
22057 (interactive)
22058 (let (deactivate-mark)
22059 (if (and (org-called-interactively-p 'any)
22060 (or (and (eq last-command this-command) (mark t))
22061 (and transient-mark-mode mark-active)))
22062 (set-mark
22063 (save-excursion
22064 (goto-char (mark))
22065 (goto-char (org-element-property :end (org-element-at-point)))))
22066 (let ((element (org-element-at-point)))
22067 (end-of-line)
22068 (push-mark (org-element-property :end element) t t)
22069 (goto-char (org-element-property :begin element))))))
22071 ;;;###autoload
22072 (defun org-narrow-to-element ()
22073 "Narrow buffer to current element."
22074 (interactive)
22075 (let ((elem (org-element-at-point)))
22076 (cond
22077 ((eq (car elem) 'headline)
22078 (narrow-to-region
22079 (org-element-property :begin elem)
22080 (org-element-property :end elem)))
22081 ((memq (car elem) org-element-greater-elements)
22082 (narrow-to-region
22083 (org-element-property :contents-begin elem)
22084 (org-element-property :contents-end elem)))
22086 (narrow-to-region
22087 (org-element-property :begin elem)
22088 (org-element-property :end elem))))))
22090 ;;;###autoload
22091 (defun org-transpose-element ()
22092 "Transpose current and previous elements, keeping blank lines between.
22093 Point is moved after both elements."
22094 (interactive)
22095 (org-skip-whitespace)
22096 (let ((end (org-element-property :end (org-element-at-point))))
22097 (org-drag-element-backward)
22098 (goto-char end)))
22100 ;;;###autoload
22101 (defun org-unindent-buffer ()
22102 "Un-indent the visible part of the buffer.
22103 Relative indentation (between items, inside blocks, etc.) isn't
22104 modified."
22105 (interactive)
22106 (unless (eq major-mode 'org-mode)
22107 (error "Cannot un-indent a buffer not in Org mode"))
22108 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22109 unindent-tree ; For byte-compiler.
22110 (unindent-tree
22111 (function
22112 (lambda (contents)
22113 (mapc
22114 (lambda (element)
22115 (if (memq (org-element-type element) '(headline section))
22116 (funcall unindent-tree (org-element-contents element))
22117 (save-excursion
22118 (save-restriction
22119 (narrow-to-region
22120 (org-element-property :begin element)
22121 (org-element-property :end element))
22122 (org-do-remove-indentation)))))
22123 (reverse contents))))))
22124 (funcall unindent-tree (org-element-contents parse-tree))))
22126 (defun org-show-subtree ()
22127 "Show everything after this heading at deeper levels."
22128 (interactive)
22129 (outline-flag-region
22130 (point)
22131 (save-excursion
22132 (org-end-of-subtree t t))
22133 nil))
22135 (defun org-show-entry ()
22136 "Show the body directly following this heading.
22137 Show the heading too, if it is currently invisible."
22138 (interactive)
22139 (save-excursion
22140 (condition-case nil
22141 (progn
22142 (org-back-to-heading t)
22143 (outline-flag-region
22144 (max (point-min) (1- (point)))
22145 (save-excursion
22146 (if (re-search-forward
22147 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22148 (match-beginning 1)
22149 (point-max)))
22150 nil)
22151 (org-cycle-hide-drawers 'children))
22152 (error nil))))
22154 (defun org-make-options-regexp (kwds &optional extra)
22155 "Make a regular expression for keyword lines."
22156 (concat
22157 "^#\\+\\("
22158 (mapconcat 'regexp-quote kwds "\\|")
22159 (if extra (concat "\\|" extra))
22160 "\\):[ \t]*\\(.*\\)"))
22162 ;; Make isearch reveal the necessary context
22163 (defun org-isearch-end ()
22164 "Reveal context after isearch exits."
22165 (when isearch-success ; only if search was successful
22166 (if (featurep 'xemacs)
22167 ;; Under XEmacs, the hook is run in the correct place,
22168 ;; we directly show the context.
22169 (org-show-context 'isearch)
22170 ;; In Emacs the hook runs *before* restoring the overlays.
22171 ;; So we have to use a one-time post-command-hook to do this.
22172 ;; (Emacs 22 has a special variable, see function `org-mode')
22173 (unless (and (boundp 'isearch-mode-end-hook-quit)
22174 isearch-mode-end-hook-quit)
22175 ;; Only when the isearch was not quitted.
22176 (org-add-hook 'post-command-hook 'org-isearch-post-command
22177 'append 'local)))))
22179 (defun org-isearch-post-command ()
22180 "Remove self from hook, and show context."
22181 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22182 (org-show-context 'isearch))
22185 ;;;; Integration with and fixes for other packages
22187 ;;; Imenu support
22189 (defvar org-imenu-markers nil
22190 "All markers currently used by Imenu.")
22191 (make-variable-buffer-local 'org-imenu-markers)
22193 (defun org-imenu-new-marker (&optional pos)
22194 "Return a new marker for use by Imenu, and remember the marker."
22195 (let ((m (make-marker)))
22196 (move-marker m (or pos (point)))
22197 (push m org-imenu-markers)
22200 (defun org-imenu-get-tree ()
22201 "Produce the index for Imenu."
22202 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22203 (setq org-imenu-markers nil)
22204 (let* ((n org-imenu-depth)
22205 (re (concat "^" (org-get-limited-outline-regexp)))
22206 (subs (make-vector (1+ n) nil))
22207 (last-level 0)
22208 m level head)
22209 (save-excursion
22210 (save-restriction
22211 (widen)
22212 (goto-char (point-max))
22213 (while (re-search-backward re nil t)
22214 (setq level (org-reduced-level (funcall outline-level)))
22215 (when (and (<= level n)
22216 (looking-at org-complex-heading-regexp))
22217 (setq head (org-link-display-format
22218 (org-match-string-no-properties 4))
22219 m (org-imenu-new-marker))
22220 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22221 (if (>= level last-level)
22222 (push (cons head m) (aref subs level))
22223 (push (cons head (aref subs (1+ level))) (aref subs level))
22224 (loop for i from (1+ level) to n do (aset subs i nil)))
22225 (setq last-level level)))))
22226 (aref subs 1)))
22228 (eval-after-load "imenu"
22229 '(progn
22230 (add-hook 'imenu-after-jump-hook
22231 (lambda ()
22232 (if (derived-mode-p 'org-mode)
22233 (org-show-context 'org-goto))))))
22235 (defun org-link-display-format (link)
22236 "Replace a link with either the description, or the link target
22237 if no description is present"
22238 (save-match-data
22239 (if (string-match org-bracket-link-analytic-regexp link)
22240 (replace-match (if (match-end 5)
22241 (match-string 5 link)
22242 (concat (match-string 1 link)
22243 (match-string 3 link)))
22244 nil t link)
22245 link)))
22247 (defun org-toggle-link-display ()
22248 "Toggle the literal or descriptive display of links."
22249 (interactive)
22250 (if org-descriptive-links
22251 (progn (org-remove-from-invisibility-spec '(org-link))
22252 (org-restart-font-lock)
22253 (setq org-descriptive-links nil))
22254 (progn (add-to-invisibility-spec '(org-link))
22255 (org-restart-font-lock)
22256 (setq org-descriptive-links t))))
22258 ;; Speedbar support
22260 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22261 "Overlay marking the agenda restriction line in speedbar.")
22262 (overlay-put org-speedbar-restriction-lock-overlay
22263 'face 'org-agenda-restriction-lock)
22264 (overlay-put org-speedbar-restriction-lock-overlay
22265 'help-echo "Agendas are currently limited to this item.")
22266 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22268 (defun org-speedbar-set-agenda-restriction ()
22269 "Restrict future agenda commands to the location at point in speedbar.
22270 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22271 (interactive)
22272 (require 'org-agenda)
22273 (let (p m tp np dir txt)
22274 (cond
22275 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22276 'org-imenu t))
22277 (setq m (get-text-property p 'org-imenu-marker))
22278 (with-current-buffer (marker-buffer m)
22279 (goto-char m)
22280 (org-agenda-set-restriction-lock 'subtree)))
22281 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22282 'speedbar-function 'speedbar-find-file))
22283 (setq tp (previous-single-property-change
22284 (1+ p) 'speedbar-function)
22285 np (next-single-property-change
22286 tp 'speedbar-function)
22287 dir (speedbar-line-directory)
22288 txt (buffer-substring-no-properties (or tp (point-min))
22289 (or np (point-max))))
22290 (with-current-buffer (find-file-noselect
22291 (let ((default-directory dir))
22292 (expand-file-name txt)))
22293 (unless (derived-mode-p 'org-mode)
22294 (error "Cannot restrict to non-Org-mode file"))
22295 (org-agenda-set-restriction-lock 'file)))
22296 (t (error "Don't know how to restrict Org-mode's agenda")))
22297 (move-overlay org-speedbar-restriction-lock-overlay
22298 (point-at-bol) (point-at-eol))
22299 (setq current-prefix-arg nil)
22300 (org-agenda-maybe-redo)))
22302 (eval-after-load "speedbar"
22303 '(progn
22304 (speedbar-add-supported-extension ".org")
22305 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22306 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22307 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22308 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22309 (add-hook 'speedbar-visiting-tag-hook
22310 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22312 ;;; Fixes and Hacks for problems with other packages
22314 ;; Make flyspell not check words in links, to not mess up our keymap
22315 (defun org-mode-flyspell-verify ()
22316 "Don't let flyspell put overlays at active buttons, or on
22317 {todo,all-time,additional-option-like}-keywords."
22318 (let ((pos (max (1- (point)) (point-min)))
22319 (word (thing-at-point 'word)))
22320 (and (not (get-text-property pos 'keymap))
22321 (not (get-text-property pos 'org-no-flyspell))
22322 (not (member word org-todo-keywords-1))
22323 (not (member word org-all-time-keywords))
22324 (not (member word org-options-keywords))
22325 (not (member word (mapcar 'car org-startup-options)))
22326 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22328 (defun org-remove-flyspell-overlays-in (beg end)
22329 "Remove flyspell overlays in region."
22330 (and (org-bound-and-true-p flyspell-mode)
22331 (fboundp 'flyspell-delete-region-overlays)
22332 (flyspell-delete-region-overlays beg end))
22333 (add-text-properties beg end '(org-no-flyspell t)))
22335 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22336 (eval-after-load "bookmark"
22337 '(if (boundp 'bookmark-after-jump-hook)
22338 ;; We can use the hook
22339 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22340 ;; Hook not available, use advice
22341 (defadvice bookmark-jump (after org-make-visible activate)
22342 "Make the position visible."
22343 (org-bookmark-jump-unhide))))
22345 ;; Make sure saveplace shows the location if it was hidden
22346 (eval-after-load "saveplace"
22347 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22348 "Make the position visible."
22349 (org-bookmark-jump-unhide)))
22351 ;; Make sure ecb shows the location if it was hidden
22352 (eval-after-load "ecb"
22353 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22354 "Make hierarchy visible when jumping into location from ECB tree buffer."
22355 (if (derived-mode-p 'org-mode)
22356 (org-show-context))))
22358 (defun org-bookmark-jump-unhide ()
22359 "Unhide the current position, to show the bookmark location."
22360 (and (derived-mode-p 'org-mode)
22361 (or (outline-invisible-p)
22362 (save-excursion (goto-char (max (point-min) (1- (point))))
22363 (outline-invisible-p)))
22364 (org-show-context 'bookmark-jump)))
22366 ;; Make session.el ignore our circular variable
22367 (eval-after-load "session"
22368 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22370 ;;;; Experimental code
22372 (defun org-closed-in-range ()
22373 "Sparse tree of items closed in a certain time range.
22374 Still experimental, may disappear in the future."
22375 (interactive)
22376 ;; Get the time interval from the user.
22377 (let* ((time1 (org-float-time
22378 (org-read-date nil 'to-time nil "Starting date: ")))
22379 (time2 (org-float-time
22380 (org-read-date nil 'to-time nil "End date:")))
22381 ;; callback function
22382 (callback (lambda ()
22383 (let ((time
22384 (org-float-time
22385 (apply 'encode-time
22386 (org-parse-time-string
22387 (match-string 1))))))
22388 ;; check if time in interval
22389 (and (>= time time1) (<= time time2))))))
22390 ;; make tree, check each match with the callback
22391 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22393 ;;;; Finish up
22395 (provide 'org)
22397 (run-hooks 'org-load-hook)
22399 ;;; org.el ends here