Remove duplicate code
[org-mode.git] / lisp / org.el
blob1e2eb298549f637e40cedb3e8d962e58f72d32d0
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol "^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias)
102 (unless (boundp 'calendar-view-holidays-initially-flag)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially))
105 (unless (boundp 'calendar-view-diary-initially-flag)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially))
108 (unless (boundp 'diary-fancy-buffer)
109 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
111 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
115 (declare-function org-at-clock-log-p "org-clock" ())
116 (declare-function org-clock-timestamps-up "org-clock" ())
117 (declare-function org-clock-timestamps-down "org-clock" ())
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :version "24.1"
151 :type '(alist :tag "Babel Languages"
152 :key-type
153 (choice
154 (const :tag "Awk" awk)
155 (const :tag "C" C)
156 (const :tag "R" R)
157 (const :tag "Asymptote" asymptote)
158 (const :tag "Calc" calc)
159 (const :tag "Clojure" clojure)
160 (const :tag "CSS" css)
161 (const :tag "Ditaa" ditaa)
162 (const :tag "Dot" dot)
163 (const :tag "Emacs Lisp" emacs-lisp)
164 (const :tag "Fortran" fortran)
165 (const :tag "Gnuplot" gnuplot)
166 (const :tag "Haskell" haskell)
167 (const :tag "IO" io)
168 (const :tag "Java" java)
169 (const :tag "Javascript" js)
170 (const :tag "LaTeX" latex)
171 (const :tag "Ledger" ledger)
172 (const :tag "Lilypond" lilypond)
173 (const :tag "Lisp" lisp)
174 (const :tag "Maxima" maxima)
175 (const :tag "Matlab" matlab)
176 (const :tag "Mscgen" mscgen)
177 (const :tag "Ocaml" ocaml)
178 (const :tag "Octave" octave)
179 (const :tag "Org" org)
180 (const :tag "Perl" perl)
181 (const :tag "Pico Lisp" picolisp)
182 (const :tag "PlantUML" plantuml)
183 (const :tag "Python" python)
184 (const :tag "Ruby" ruby)
185 (const :tag "Sass" sass)
186 (const :tag "Scala" scala)
187 (const :tag "Scheme" scheme)
188 (const :tag "Screen" screen)
189 (const :tag "Shell Script" sh)
190 (const :tag "Shen" shen)
191 (const :tag "Sql" sql)
192 (const :tag "Sqlite" sqlite))
193 :value-type (boolean :tag "Activate" :value t)))
195 ;;;; Customization variables
196 (defcustom org-clone-delete-id nil
197 "Remove ID property of clones of a subtree.
198 When non-nil, clones of a subtree don't inherit the ID property.
199 Otherwise they inherit the ID property with a new unique
200 identifier."
201 :type 'boolean
202 :version "24.1"
203 :group 'org-id)
205 ;;; Version
206 (require 'org-compat)
207 (org-check-version)
208 ;;;###autoload
209 (defun org-version (&optional here full message)
210 "Show the org-mode version in the echo area.
211 With prefix argument HERE, insert it at point.
212 When FULL is non-nil, use a verbose version string.
213 When MESSAGE is non-nil, display a message with the version."
214 (interactive "P")
215 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
216 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
217 (org-trash (or
218 (and (fboundp 'org-release) (fboundp 'org-git-version))
219 (load (concat org-dir "org-version.el")
220 'noerror 'nomessage 'nosuffix)))
221 (org-version (org-release))
222 (git-version (org-git-version))
223 (version (format "Org-mode version %s (%s @ %s)"
224 org-version
225 git-version
226 (if org-install-dir
227 (if (string= org-dir org-install-dir)
228 org-install-dir
229 (concat "mixed installation! " org-install-dir " and " org-dir))
230 "org-install.el can not be found!")))
231 (_version (if full version org-version)))
232 (if (org-called-interactively-p 'interactive)
233 (if here
234 (insert version)
235 (message version))
236 (if message (message _version))
237 _version)))
239 ;;; Compatibility constants
241 ;;; The custom variables
243 (defgroup org nil
244 "Outline-based notes management and organizer."
245 :tag "Org"
246 :group 'outlines
247 :group 'calendar)
249 (defcustom org-mode-hook nil
250 "Mode hook for Org-mode, run after the mode was turned on."
251 :group 'org
252 :type 'hook)
254 (defcustom org-load-hook nil
255 "Hook that is run after org.el has been loaded."
256 :group 'org
257 :type 'hook)
259 (defcustom org-log-buffer-setup-hook nil
260 "Hook that is run after an Org log buffer is created."
261 :group 'org
262 :version "24.1"
263 :type 'hook)
265 (defvar org-modules) ; defined below
266 (defvar org-modules-loaded nil
267 "Have the modules been loaded already?")
269 (defun org-load-modules-maybe (&optional force)
270 "Load all extensions listed in `org-modules'."
271 (when (or force (not org-modules-loaded))
272 (mapc (lambda (ext)
273 (condition-case nil (require ext)
274 (error (message "Problems while trying to load feature `%s'" ext))))
275 org-modules)
276 (setq org-modules-loaded t)))
278 (defun org-set-modules (var value)
279 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
280 (set var value)
281 (when (featurep 'org)
282 (org-load-modules-maybe 'force)))
284 (when (org-bound-and-true-p org-modules)
285 (let ((a (member 'org-infojs org-modules)))
286 (and a (setcar a 'org-jsinfo))))
288 (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)
289 "Modules that should always be loaded together with org.el.
290 If a description starts with <C>, the file is not part of Emacs
291 and loading it will require that you have downloaded and properly installed
292 the org-mode distribution.
294 You can also use this system to load external packages (i.e. neither Org
295 core modules, nor modules from the CONTRIB directory). Just add symbols
296 to the end of the list. If the package is called org-xyz.el, then you need
297 to add the symbol `xyz', and the package must have a call to
299 (provide 'org-xyz)"
300 :group 'org
301 :set 'org-set-modules
302 :type
303 '(set :greedy t
304 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
305 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
306 (const :tag " crypt: Encryption of subtrees" org-crypt)
307 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
308 (const :tag " docview: Links to doc-view buffers" org-docview)
309 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
310 (const :tag " id: Global IDs for identifying entries" org-id)
311 (const :tag " info: Links to Info nodes" org-info)
312 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
313 (const :tag " habit: Track your consistency with habits" org-habit)
314 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
315 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
316 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
317 (const :tag " mew Links to Mew folders/messages" org-mew)
318 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
319 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
320 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
321 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
322 (const :tag " vm: Links to VM folders/messages" org-vm)
323 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
324 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
325 (const :tag " mouse: Additional mouse support" org-mouse)
326 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
328 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
329 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
330 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
331 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
332 (const :tag "C collector: Collect properties into tables" org-collector)
333 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
334 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
335 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
336 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
337 (const :tag "C eval: Include command output as text" org-eval)
338 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
339 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
340 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
341 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
342 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
344 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
346 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
347 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
348 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
349 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
350 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
351 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
352 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
353 (const :tag "C mtags: Support for muse-like tags" org-mtags)
354 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
355 (const :tag "C registry: A registry for Org-mode links" org-registry)
356 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
357 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
358 (const :tag "C secretary: Team management with org-mode" org-secretary)
359 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
360 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
361 (const :tag "C track: Keep up with Org-mode development" org-track)
362 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
363 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
364 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
366 (defcustom org-support-shift-select nil
367 "Non-nil means make shift-cursor commands select text when possible.
369 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
370 start selecting a region, or enlarge regions started in this way.
371 In Org-mode, in special contexts, these same keys are used for
372 other purposes, important enough to compete with shift selection.
373 Org tries to balance these needs by supporting `shift-select-mode'
374 outside these special contexts, under control of this variable.
376 The default of this variable is nil, to avoid confusing behavior. Shifted
377 cursor keys will then execute Org commands in the following contexts:
378 - on a headline, changing TODO state (left/right) and priority (up/down)
379 - on a time stamp, changing the time
380 - in a plain list item, changing the bullet type
381 - in a property definition line, switching between allowed values
382 - in the BEGIN line of a clock table (changing the time block).
383 Outside these contexts, the commands will throw an error.
385 When this variable is t and the cursor is not in a special
386 context, Org-mode will support shift-selection for making and
387 enlarging regions. To make this more effective, the bullet
388 cycling will no longer happen anywhere in an item line, but only
389 if the cursor is exactly on the bullet.
391 If you set this variable to the symbol `always', then the keys
392 will not be special in headlines, property lines, and item lines,
393 to make shift selection work there as well. If this is what you
394 want, you can use the following alternative commands: `C-c C-t'
395 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
396 can be used to switch TODO sets, `C-c -' to cycle item bullet
397 types, and properties can be edited by hand or in column view.
399 However, when the cursor is on a timestamp, shift-cursor commands
400 will still edit the time stamp - this is just too good to give up.
402 XEmacs user should have this variable set to nil, because
403 `shift-select-mode' is in Emacs 23 or later only."
404 :group 'org
405 :type '(choice
406 (const :tag "Never" nil)
407 (const :tag "When outside special context" t)
408 (const :tag "Everywhere except timestamps" always)))
410 (defcustom org-loop-over-headlines-in-active-region nil
411 "Shall some commands act upon headlines in the active region?
413 When set to `t', some commands will be performed in all headlines
414 within the active region.
416 When set to `start-level', some commands will be performed in all
417 headlines within the active region, provided that these headlines
418 are of the same level than the first one.
420 When set to a string, those commands will be performed on the
421 matching headlines within the active region. Such string must be
422 a tags/property/todo match as it is used in the agenda tags view.
424 The list of commands is: `org-schedule', `org-deadline',
425 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
426 `org-archive-to-archive-sibling'. The archiving commands skip
427 already archived entries."
428 :type '(choice (const :tag "Don't loop" nil)
429 (const :tag "All headlines in active region" t)
430 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
431 (string :tag "Tags/Property/Todo matcher"))
432 :version "24.1"
433 :group 'org-todo
434 :group 'org-archive)
436 (defgroup org-startup nil
437 "Options concerning startup of Org-mode."
438 :tag "Org Startup"
439 :group 'org)
441 (defcustom org-startup-folded t
442 "Non-nil means entering Org-mode will switch to OVERVIEW.
443 This can also be configured on a per-file basis by adding one of
444 the following lines anywhere in the buffer:
446 #+STARTUP: fold (or `overview', this is equivalent)
447 #+STARTUP: nofold (or `showall', this is equivalent)
448 #+STARTUP: content
449 #+STARTUP: showeverything"
450 :group 'org-startup
451 :type '(choice
452 (const :tag "nofold: show all" nil)
453 (const :tag "fold: overview" t)
454 (const :tag "content: all headlines" content)
455 (const :tag "show everything, even drawers" showeverything)))
457 (defcustom org-startup-truncated t
458 "Non-nil means entering Org-mode will set `truncate-lines'.
459 This is useful since some lines containing links can be very long and
460 uninteresting. Also tables look terrible when wrapped."
461 :group 'org-startup
462 :type 'boolean)
464 (defcustom org-startup-indented nil
465 "Non-nil means turn on `org-indent-mode' on startup.
466 This can also be configured on a per-file basis by adding one of
467 the following lines anywhere in the buffer:
469 #+STARTUP: indent
470 #+STARTUP: noindent"
471 :group 'org-structure
472 :type '(choice
473 (const :tag "Not" nil)
474 (const :tag "Globally (slow on startup in large files)" t)))
476 (defcustom org-use-sub-superscripts t
477 "Non-nil means interpret \"_\" and \"^\" for export.
478 When this option is turned on, you can use TeX-like syntax for sub- and
479 superscripts. Several characters after \"_\" or \"^\" will be
480 considered as a single item - so grouping with {} is normally not
481 needed. For example, the following things will be parsed as single
482 sub- or superscripts.
484 10^24 or 10^tau several digits will be considered 1 item.
485 10^-12 or 10^-tau a leading sign with digits or a word
486 x^2-y^3 will be read as x^2 - y^3, because items are
487 terminated by almost any nonword/nondigit char.
488 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
490 Still, ambiguity is possible - so when in doubt use {} to enclose the
491 sub/superscript. If you set this variable to the symbol `{}',
492 the braces are *required* in order to trigger interpretations as
493 sub/superscript. This can be helpful in documents that need \"_\"
494 frequently in plain text.
496 Not all export backends support this, but HTML does.
498 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
499 :group 'org-startup
500 :group 'org-export-translation
501 :version "24.1"
502 :type '(choice
503 (const :tag "Always interpret" t)
504 (const :tag "Only with braces" {})
505 (const :tag "Never interpret" nil)))
507 (if (fboundp 'defvaralias)
508 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
511 (defcustom org-startup-with-beamer-mode nil
512 "Non-nil means turn on `org-beamer-mode' on startup.
513 This can also be configured on a per-file basis by adding one of
514 the following lines anywhere in the buffer:
516 #+STARTUP: beamer"
517 :group 'org-startup
518 :version "24.1"
519 :type 'boolean)
521 (defcustom org-startup-align-all-tables nil
522 "Non-nil means align all tables when visiting a file.
523 This is useful when the column width in tables is forced with <N> cookies
524 in table fields. Such tables will look correct only after the first re-align.
525 This can also be configured on a per-file basis by adding one of
526 the following lines anywhere in the buffer:
527 #+STARTUP: align
528 #+STARTUP: noalign"
529 :group 'org-startup
530 :type 'boolean)
532 (defcustom org-startup-with-inline-images nil
533 "Non-nil means show inline images when loading a new Org file.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
536 #+STARTUP: inlineimages
537 #+STARTUP: noinlineimages"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-insert-mode-line-in-empty-file nil
543 "Non-nil means insert the first line setting Org-mode in empty files.
544 When the function `org-mode' is called interactively in an empty file, this
545 normally means that the file name does not automatically trigger Org-mode.
546 To ensure that the file will always be in Org-mode in the future, a
547 line enforcing Org-mode will be inserted into the buffer, if this option
548 has been set."
549 :group 'org-startup
550 :type 'boolean)
552 (defcustom org-replace-disputed-keys nil
553 "Non-nil means use alternative key bindings for some keys.
554 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
555 These keys are also used by other packages like shift-selection-mode'
556 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
557 If you want to use Org-mode together with one of these other modes,
558 or more generally if you would like to move some Org-mode commands to
559 other keys, set this variable and configure the keys with the variable
560 `org-disputed-keys'.
562 This option is only relevant at load-time of Org-mode, and must be set
563 *before* org.el is loaded. Changing it requires a restart of Emacs to
564 become effective."
565 :group 'org-startup
566 :type 'boolean)
568 (defcustom org-use-extra-keys nil
569 "Non-nil means use extra key sequence definitions for certain commands.
570 This happens automatically if you run XEmacs or if `window-system'
571 is nil. This variable lets you do the same manually. You must
572 set it before loading org.
574 Example: on Carbon Emacs 22 running graphically, with an external
575 keyboard on a Powerbook, the default way of setting M-left might
576 not work for either Alt or ESC. Setting this variable will make
577 it work for ESC."
578 :group 'org-startup
579 :type 'boolean)
581 (if (fboundp 'defvaralias)
582 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
584 (defcustom org-disputed-keys
585 '(([(shift up)] . [(meta p)])
586 ([(shift down)] . [(meta n)])
587 ([(shift left)] . [(meta -)])
588 ([(shift right)] . [(meta +)])
589 ([(control shift right)] . [(meta shift +)])
590 ([(control shift left)] . [(meta shift -)]))
591 "Keys for which Org-mode and other modes compete.
592 This is an alist, cars are the default keys, second element specifies
593 the alternative to use when `org-replace-disputed-keys' is t.
595 Keys can be specified in any syntax supported by `define-key'.
596 The value of this option takes effect only at Org-mode's startup,
597 therefore you'll have to restart Emacs to apply it after changing."
598 :group 'org-startup
599 :type 'alist)
601 (defun org-key (key)
602 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
603 Or return the original if not disputed.
604 Also apply the translations defined in `org-xemacs-key-equivalents'."
605 (when org-replace-disputed-keys
606 (let* ((nkey (key-description key))
607 (x (org-find-if (lambda (x)
608 (equal (key-description (car x)) nkey))
609 org-disputed-keys)))
610 (setq key (if x (cdr x) key))))
611 (when (featurep 'xemacs)
612 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
613 key)
615 (defun org-find-if (predicate seq)
616 (catch 'exit
617 (while seq
618 (if (funcall predicate (car seq))
619 (throw 'exit (car seq))
620 (pop seq)))))
622 (defun org-defkey (keymap key def)
623 "Define a key, possibly translated, as returned by `org-key'."
624 (define-key keymap (org-key key) def))
626 (defcustom org-ellipsis nil
627 "The ellipsis to use in the Org-mode outline.
628 When nil, just use the standard three dots. When a string, use that instead,
629 When a face, use the standard 3 dots, but with the specified face.
630 The change affects only Org-mode (which will then use its own display table).
631 Changing this requires executing `M-x org-mode' in a buffer to become
632 effective."
633 :group 'org-startup
634 :type '(choice (const :tag "Default" nil)
635 (face :tag "Face" :value org-warning)
636 (string :tag "String" :value "...#")))
638 (defvar org-display-table nil
639 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
641 (defgroup org-keywords nil
642 "Keywords in Org-mode."
643 :tag "Org Keywords"
644 :group 'org)
646 (defcustom org-deadline-string "DEADLINE:"
647 "String to mark deadline entries.
648 A deadline is this string, followed by a time stamp. Should be a word,
649 terminated by a colon. You can insert a schedule keyword and
650 a timestamp with \\[org-deadline].
651 Changes become only effective after restarting Emacs."
652 :group 'org-keywords
653 :type 'string)
655 (defcustom org-scheduled-string "SCHEDULED:"
656 "String to mark scheduled TODO entries.
657 A schedule is this string, followed by a time stamp. Should be a word,
658 terminated by a colon. You can insert a schedule keyword and
659 a timestamp with \\[org-schedule].
660 Changes become only effective after restarting Emacs."
661 :group 'org-keywords
662 :type 'string)
664 (defcustom org-closed-string "CLOSED:"
665 "String used as the prefix for timestamps logging closing a TODO entry."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-clock-string "CLOCK:"
670 "String used as prefix for timestamps clocking work hours on an item."
671 :group 'org-keywords
672 :type 'string)
674 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
675 org-scheduled-string "\\|"
676 org-deadline-string "\\|"
677 org-closed-string "\\|"
678 org-clock-string "\\)")
679 "Matches a line with planning or clock info.")
681 (defcustom org-comment-string "COMMENT"
682 "Entries starting with this keyword will never be exported.
683 An entry can be toggled between COMMENT and normal with
684 \\[org-toggle-comment].
685 Changes become only effective after restarting Emacs."
686 :group 'org-keywords
687 :type 'string)
689 (defcustom org-quote-string "QUOTE"
690 "Entries starting with this keyword will be exported in fixed-width font.
691 Quoting applies only to the text in the entry following the headline, and does
692 not extend beyond the next headline, even if that is lower level.
693 An entry can be toggled between QUOTE and normal with
694 \\[org-toggle-fixed-width-section]."
695 :group 'org-keywords
696 :type 'string)
698 (defconst org-repeat-re
699 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
700 "Regular expression for specifying repeated events.
701 After a match, group 1 contains the repeat expression.")
703 (defgroup org-structure nil
704 "Options concerning the general structure of Org-mode files."
705 :tag "Org Structure"
706 :group 'org)
708 (defgroup org-reveal-location nil
709 "Options about how to make context of a location visible."
710 :tag "Org Reveal Location"
711 :group 'org-structure)
713 (defconst org-context-choice
714 '(choice
715 (const :tag "Always" t)
716 (const :tag "Never" nil)
717 (repeat :greedy t :tag "Individual contexts"
718 (cons
719 (choice :tag "Context"
720 (const agenda)
721 (const org-goto)
722 (const occur-tree)
723 (const tags-tree)
724 (const link-search)
725 (const mark-goto)
726 (const bookmark-jump)
727 (const isearch)
728 (const default))
729 (boolean))))
730 "Contexts for the reveal options.")
732 (defcustom org-show-hierarchy-above '((default . t))
733 "Non-nil means show full hierarchy when revealing a location.
734 Org-mode often shows locations in an org-mode file which might have
735 been invisible before. When this is set, the hierarchy of headings
736 above the exposed location is shown.
737 Turning this off for example for sparse trees makes them very compact.
738 Instead of t, this can also be an alist specifying this option for different
739 contexts. Valid contexts are
740 agenda when exposing an entry from the agenda
741 org-goto when using the command `org-goto' on key C-c C-j
742 occur-tree when using the command `org-occur' on key C-c /
743 tags-tree when constructing a sparse tree based on tags matches
744 link-search when exposing search matches associated with a link
745 mark-goto when exposing the jump goal of a mark
746 bookmark-jump when exposing a bookmark location
747 isearch when exiting from an incremental search
748 default default for all contexts not set explicitly"
749 :group 'org-reveal-location
750 :type org-context-choice)
752 (defcustom org-show-following-heading '((default . nil))
753 "Non-nil means show following heading when revealing a location.
754 Org-mode often shows locations in an org-mode file which might have
755 been invisible before. When this is set, the heading following the
756 match is shown.
757 Turning this off for example for sparse trees makes them very compact,
758 but makes it harder to edit the location of the match. In such a case,
759 use the command \\[org-reveal] to show more context.
760 Instead of t, this can also be an alist specifying this option for different
761 contexts. See `org-show-hierarchy-above' for valid contexts."
762 :group 'org-reveal-location
763 :type org-context-choice)
765 (defcustom org-show-siblings '((default . nil) (isearch t))
766 "Non-nil means show all sibling heading when revealing a location.
767 Org-mode often shows locations in an org-mode file which might have
768 been invisible before. When this is set, the sibling of the current entry
769 heading are all made visible. If `org-show-hierarchy-above' is t,
770 the same happens on each level of the hierarchy above the current entry.
772 By default this is on for the isearch context, off for all other contexts.
773 Turning this off for example for sparse trees makes them very compact,
774 but makes it harder to edit the location of the match. In such a case,
775 use the command \\[org-reveal] to show more context.
776 Instead of t, this can also be an alist specifying this option for different
777 contexts. See `org-show-hierarchy-above' for valid contexts."
778 :group 'org-reveal-location
779 :type org-context-choice)
781 (defcustom org-show-entry-below '((default . nil))
782 "Non-nil means show the entry below a headline when revealing a location.
783 Org-mode often shows locations in an org-mode file which might have
784 been invisible before. When this is set, the text below the headline that is
785 exposed is also shown.
787 By default this is off for all contexts.
788 Instead of t, this can also be an alist specifying this option for different
789 contexts. See `org-show-hierarchy-above' for valid contexts."
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-indirect-buffer-display 'other-window
794 "How should indirect tree buffers be displayed?
795 This applies to indirect buffers created with the commands
796 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
797 Valid values are:
798 current-window Display in the current window
799 other-window Just display in another window.
800 dedicated-frame Create one new frame, and re-use it each time.
801 new-frame Make a new frame each time. Note that in this case
802 previously-made indirect buffers are kept, and you need to
803 kill these buffers yourself."
804 :group 'org-structure
805 :group 'org-agenda-windows
806 :type '(choice
807 (const :tag "In current window" current-window)
808 (const :tag "In current frame, other window" other-window)
809 (const :tag "Each time a new frame" new-frame)
810 (const :tag "One dedicated frame" dedicated-frame)))
812 (defcustom org-use-speed-commands nil
813 "Non-nil means activate single letter commands at beginning of a headline.
814 This may also be a function to test for appropriate locations where speed
815 commands should be active."
816 :group 'org-structure
817 :type '(choice
818 (const :tag "Never" nil)
819 (const :tag "At beginning of headline stars" t)
820 (function)))
822 (defcustom org-speed-commands-user nil
823 "Alist of additional speed commands.
824 This list will be checked before `org-speed-commands-default'
825 when the variable `org-use-speed-commands' is non-nil
826 and when the cursor is at the beginning of a headline.
827 The car if each entry is a string with a single letter, which must
828 be assigned to `self-insert-command' in the global map.
829 The cdr is either a command to be called interactively, a function
830 to be called, or a form to be evaluated.
831 An entry that is just a list with a single string will be interpreted
832 as a descriptive headline that will be added when listing the speed
833 commands in the Help buffer using the `?' speed command."
834 :group 'org-structure
835 :type '(repeat :value ("k" . ignore)
836 (choice :value ("k" . ignore)
837 (list :tag "Descriptive Headline" (string :tag "Headline"))
838 (cons :tag "Letter and Command"
839 (string :tag "Command letter")
840 (choice
841 (function)
842 (sexp))))))
844 (defgroup org-cycle nil
845 "Options concerning visibility cycling in Org-mode."
846 :tag "Org Cycle"
847 :group 'org-structure)
849 (defcustom org-cycle-skip-children-state-if-no-children t
850 "Non-nil means skip CHILDREN state in entries that don't have any."
851 :group 'org-cycle
852 :type 'boolean)
854 (defcustom org-cycle-max-level nil
855 "Maximum level which should still be subject to visibility cycling.
856 Levels higher than this will, for cycling, be treated as text, not a headline.
857 When `org-odd-levels-only' is set, a value of N in this variable actually
858 means 2N-1 stars as the limiting headline.
859 When nil, cycle all levels.
860 Note that the limiting level of cycling is also influenced by
861 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
862 `org-inlinetask-min-level' is, cycling will be limited to levels one less
863 than its value."
864 :group 'org-cycle
865 :type '(choice
866 (const :tag "No limit" nil)
867 (integer :tag "Maximum level")))
869 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
870 "Names of drawers. Drawers are not opened by cycling on the headline above.
871 Drawers only open with a TAB on the drawer line itself. A drawer looks like
872 this:
873 :DRAWERNAME:
874 .....
875 :END:
876 The drawer \"PROPERTIES\" is special for capturing properties through
877 the property API.
879 Drawers can be defined on the per-file basis with a line like:
881 #+DRAWERS: HIDDEN STATE PROPERTIES"
882 :group 'org-structure
883 :group 'org-cycle
884 :type '(repeat (string :tag "Drawer Name")))
886 (defcustom org-hide-block-startup nil
887 "Non-nil means entering Org-mode will fold all blocks.
888 This can also be set in on a per-file basis with
890 #+STARTUP: hideblocks
891 #+STARTUP: showblocks"
892 :group 'org-startup
893 :group 'org-cycle
894 :type 'boolean)
896 (defcustom org-cycle-global-at-bob nil
897 "Cycle globally if cursor is at beginning of buffer and not at a headline.
898 This makes it possible to do global cycling without having to use S-TAB or
899 \\[universal-argument] TAB. For this special case to work, the first line \
900 of the buffer
901 must not be a headline - it may be empty or some other text. When used in
902 this way, `org-cycle-hook' is disables temporarily, to make sure the
903 cursor stays at the beginning of the buffer.
904 When this option is nil, don't do anything special at the beginning
905 of the buffer."
906 :group 'org-cycle
907 :type 'boolean)
909 (defcustom org-cycle-level-after-item/entry-creation t
910 "Non-nil means cycle entry level or item indentation in new empty entries.
912 When the cursor is at the end of an empty headline, i.e with only stars
913 and maybe a TODO keyword, TAB will then switch the entry to become a child,
914 and then all possible ancestor states, before returning to the original state.
915 This makes data entry extremely fast: M-RET to create a new headline,
916 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
918 When the cursor is at the end of an empty plain list item, one TAB will
919 make it a subitem, two or more tabs will back up to make this an item
920 higher up in the item hierarchy."
921 :group 'org-cycle
922 :type 'boolean)
924 (defcustom org-cycle-emulate-tab t
925 "Where should `org-cycle' emulate TAB.
926 nil Never
927 white Only in completely white lines
928 whitestart Only at the beginning of lines, before the first non-white char
929 t Everywhere except in headlines
930 exc-hl-bol Everywhere except at the start of a headline
931 If TAB is used in a place where it does not emulate TAB, the current subtree
932 visibility is cycled."
933 :group 'org-cycle
934 :type '(choice (const :tag "Never" nil)
935 (const :tag "Only in completely white lines" white)
936 (const :tag "Before first char in a line" whitestart)
937 (const :tag "Everywhere except in headlines" t)
938 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
941 (defcustom org-cycle-separator-lines 2
942 "Number of empty lines needed to keep an empty line between collapsed trees.
943 If you leave an empty line between the end of a subtree and the following
944 headline, this empty line is hidden when the subtree is folded.
945 Org-mode will leave (exactly) one empty line visible if the number of
946 empty lines is equal or larger to the number given in this variable.
947 So the default 2 means at least 2 empty lines after the end of a subtree
948 are needed to produce free space between a collapsed subtree and the
949 following headline.
951 If the number is negative, and the number of empty lines is at least -N,
952 all empty lines are shown.
954 Special case: when 0, never leave empty lines in collapsed view."
955 :group 'org-cycle
956 :type 'integer)
957 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
959 (defcustom org-pre-cycle-hook nil
960 "Hook that is run before visibility cycling is happening.
961 The function(s) in this hook must accept a single argument which indicates
962 the new state that will be set right after running this hook. The
963 argument is a symbol. Before a global state change, it can have the values
964 `overview', `content', or `all'. Before a local state change, it can have
965 the values `folded', `children', or `subtree'."
966 :group 'org-cycle
967 :type 'hook)
969 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
970 org-cycle-hide-drawers
971 org-cycle-show-empty-lines
972 org-optimize-window-after-visibility-change)
973 "Hook that is run after `org-cycle' has changed the buffer visibility.
974 The function(s) in this hook must accept a single argument which indicates
975 the new state that was set by the most recent `org-cycle' command. The
976 argument is a symbol. After a global state change, it can have the values
977 `overview', `content', or `all'. After a local state change, it can have
978 the values `folded', `children', or `subtree'."
979 :group 'org-cycle
980 :type 'hook)
982 (defgroup org-edit-structure nil
983 "Options concerning structure editing in Org-mode."
984 :tag "Org Edit Structure"
985 :group 'org-structure)
987 (defcustom org-odd-levels-only nil
988 "Non-nil means skip even levels and only use odd levels for the outline.
989 This has the effect that two stars are being added/taken away in
990 promotion/demotion commands. It also influences how levels are
991 handled by the exporters.
992 Changing it requires restart of `font-lock-mode' to become effective
993 for fontification also in regions already fontified.
994 You may also set this on a per-file basis by adding one of the following
995 lines to the buffer:
997 #+STARTUP: odd
998 #+STARTUP: oddeven"
999 :group 'org-edit-structure
1000 :group 'org-appearance
1001 :type 'boolean)
1003 (defcustom org-adapt-indentation t
1004 "Non-nil means adapt indentation to outline node level.
1006 When this variable is set, Org assumes that you write outlines by
1007 indenting text in each node to align with the headline (after the stars).
1008 The following issues are influenced by this variable:
1010 - When this is set and the *entire* text in an entry is indented, the
1011 indentation is increased by one space in a demotion command, and
1012 decreased by one in a promotion command. If any line in the entry
1013 body starts with text at column 0, indentation is not changed at all.
1015 - Property drawers and planning information is inserted indented when
1016 this variable s set. When nil, they will not be indented.
1018 - TAB indents a line relative to context. The lines below a headline
1019 will be indented when this variable is set.
1021 Note that this is all about true indentation, by adding and removing
1022 space characters. See also `org-indent.el' which does level-dependent
1023 indentation in a virtual way, i.e. at display time in Emacs."
1024 :group 'org-edit-structure
1025 :type 'boolean)
1027 (defcustom org-special-ctrl-a/e nil
1028 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1030 When t, `C-a' will bring back the cursor to the beginning of the
1031 headline text, i.e. after the stars and after a possible TODO
1032 keyword. In an item, this will be the position after bullet and
1033 check-box, if any. When the cursor is already at that position,
1034 another `C-a' will bring it to the beginning of the line.
1036 `C-e' will jump to the end of the headline, ignoring the presence
1037 of tags in the headline. A second `C-e' will then jump to the
1038 true end of the line, after any tags. This also means that, when
1039 this variable is non-nil, `C-e' also will never jump beyond the
1040 end of the heading of a folded section, i.e. not after the
1041 ellipses.
1043 When set to the symbol `reversed', the first `C-a' or `C-e' works
1044 normally, going to the true line boundary first. Only a directly
1045 following, identical keypress will bring the cursor to the
1046 special positions.
1048 This may also be a cons cell where the behavior for `C-a' and
1049 `C-e' is set separately."
1050 :group 'org-edit-structure
1051 :type '(choice
1052 (const :tag "off" nil)
1053 (const :tag "on: after stars/bullet and before tags first" t)
1054 (const :tag "reversed: true line boundary first" reversed)
1055 (cons :tag "Set C-a and C-e separately"
1056 (choice :tag "Special C-a"
1057 (const :tag "off" nil)
1058 (const :tag "on: after stars/bullet first" t)
1059 (const :tag "reversed: before stars/bullet first" reversed))
1060 (choice :tag "Special C-e"
1061 (const :tag "off" nil)
1062 (const :tag "on: before tags first" t)
1063 (const :tag "reversed: after tags first" reversed)))))
1064 (if (fboundp 'defvaralias)
1065 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1067 (defcustom org-special-ctrl-k nil
1068 "Non-nil means `C-k' will behave specially in headlines.
1069 When nil, `C-k' will call the default `kill-line' command.
1070 When t, the following will happen while the cursor is in the headline:
1072 - When the cursor is at the beginning of a headline, kill the entire
1073 line and possible the folded subtree below the line.
1074 - When in the middle of the headline text, kill the headline up to the tags.
1075 - When after the headline text, kill the tags."
1076 :group 'org-edit-structure
1077 :type 'boolean)
1079 (defcustom org-ctrl-k-protect-subtree nil
1080 "Non-nil means, do not delete a hidden subtree with C-k.
1081 When set to the symbol `error', simply throw an error when C-k is
1082 used to kill (part-of) a headline that has hidden text behind it.
1083 Any other non-nil value will result in a query to the user, if it is
1084 OK to kill that hidden subtree. When nil, kill without remorse."
1085 :group 'org-edit-structure
1086 :version "24.1"
1087 :type '(choice
1088 (const :tag "Do not protect hidden subtrees" nil)
1089 (const :tag "Protect hidden subtrees with a security query" t)
1090 (const :tag "Never kill a hidden subtree with C-k" error)))
1092 (defcustom org-catch-invisible-edits nil
1093 "Check if in invisible region before inserting or deleting a character.
1094 Valid values are:
1096 nil Do not check, so just do invisible edits.
1097 error Throw an error and do nothing.
1098 show Make point visible, and do the requested edit.
1099 show-and-error Make point visible, then throw an error and abort the edit.
1100 smart Make point visible, and do insertion/deletion if it is
1101 adjacent to visible text and the change feels predictable.
1102 Never delete a previously invisible character or add in the
1103 middle or right after an invisible region. Basically, this
1104 allows insertion and backward-delete right before ellipses.
1105 FIXME: maybe in this case we should not even show?"
1106 :group 'org-edit-structure
1107 :version "24.1"
1108 :type '(choice
1109 (const :tag "Do not check" nil)
1110 (const :tag "Throw error when trying to edit" error)
1111 (const :tag "Unhide, but do not do the edit" show-and-error)
1112 (const :tag "Show invisible part and do the edit" show)
1113 (const :tag "Be smart and do the right thing" smart)))
1115 (defcustom org-yank-folded-subtrees t
1116 "Non-nil means when yanking subtrees, fold them.
1117 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1118 it starts with a heading and all other headings in it are either children
1119 or siblings, then fold all the subtrees. However, do this only if no
1120 text after the yank would be swallowed into a folded tree by this action."
1121 :group 'org-edit-structure
1122 :type 'boolean)
1124 (defcustom org-yank-adjusted-subtrees nil
1125 "Non-nil means when yanking subtrees, adjust the level.
1126 With this setting, `org-paste-subtree' is used to insert the subtree, see
1127 this function for details."
1128 :group 'org-edit-structure
1129 :type 'boolean)
1131 (defcustom org-M-RET-may-split-line '((default . t))
1132 "Non-nil means M-RET will split the line at the cursor position.
1133 When nil, it will go to the end of the line before making a
1134 new line.
1135 You may also set this option in a different way for different
1136 contexts. Valid contexts are:
1138 headline when creating a new headline
1139 item when creating a new item
1140 table in a table field
1141 default the value to be used for all contexts not explicitly
1142 customized"
1143 :group 'org-structure
1144 :group 'org-table
1145 :type '(choice
1146 (const :tag "Always" t)
1147 (const :tag "Never" nil)
1148 (repeat :greedy t :tag "Individual contexts"
1149 (cons
1150 (choice :tag "Context"
1151 (const headline)
1152 (const item)
1153 (const table)
1154 (const default))
1155 (boolean)))))
1158 (defcustom org-insert-heading-respect-content nil
1159 "Non-nil means insert new headings after the current subtree.
1160 When nil, the new heading is created directly after the current line.
1161 The commands \\[org-insert-heading-respect-content] and
1162 \\[org-insert-todo-heading-respect-content] turn this variable on
1163 for the duration of the command."
1164 :group 'org-structure
1165 :type 'boolean)
1167 (defcustom org-blank-before-new-entry '((heading . auto)
1168 (plain-list-item . auto))
1169 "Should `org-insert-heading' leave a blank line before new heading/item?
1170 The value is an alist, with `heading' and `plain-list-item' as CAR,
1171 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1172 which case Org will look at the surrounding headings/items and try to
1173 make an intelligent decision whether to insert a blank line or not.
1175 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1176 set, the setting here is ignored and no empty line is inserted, to avoid
1177 breaking the list structure."
1178 :group 'org-edit-structure
1179 :type '(list
1180 (cons (const heading)
1181 (choice (const :tag "Never" nil)
1182 (const :tag "Always" t)
1183 (const :tag "Auto" auto)))
1184 (cons (const plain-list-item)
1185 (choice (const :tag "Never" nil)
1186 (const :tag "Always" t)
1187 (const :tag "Auto" auto)))))
1189 (defcustom org-insert-heading-hook nil
1190 "Hook being run after inserting a new heading."
1191 :group 'org-edit-structure
1192 :type 'hook)
1194 (defcustom org-enable-fixed-width-editor t
1195 "Non-nil means lines starting with \":\" are treated as fixed-width.
1196 This currently only means they are never auto-wrapped.
1197 When nil, such lines will be treated like ordinary lines.
1198 See also the QUOTE keyword."
1199 :group 'org-edit-structure
1200 :type 'boolean)
1202 (defcustom org-goto-auto-isearch t
1203 "Non-nil means typing characters in `org-goto' starts incremental search."
1204 :group 'org-edit-structure
1205 :type 'boolean)
1207 (defgroup org-sparse-trees nil
1208 "Options concerning sparse trees in Org-mode."
1209 :tag "Org Sparse Trees"
1210 :group 'org-structure)
1212 (defcustom org-highlight-sparse-tree-matches t
1213 "Non-nil means highlight all matches that define a sparse tree.
1214 The highlights will automatically disappear the next time the buffer is
1215 changed by an edit command."
1216 :group 'org-sparse-trees
1217 :type 'boolean)
1219 (defcustom org-remove-highlights-with-change t
1220 "Non-nil means any change to the buffer will remove temporary highlights.
1221 Such highlights are created by `org-occur' and `org-clock-display'.
1222 When nil, `C-c C-c needs to be used to get rid of the highlights.
1223 The highlights created by `org-preview-latex-fragment' always need
1224 `C-c C-c' to be removed."
1225 :group 'org-sparse-trees
1226 :group 'org-time
1227 :type 'boolean)
1230 (defcustom org-occur-hook '(org-first-headline-recenter)
1231 "Hook that is run after `org-occur' has constructed a sparse tree.
1232 This can be used to recenter the window to show as much of the structure
1233 as possible."
1234 :group 'org-sparse-trees
1235 :type 'hook)
1237 (defgroup org-imenu-and-speedbar nil
1238 "Options concerning imenu and speedbar in Org-mode."
1239 :tag "Org Imenu and Speedbar"
1240 :group 'org-structure)
1242 (defcustom org-imenu-depth 2
1243 "The maximum level for Imenu access to Org-mode headlines.
1244 This also applied for speedbar access."
1245 :group 'org-imenu-and-speedbar
1246 :type 'integer)
1248 (defgroup org-table nil
1249 "Options concerning tables in Org-mode."
1250 :tag "Org Table"
1251 :group 'org)
1253 (defcustom org-enable-table-editor 'optimized
1254 "Non-nil means lines starting with \"|\" are handled by the table editor.
1255 When nil, such lines will be treated like ordinary lines.
1257 When equal to the symbol `optimized', the table editor will be optimized to
1258 do the following:
1259 - Automatic overwrite mode in front of whitespace in table fields.
1260 This makes the structure of the table stay in tact as long as the edited
1261 field does not exceed the column width.
1262 - Minimize the number of realigns. Normally, the table is aligned each time
1263 TAB or RET are pressed to move to another field. With optimization this
1264 happens only if changes to a field might have changed the column width.
1265 Optimization requires replacing the functions `self-insert-command',
1266 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1267 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1268 very good at guessing when a re-align will be necessary, but you can always
1269 force one with \\[org-ctrl-c-ctrl-c].
1271 If you would like to use the optimized version in Org-mode, but the
1272 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1274 This variable can be used to turn on and off the table editor during a session,
1275 but in order to toggle optimization, a restart is required.
1277 See also the variable `org-table-auto-blank-field'."
1278 :group 'org-table
1279 :type '(choice
1280 (const :tag "off" nil)
1281 (const :tag "on" t)
1282 (const :tag "on, optimized" optimized)))
1284 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1285 (version<= emacs-version "24.1"))
1286 "Non-nil means cluster self-insert commands for undo when possible.
1287 If this is set, then, like in the Emacs command loop, 20 consecutive
1288 characters will be undone together.
1289 This is configurable, because there is some impact on typing performance."
1290 :group 'org-table
1291 :type 'boolean)
1293 (defcustom org-table-tab-recognizes-table.el t
1294 "Non-nil means TAB will automatically notice a table.el table.
1295 When it sees such a table, it moves point into it and - if necessary -
1296 calls `table-recognize-table'."
1297 :group 'org-table-editing
1298 :type 'boolean)
1300 (defgroup org-link nil
1301 "Options concerning links in Org-mode."
1302 :tag "Org Link"
1303 :group 'org)
1305 (defvar org-link-abbrev-alist-local nil
1306 "Buffer-local version of `org-link-abbrev-alist', which see.
1307 The value of this is taken from the #+LINK lines.")
1308 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1310 (defcustom org-link-abbrev-alist nil
1311 "Alist of link abbreviations.
1312 The car of each element is a string, to be replaced at the start of a link.
1313 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1314 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1316 [[linkkey:tag][description]]
1318 The 'linkkey' must be a word word, starting with a letter, followed
1319 by letters, numbers, '-' or '_'.
1321 If REPLACE is a string, the tag will simply be appended to create the link.
1322 If the string contains \"%s\", the tag will be inserted there. If the string
1323 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1324 at that point (see the function `url-hexify-string'). If the string contains
1325 the specifier \"%(my-function)\", then the custom function `my-function' will
1326 be invoked: this function takes the tag as its only argument and must return
1327 a string.
1329 REPLACE may also be a function that will be called with the tag as the
1330 only argument to create the link, which should be returned as a string.
1332 See the manual for examples."
1333 :group 'org-link
1334 :type '(repeat
1335 (cons
1336 (string :tag "Protocol")
1337 (choice
1338 (string :tag "Format")
1339 (function)))))
1341 (defcustom org-descriptive-links t
1342 "Non-nil means Org will display descriptive links.
1343 E.g. [[http://orgmode.org][Org website]] will be displayed as
1344 \"Org Website\", hiding the link itself and just displaying its
1345 description. When set to `nil', Org will display the full links
1346 literally.
1348 You can interactively set the value of this variable by calling
1349 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1350 :group 'org-link
1351 :type 'boolean)
1353 (defcustom org-link-file-path-type 'adaptive
1354 "How the path name in file links should be stored.
1355 Valid values are:
1357 relative Relative to the current directory, i.e. the directory of the file
1358 into which the link is being inserted.
1359 absolute Absolute path, if possible with ~ for home directory.
1360 noabbrev Absolute path, no abbreviation of home directory.
1361 adaptive Use relative path for files in the current directory and sub-
1362 directories of it. For other files, use an absolute path."
1363 :group 'org-link
1364 :type '(choice
1365 (const relative)
1366 (const absolute)
1367 (const noabbrev)
1368 (const adaptive)))
1370 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1371 "Types of links that should be activated in Org-mode files.
1372 This is a list of symbols, each leading to the activation of a certain link
1373 type. In principle, it does not hurt to turn on most link types - there may
1374 be a small gain when turning off unused link types. The types are:
1376 bracket The recommended [[link][description]] or [[link]] links with hiding.
1377 angle Links in angular brackets that may contain whitespace like
1378 <bbdb:Carsten Dominik>.
1379 plain Plain links in normal text, no whitespace, like http://google.com.
1380 radio Text that is matched by a radio target, see manual for details.
1381 tag Tag settings in a headline (link to tag search).
1382 date Time stamps (link to calendar).
1383 footnote Footnote labels.
1385 Changing this variable requires a restart of Emacs to become effective."
1386 :group 'org-link
1387 :type '(set :greedy t
1388 (const :tag "Double bracket links" bracket)
1389 (const :tag "Angular bracket links" angle)
1390 (const :tag "Plain text links" plain)
1391 (const :tag "Radio target matches" radio)
1392 (const :tag "Tags" tag)
1393 (const :tag "Timestamps" date)
1394 (const :tag "Footnotes" footnote)))
1396 (defcustom org-make-link-description-function nil
1397 "Function to use to generate link descriptions from links.
1398 If nil the link location will be used. This function must take
1399 two parameters; the first is the link and the second the
1400 description `org-insert-link' has generated, and should return the
1401 description to use."
1402 :group 'org-link
1403 :type 'function)
1405 (defgroup org-link-store nil
1406 "Options concerning storing links in Org-mode."
1407 :tag "Org Store Link"
1408 :group 'org-link)
1410 (defcustom org-url-hexify-p t
1411 "When non-nil, hexify URL when creating a link."
1412 :type 'boolean
1413 ;; :version "24.3"
1414 :group 'org-link-store)
1416 (defcustom org-email-link-description-format "Email %c: %.30s"
1417 "Format of the description part of a link to an email or usenet message.
1418 The following %-escapes will be replaced by corresponding information:
1420 %F full \"From\" field
1421 %f name, taken from \"From\" field, address if no name
1422 %T full \"To\" field
1423 %t first name in \"To\" field, address if no name
1424 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1425 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1426 %s subject
1427 %d date
1428 %m message-id.
1430 You may use normal field width specification between the % and the letter.
1431 This is for example useful to limit the length of the subject.
1433 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1434 :group 'org-link-store
1435 :type 'string)
1437 (defcustom org-from-is-user-regexp
1438 (let (r1 r2)
1439 (when (and user-mail-address (not (string= user-mail-address "")))
1440 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1441 (when (and user-full-name (not (string= user-full-name "")))
1442 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1443 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1444 "Regexp matched against the \"From:\" header of an email or usenet message.
1445 It should match if the message is from the user him/herself."
1446 :group 'org-link-store
1447 :type 'regexp)
1449 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1450 "Non-nil means storing a link to an Org file will use entry IDs.
1452 Note that before this variable is even considered, org-id must be loaded,
1453 so please customize `org-modules' and turn it on.
1455 The variable can have the following values:
1457 t Create an ID if needed to make a link to the current entry.
1459 create-if-interactive
1460 If `org-store-link' is called directly (interactively, as a user
1461 command), do create an ID to support the link. But when doing the
1462 job for remember, only use the ID if it already exists. The
1463 purpose of this setting is to avoid proliferation of unwanted
1464 IDs, just because you happen to be in an Org file when you
1465 call `org-capture' that automatically and preemptively creates a
1466 link. If you do want to get an ID link in a remember template to
1467 an entry not having an ID, create it first by explicitly creating
1468 a link to it, using `C-c C-l' first.
1470 create-if-interactive-and-no-custom-id
1471 Like create-if-interactive, but do not create an ID if there is
1472 a CUSTOM_ID property defined in the entry. This is the default.
1474 use-existing
1475 Use existing ID, do not create one.
1477 nil Never use an ID to make a link, instead link using a text search for
1478 the headline text."
1479 :group 'org-link-store
1480 :type '(choice
1481 (const :tag "Create ID to make link" t)
1482 (const :tag "Create if storing link interactively"
1483 create-if-interactive)
1484 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1485 create-if-interactive-and-no-custom-id)
1486 (const :tag "Only use existing" use-existing)
1487 (const :tag "Do not use ID to create link" nil)))
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 ;; :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a remember template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a remember note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :type 'directory)
1881 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1882 "Default target for storing notes.
1883 Used as a fall back file for org-remember.el and org-capture.el, for
1884 templates that do not specify a target file."
1885 :group 'org-refile
1886 :group 'org-remember
1887 :type '(choice
1888 (const :tag "Default from remember-data-file" nil)
1889 file))
1891 (defcustom org-goto-interface 'outline
1892 "The default interface to be used for `org-goto'.
1893 Allowed values are:
1894 outline The interface shows an outline of the relevant file
1895 and the correct heading is found by moving through
1896 the outline or by searching with incremental search.
1897 outline-path-completion Headlines in the current buffer are offered via
1898 completion. This is the interface also used by
1899 the refile command."
1900 :group 'org-refile
1901 :type '(choice
1902 (const :tag "Outline" outline)
1903 (const :tag "Outline-path-completion" outline-path-completion)))
1905 (defcustom org-goto-max-level 5
1906 "Maximum target level when running `org-goto' with refile interface."
1907 :group 'org-refile
1908 :type 'integer)
1910 (defcustom org-reverse-note-order nil
1911 "Non-nil means store new notes at the beginning of a file or entry.
1912 When nil, new notes will be filed to the end of a file or entry.
1913 This can also be a list with cons cells of regular expressions that
1914 are matched against file names, and values."
1915 :group 'org-remember
1916 :group 'org-refile
1917 :type '(choice
1918 (const :tag "Reverse always" t)
1919 (const :tag "Reverse never" nil)
1920 (repeat :tag "By file name regexp"
1921 (cons regexp boolean))))
1923 (defcustom org-log-refile nil
1924 "Information to record when a task is refiled.
1926 Possible values are:
1928 nil Don't add anything
1929 time Add a time stamp to the task
1930 note Prompt for a note and add it with template `org-log-note-headings'
1932 This option can also be set with on a per-file-basis with
1934 #+STARTUP: nologrefile
1935 #+STARTUP: logrefile
1936 #+STARTUP: lognoterefile
1938 You can have local logging settings for a subtree by setting the LOGGING
1939 property to one or more of these keywords.
1941 When bulk-refiling from the agenda, the value `note' is forbidden and
1942 will temporarily be changed to `time'."
1943 :group 'org-refile
1944 :group 'org-progress
1945 :version "24.1"
1946 :type '(choice
1947 (const :tag "No logging" nil)
1948 (const :tag "Record timestamp" time)
1949 (const :tag "Record timestamp with note." note)))
1951 (defcustom org-refile-targets nil
1952 "Targets for refiling entries with \\[org-refile].
1953 This is a list of cons cells. Each cell contains:
1954 - a specification of the files to be considered, either a list of files,
1955 or a symbol whose function or variable value will be used to retrieve
1956 a file name or a list of file names. If you use `org-agenda-files' for
1957 that, all agenda files will be scanned for targets. Nil means consider
1958 headings in the current buffer.
1959 - A specification of how to find candidate refile targets. This may be
1960 any of:
1961 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1962 This tag has to be present in all target headlines, inheritance will
1963 not be considered.
1964 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1965 todo keyword.
1966 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1967 headlines that are refiling targets.
1968 - a cons cell (:level . N). Any headline of level N is considered a target.
1969 Note that, when `org-odd-levels-only' is set, level corresponds to
1970 order in hierarchy, not to the number of stars.
1971 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1975 Each element of this list generates a set of possible targets.
1976 The union of these sets is presented (with completion) to
1977 the user by `org-refile'.
1979 You can set the variable `org-refile-target-verify-function' to a function
1980 to verify each headline found by the simple criteria above.
1982 When this variable is nil, all top-level headlines in the current buffer
1983 are used, equivalent to the value `((nil . (:level . 1))'."
1984 :group 'org-refile
1985 :type '(repeat
1986 (cons
1987 (choice :value org-agenda-files
1988 (const :tag "All agenda files" org-agenda-files)
1989 (const :tag "Current buffer" nil)
1990 (function) (variable) (file))
1991 (choice :tag "Identify target headline by"
1992 (cons :tag "Specific tag" (const :value :tag) (string))
1993 (cons :tag "TODO keyword" (const :value :todo) (string))
1994 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1995 (cons :tag "Level number" (const :value :level) (integer))
1996 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1998 (defcustom org-refile-target-verify-function nil
1999 "Function to verify if the headline at point should be a refile target.
2000 The function will be called without arguments, with point at the
2001 beginning of the headline. It should return t and leave point
2002 where it is if the headline is a valid target for refiling.
2004 If the target should not be selected, the function must return nil.
2005 In addition to this, it may move point to a place from where the search
2006 should be continued. For example, the function may decide that the entire
2007 subtree of the current entry should be excluded and move point to the end
2008 of the subtree."
2009 :group 'org-refile
2010 :type 'function)
2012 (defcustom org-refile-use-cache nil
2013 "Non-nil means cache refile targets to speed up the process.
2014 The cache for a particular file will be updated automatically when
2015 the buffer has been killed, or when any of the marker used for flagging
2016 refile targets no longer points at a live buffer.
2017 If you have added new entries to a buffer that might themselves be targets,
2018 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2019 find that easier, `C-u C-u C-u C-c C-w'."
2020 :group 'org-refile
2021 :version "24.1"
2022 :type 'boolean)
2024 (defcustom org-refile-use-outline-path nil
2025 "Non-nil means provide refile targets as paths.
2026 So a level 3 headline will be available as level1/level2/level3.
2028 When the value is `file', also include the file name (without directory)
2029 into the path. In this case, you can also stop the completion after
2030 the file name, to get entries inserted as top level in the file.
2032 When `full-file-path', include the full file path."
2033 :group 'org-refile
2034 :type '(choice
2035 (const :tag "Not" nil)
2036 (const :tag "Yes" t)
2037 (const :tag "Start with file name" file)
2038 (const :tag "Start with full file path" full-file-path)))
2040 (defcustom org-outline-path-complete-in-steps t
2041 "Non-nil means complete the outline path in hierarchical steps.
2042 When Org-mode uses the refile interface to select an outline path
2043 \(see variable `org-refile-use-outline-path'), the completion of
2044 the path can be done is a single go, or if can be done in steps down
2045 the headline hierarchy. Going in steps is probably the best if you
2046 do not use a special completion package like `ido' or `icicles'.
2047 However, when using these packages, going in one step can be very
2048 fast, while still showing the whole path to the entry."
2049 :group 'org-refile
2050 :type 'boolean)
2052 (defcustom org-refile-allow-creating-parent-nodes nil
2053 "Non-nil means allow to create new nodes as refile targets.
2054 New nodes are then created by adding \"/new node name\" to the completion
2055 of an existing node. When the value of this variable is `confirm',
2056 new node creation must be confirmed by the user (recommended)
2057 When nil, the completion must match an existing entry.
2059 Note that, if the new heading is not seen by the criteria
2060 listed in `org-refile-targets', multiple instances of the same
2061 heading would be created by trying again to file under the new
2062 heading."
2063 :group 'org-refile
2064 :type '(choice
2065 (const :tag "Never" nil)
2066 (const :tag "Always" t)
2067 (const :tag "Prompt for confirmation" confirm)))
2069 (defcustom org-refile-active-region-within-subtree nil
2070 "Non-nil means also refile active region within a subtree.
2072 By default `org-refile' doesn't allow refiling regions if they
2073 don't contain a set of subtrees, but it might be convenient to
2074 do so sometimes: in that case, the first line of the region is
2075 converted to a headline before refiling."
2076 :group 'org-refile
2077 :version "24.1"
2078 :type 'boolean)
2080 (defgroup org-todo nil
2081 "Options concerning TODO items in Org-mode."
2082 :tag "Org TODO"
2083 :group 'org)
2085 (defgroup org-progress nil
2086 "Options concerning Progress logging in Org-mode."
2087 :tag "Org Progress"
2088 :group 'org-time)
2090 (defvar org-todo-interpretation-widgets
2091 '((:tag "Sequence (cycling hits every state)" sequence)
2092 (:tag "Type (cycling directly to DONE)" type))
2093 "The available interpretation symbols for customizing `org-todo-keywords'.
2094 Interested libraries should add to this list.")
2096 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2097 "List of TODO entry keyword sequences and their interpretation.
2098 \\<org-mode-map>This is a list of sequences.
2100 Each sequence starts with a symbol, either `sequence' or `type',
2101 indicating if the keywords should be interpreted as a sequence of
2102 action steps, or as different types of TODO items. The first
2103 keywords are states requiring action - these states will select a headline
2104 for inclusion into the global TODO list Org-mode produces. If one of
2105 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2106 signify that no further action is necessary. If \"|\" is not found,
2107 the last keyword is treated as the only DONE state of the sequence.
2109 The command \\[org-todo] cycles an entry through these states, and one
2110 additional state where no keyword is present. For details about this
2111 cycling, see the manual.
2113 TODO keywords and interpretation can also be set on a per-file basis with
2114 the special #+SEQ_TODO and #+TYP_TODO lines.
2116 Each keyword can optionally specify a character for fast state selection
2117 \(in combination with the variable `org-use-fast-todo-selection')
2118 and specifiers for state change logging, using the same syntax that
2119 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2120 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2121 indicates to record a time stamp each time this state is selected.
2123 Each keyword may also specify if a timestamp or a note should be
2124 recorded when entering or leaving the state, by adding additional
2125 characters in the parenthesis after the keyword. This looks like this:
2126 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2127 record only the time of the state change. With X and Y being either
2128 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2129 Y when leaving the state if and only if the *target* state does not
2130 define X. You may omit any of the fast-selection key or X or /Y,
2131 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2133 For backward compatibility, this variable may also be just a list
2134 of keywords. In this case the interpretation (sequence or type) will be
2135 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2136 :group 'org-todo
2137 :group 'org-keywords
2138 :type '(choice
2139 (repeat :tag "Old syntax, just keywords"
2140 (string :tag "Keyword"))
2141 (repeat :tag "New syntax"
2142 (cons
2143 (choice
2144 :tag "Interpretation"
2145 ;;Quick and dirty way to see
2146 ;;`org-todo-interpretations'. This takes the
2147 ;;place of item arguments
2148 :convert-widget
2149 (lambda (widget)
2150 (widget-put widget
2151 :args (mapcar
2152 #'(lambda (x)
2153 (widget-convert
2154 (cons 'const x)))
2155 org-todo-interpretation-widgets))
2156 widget))
2157 (repeat
2158 (string :tag "Keyword"))))))
2160 (defvar org-todo-keywords-1 nil
2161 "All TODO and DONE keywords active in a buffer.")
2162 (make-variable-buffer-local 'org-todo-keywords-1)
2163 (defvar org-todo-keywords-for-agenda nil)
2164 (defvar org-done-keywords-for-agenda nil)
2165 (defvar org-drawers-for-agenda nil)
2166 (defvar org-todo-keyword-alist-for-agenda nil)
2167 (defvar org-tag-alist-for-agenda nil)
2168 (defvar org-agenda-contributing-files nil)
2169 (defvar org-not-done-keywords nil)
2170 (make-variable-buffer-local 'org-not-done-keywords)
2171 (defvar org-done-keywords nil)
2172 (make-variable-buffer-local 'org-done-keywords)
2173 (defvar org-todo-heads nil)
2174 (make-variable-buffer-local 'org-todo-heads)
2175 (defvar org-todo-sets nil)
2176 (make-variable-buffer-local 'org-todo-sets)
2177 (defvar org-todo-log-states nil)
2178 (make-variable-buffer-local 'org-todo-log-states)
2179 (defvar org-todo-kwd-alist nil)
2180 (make-variable-buffer-local 'org-todo-kwd-alist)
2181 (defvar org-todo-key-alist nil)
2182 (make-variable-buffer-local 'org-todo-key-alist)
2183 (defvar org-todo-key-trigger nil)
2184 (make-variable-buffer-local 'org-todo-key-trigger)
2186 (defcustom org-todo-interpretation 'sequence
2187 "Controls how TODO keywords are interpreted.
2188 This variable is in principle obsolete and is only used for
2189 backward compatibility, if the interpretation of todo keywords is
2190 not given already in `org-todo-keywords'. See that variable for
2191 more information."
2192 :group 'org-todo
2193 :group 'org-keywords
2194 :type '(choice (const sequence)
2195 (const type)))
2197 (defcustom org-use-fast-todo-selection t
2198 "Non-nil means use the fast todo selection scheme with C-c C-t.
2199 This variable describes if and under what circumstances the cycling
2200 mechanism for TODO keywords will be replaced by a single-key, direct
2201 selection scheme.
2203 When nil, fast selection is never used.
2205 When the symbol `prefix', it will be used when `org-todo' is called
2206 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2207 `C-u t' in an agenda buffer.
2209 When t, fast selection is used by default. In this case, the prefix
2210 argument forces cycling instead.
2212 In all cases, the special interface is only used if access keys have
2213 actually been assigned by the user, i.e. if keywords in the configuration
2214 are followed by a letter in parenthesis, like TODO(t)."
2215 :group 'org-todo
2216 :type '(choice
2217 (const :tag "Never" nil)
2218 (const :tag "By default" t)
2219 (const :tag "Only with C-u C-c C-t" prefix)))
2221 (defcustom org-provide-todo-statistics t
2222 "Non-nil means update todo statistics after insert and toggle.
2223 ALL-HEADLINES means update todo statistics by including headlines
2224 with no TODO keyword as well, counting them as not done.
2225 A list of TODO keywords means the same, but skip keywords that are
2226 not in this list.
2228 When this is set, todo statistics is updated in the parent of the
2229 current entry each time a todo state is changed."
2230 :group 'org-todo
2231 :type '(choice
2232 (const :tag "Yes, only for TODO entries" t)
2233 (const :tag "Yes, including all entries" 'all-headlines)
2234 (repeat :tag "Yes, for TODOs in this list"
2235 (string :tag "TODO keyword"))
2236 (other :tag "No TODO statistics" nil)))
2238 (defcustom org-hierarchical-todo-statistics t
2239 "Non-nil means TODO statistics covers just direct children.
2240 When nil, all entries in the subtree are considered.
2241 This has only an effect if `org-provide-todo-statistics' is set.
2242 To set this to nil for only a single subtree, use a COOKIE_DATA
2243 property and include the word \"recursive\" into the value."
2244 :group 'org-todo
2245 :type 'boolean)
2247 (defcustom org-after-todo-state-change-hook nil
2248 "Hook which is run after the state of a TODO item was changed.
2249 The new state (a string with a TODO keyword, or nil) is available in the
2250 Lisp variable `org-state'."
2251 :group 'org-todo
2252 :type 'hook)
2254 (defvar org-blocker-hook nil
2255 "Hook for functions that are allowed to block a state change.
2257 Each function gets as its single argument a property list, see
2258 `org-trigger-hook' for more information about this list.
2260 If any of the functions in this hook returns nil, the state change
2261 is blocked.")
2263 (defvar org-trigger-hook nil
2264 "Hook for functions that are triggered by a state change.
2266 Each function gets as its single argument a property list with at least
2267 the following elements:
2269 (:type type-of-change :position pos-at-entry-start
2270 :from old-state :to new-state)
2272 Depending on the type, more properties may be present.
2274 This mechanism is currently implemented for:
2276 TODO state changes
2277 ------------------
2278 :type todo-state-change
2279 :from previous state (keyword as a string), or nil, or a symbol
2280 'todo' or 'done', to indicate the general type of state.
2281 :to new state, like in :from")
2283 (defcustom org-enforce-todo-dependencies nil
2284 "Non-nil means undone TODO entries will block switching the parent to DONE.
2285 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2286 be blocked if any prior sibling is not yet done.
2287 Finally, if the parent is blocked because of ordered siblings of its own,
2288 the child will also be blocked."
2289 :set (lambda (var val)
2290 (set var val)
2291 (if val
2292 (add-hook 'org-blocker-hook
2293 'org-block-todo-from-children-or-siblings-or-parent)
2294 (remove-hook 'org-blocker-hook
2295 'org-block-todo-from-children-or-siblings-or-parent)))
2296 :group 'org-todo
2297 :type 'boolean)
2299 (defcustom org-enforce-todo-checkbox-dependencies nil
2300 "Non-nil means unchecked boxes will block switching the parent to DONE.
2301 When this is nil, checkboxes have no influence on switching TODO states.
2302 When non-nil, you first need to check off all check boxes before the TODO
2303 entry can be switched to DONE.
2304 This variable needs to be set before org.el is loaded, and you need to
2305 restart Emacs after a change to make the change effective. The only way
2306 to change is while Emacs is running is through the customize interface."
2307 :set (lambda (var val)
2308 (set var val)
2309 (if val
2310 (add-hook 'org-blocker-hook
2311 'org-block-todo-from-checkboxes)
2312 (remove-hook 'org-blocker-hook
2313 'org-block-todo-from-checkboxes)))
2314 :group 'org-todo
2315 :type 'boolean)
2317 (defcustom org-treat-insert-todo-heading-as-state-change nil
2318 "Non-nil means inserting a TODO heading is treated as state change.
2319 So when the command \\[org-insert-todo-heading] is used, state change
2320 logging will apply if appropriate. When nil, the new TODO item will
2321 be inserted directly, and no logging will take place."
2322 :group 'org-todo
2323 :type 'boolean)
2325 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2326 "Non-nil means switching TODO states with S-cursor counts as state change.
2327 This is the default behavior. However, setting this to nil allows a
2328 convenient way to select a TODO state and bypass any logging associated
2329 with that."
2330 :group 'org-todo
2331 :type 'boolean)
2333 (defcustom org-todo-state-tags-triggers nil
2334 "Tag changes that should be triggered by TODO state changes.
2335 This is a list. Each entry is
2337 (state-change (tag . flag) .......)
2339 State-change can be a string with a state, and empty string to indicate the
2340 state that has no TODO keyword, or it can be one of the symbols `todo'
2341 or `done', meaning any not-done or done state, respectively."
2342 :group 'org-todo
2343 :group 'org-tags
2344 :type '(repeat
2345 (cons (choice :tag "When changing to"
2346 (const :tag "Not-done state" todo)
2347 (const :tag "Done state" done)
2348 (string :tag "State"))
2349 (repeat
2350 (cons :tag "Tag action"
2351 (string :tag "Tag")
2352 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2354 (defcustom org-log-done nil
2355 "Information to record when a task moves to the DONE state.
2357 Possible values are:
2359 nil Don't add anything, just change the keyword
2360 time Add a time stamp to the task
2361 note Prompt for a note and add it with template `org-log-note-headings'
2363 This option can also be set with on a per-file-basis with
2365 #+STARTUP: nologdone
2366 #+STARTUP: logdone
2367 #+STARTUP: lognotedone
2369 You can have local logging settings for a subtree by setting the LOGGING
2370 property to one or more of these keywords."
2371 :group 'org-todo
2372 :group 'org-progress
2373 :type '(choice
2374 (const :tag "No logging" nil)
2375 (const :tag "Record CLOSED timestamp" time)
2376 (const :tag "Record CLOSED timestamp with note." note)))
2378 ;; Normalize old uses of org-log-done.
2379 (cond
2380 ((eq org-log-done t) (setq org-log-done 'time))
2381 ((and (listp org-log-done) (memq 'done org-log-done))
2382 (setq org-log-done 'note)))
2384 (defcustom org-log-reschedule nil
2385 "Information to record when the scheduling date of a tasks is modified.
2387 Possible values are:
2389 nil Don't add anything, just change the date
2390 time Add a time stamp to the task
2391 note Prompt for a note and add it with template `org-log-note-headings'
2393 This option can also be set with on a per-file-basis with
2395 #+STARTUP: nologreschedule
2396 #+STARTUP: logreschedule
2397 #+STARTUP: lognotereschedule"
2398 :group 'org-todo
2399 :group 'org-progress
2400 :type '(choice
2401 (const :tag "No logging" nil)
2402 (const :tag "Record timestamp" time)
2403 (const :tag "Record timestamp with note." note)))
2405 (defcustom org-log-redeadline nil
2406 "Information to record when the deadline date of a tasks is modified.
2408 Possible values are:
2410 nil Don't add anything, just change the date
2411 time Add a time stamp to the task
2412 note Prompt for a note and add it with template `org-log-note-headings'
2414 This option can also be set with on a per-file-basis with
2416 #+STARTUP: nologredeadline
2417 #+STARTUP: logredeadline
2418 #+STARTUP: lognoteredeadline
2420 You can have local logging settings for a subtree by setting the LOGGING
2421 property to one or more of these keywords."
2422 :group 'org-todo
2423 :group 'org-progress
2424 :type '(choice
2425 (const :tag "No logging" nil)
2426 (const :tag "Record timestamp" time)
2427 (const :tag "Record timestamp with note." note)))
2429 (defcustom org-log-note-clock-out nil
2430 "Non-nil means record a note when clocking out of an item.
2431 This can also be configured on a per-file basis by adding one of
2432 the following lines anywhere in the buffer:
2434 #+STARTUP: lognoteclock-out
2435 #+STARTUP: nolognoteclock-out"
2436 :group 'org-todo
2437 :group 'org-progress
2438 :type 'boolean)
2440 (defcustom org-log-done-with-time t
2441 "Non-nil means the CLOSED time stamp will contain date and time.
2442 When nil, only the date will be recorded."
2443 :group 'org-progress
2444 :type 'boolean)
2446 (defcustom org-log-note-headings
2447 '((done . "CLOSING NOTE %t")
2448 (state . "State %-12s from %-12S %t")
2449 (note . "Note taken on %t")
2450 (reschedule . "Rescheduled from %S on %t")
2451 (delschedule . "Not scheduled, was %S on %t")
2452 (redeadline . "New deadline from %S on %t")
2453 (deldeadline . "Removed deadline, was %S on %t")
2454 (refile . "Refiled on %t")
2455 (clock-out . ""))
2456 "Headings for notes added to entries.
2457 The value is an alist, with the car being a symbol indicating the note
2458 context, and the cdr is the heading to be used. The heading may also be the
2459 empty string.
2460 %t in the heading will be replaced by a time stamp.
2461 %T will be an active time stamp instead the default inactive one
2462 %d will be replaced by a short-format time stamp.
2463 %D will be replaced by an active short-format time stamp.
2464 %s will be replaced by the new TODO state, in double quotes.
2465 %S will be replaced by the old TODO state, in double quotes.
2466 %u will be replaced by the user name.
2467 %U will be replaced by the full user name.
2469 In fact, it is not a good idea to change the `state' entry, because
2470 agenda log mode depends on the format of these entries."
2471 :group 'org-todo
2472 :group 'org-progress
2473 :type '(list :greedy t
2474 (cons (const :tag "Heading when closing an item" done) string)
2475 (cons (const :tag
2476 "Heading when changing todo state (todo sequence only)"
2477 state) string)
2478 (cons (const :tag "Heading when just taking a note" note) string)
2479 (cons (const :tag "Heading when clocking out" clock-out) string)
2480 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2481 (cons (const :tag "Heading when rescheduling" reschedule) string)
2482 (cons (const :tag "Heading when changing deadline" redeadline) string)
2483 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2484 (cons (const :tag "Heading when refiling" refile) string)))
2486 (unless (assq 'note org-log-note-headings)
2487 (push '(note . "%t") org-log-note-headings))
2489 (defcustom org-log-into-drawer nil
2490 "Non-nil means insert state change notes and time stamps into a drawer.
2491 When nil, state changes notes will be inserted after the headline and
2492 any scheduling and clock lines, but not inside a drawer.
2494 The value of this variable should be the name of the drawer to use.
2495 LOGBOOK is proposed as the default drawer for this purpose, you can
2496 also set this to a string to define the drawer of your choice.
2498 A value of t is also allowed, representing \"LOGBOOK\".
2500 If this variable is set, `org-log-state-notes-insert-after-drawers'
2501 will be ignored.
2503 You can set the property LOG_INTO_DRAWER to overrule this setting for
2504 a subtree."
2505 :group 'org-todo
2506 :group 'org-progress
2507 :type '(choice
2508 (const :tag "Not into a drawer" nil)
2509 (const :tag "LOGBOOK" t)
2510 (string :tag "Other")))
2512 (if (fboundp 'defvaralias)
2513 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2515 (defun org-log-into-drawer ()
2516 "Return the value of `org-log-into-drawer', but let properties overrule.
2517 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2518 used instead of the default value."
2519 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2520 (cond
2521 ((or (not p) (equal p "nil")) org-log-into-drawer)
2522 ((equal p "t") "LOGBOOK")
2523 (t p))))
2525 (defcustom org-log-state-notes-insert-after-drawers nil
2526 "Non-nil means insert state change notes after any drawers in entry.
2527 Only the drawers that *immediately* follow the headline and the
2528 deadline/scheduled line are skipped.
2529 When nil, insert notes right after the heading and perhaps the line
2530 with deadline/scheduling if present.
2532 This variable will have no effect if `org-log-into-drawer' is
2533 set."
2534 :group 'org-todo
2535 :group 'org-progress
2536 :type 'boolean)
2538 (defcustom org-log-states-order-reversed t
2539 "Non-nil means the latest state note will be directly after heading.
2540 When nil, the state change notes will be ordered according to time."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type 'boolean)
2545 (defcustom org-todo-repeat-to-state nil
2546 "The TODO state to which a repeater should return the repeating task.
2547 By default this is the first task in a TODO sequence, or the previous state
2548 in a TODO_TYP set. But you can specify another task here.
2549 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2550 :group 'org-todo
2551 :version "24.1"
2552 :type '(choice (const :tag "Head of sequence" nil)
2553 (string :tag "Specific state")))
2555 (defcustom org-log-repeat 'time
2556 "Non-nil means record moving through the DONE state when triggering repeat.
2557 An auto-repeating task is immediately switched back to TODO when
2558 marked DONE. If you are not logging state changes (by adding \"@\"
2559 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2560 record a closing note, there will be no record of the task moving
2561 through DONE. This variable forces taking a note anyway.
2563 nil Don't force a record
2564 time Record a time stamp
2565 note Prompt for a note and add it with template `org-log-note-headings'
2567 This option can also be set with on a per-file-basis with
2569 #+STARTUP: nologrepeat
2570 #+STARTUP: logrepeat
2571 #+STARTUP: lognoterepeat
2573 You can have local logging settings for a subtree by setting the LOGGING
2574 property to one or more of these keywords."
2575 :group 'org-todo
2576 :group 'org-progress
2577 :type '(choice
2578 (const :tag "Don't force a record" nil)
2579 (const :tag "Force recording the DONE state" time)
2580 (const :tag "Force recording a note with the DONE state" note)))
2583 (defgroup org-priorities nil
2584 "Priorities in Org-mode."
2585 :tag "Org Priorities"
2586 :group 'org-todo)
2588 (defcustom org-enable-priority-commands t
2589 "Non-nil means priority commands are active.
2590 When nil, these commands will be disabled, so that you never accidentally
2591 set a priority."
2592 :group 'org-priorities
2593 :type 'boolean)
2595 (defcustom org-highest-priority ?A
2596 "The highest priority of TODO items. A character like ?A, ?B etc.
2597 Must have a smaller ASCII number than `org-lowest-priority'."
2598 :group 'org-priorities
2599 :type 'character)
2601 (defcustom org-lowest-priority ?C
2602 "The lowest priority of TODO items. A character like ?A, ?B etc.
2603 Must have a larger ASCII number than `org-highest-priority'."
2604 :group 'org-priorities
2605 :type 'character)
2607 (defcustom org-default-priority ?B
2608 "The default priority of TODO items.
2609 This is the priority an item gets if no explicit priority is given.
2610 When starting to cycle on an empty priority the first step in the cycle
2611 depends on `org-priority-start-cycle-with-default'. The resulting first
2612 step priority must not exceed the range from `org-highest-priority' to
2613 `org-lowest-priority' which means that `org-default-priority' has to be
2614 in this range exclusive or inclusive the range boundaries. Else the
2615 first step refuses to set the default and the second will fall back
2616 to (depending on the command used) the highest or lowest priority."
2617 :group 'org-priorities
2618 :type 'character)
2620 (defcustom org-priority-start-cycle-with-default t
2621 "Non-nil means start with default priority when starting to cycle.
2622 When this is nil, the first step in the cycle will be (depending on the
2623 command used) one higher or lower than the default priority.
2624 See also `org-default-priority'."
2625 :group 'org-priorities
2626 :type 'boolean)
2628 (defcustom org-get-priority-function nil
2629 "Function to extract the priority from a string.
2630 The string is normally the headline. If this is nil Org computes the
2631 priority from the priority cookie like [#A] in the headline. It returns
2632 an integer, increasing by 1000 for each priority level.
2633 The user can set a different function here, which should take a string
2634 as an argument and return the numeric priority."
2635 :group 'org-priorities
2636 :version "24.1"
2637 :type 'function)
2639 (defgroup org-time nil
2640 "Options concerning time stamps and deadlines in Org-mode."
2641 :tag "Org Time"
2642 :group 'org)
2644 (defcustom org-insert-labeled-timestamps-at-point nil
2645 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2646 When nil, these labeled time stamps are forces into the second line of an
2647 entry, just after the headline. When scheduling from the global TODO list,
2648 the time stamp will always be forced into the second line."
2649 :group 'org-time
2650 :type 'boolean)
2652 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2653 "Formats for `format-time-string' which are used for time stamps.
2654 It is not recommended to change this constant.")
2656 (defcustom org-time-stamp-rounding-minutes '(0 5)
2657 "Number of minutes to round time stamps to.
2658 These are two values, the first applies when first creating a time stamp.
2659 The second applies when changing it with the commands `S-up' and `S-down'.
2660 When changing the time stamp, this means that it will change in steps
2661 of N minutes, as given by the second value.
2663 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2664 numbers should be factors of 60, so for example 5, 10, 15.
2666 When this is larger than 1, you can still force an exact time stamp by using
2667 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2668 and by using a prefix arg to `S-up/down' to specify the exact number
2669 of minutes to shift."
2670 :group 'org-time
2671 :get #'(lambda (var) ; Make sure both elements are there
2672 (if (integerp (default-value var))
2673 (list (default-value var) 5)
2674 (default-value var)))
2675 :type '(list
2676 (integer :tag "when inserting times")
2677 (integer :tag "when modifying times")))
2679 ;; Normalize old customizations of this variable.
2680 (when (integerp org-time-stamp-rounding-minutes)
2681 (setq org-time-stamp-rounding-minutes
2682 (list org-time-stamp-rounding-minutes
2683 org-time-stamp-rounding-minutes)))
2685 (defcustom org-display-custom-times nil
2686 "Non-nil means overlay custom formats over all time stamps.
2687 The formats are defined through the variable `org-time-stamp-custom-formats'.
2688 To turn this on on a per-file basis, insert anywhere in the file:
2689 #+STARTUP: customtime"
2690 :group 'org-time
2691 :set 'set-default
2692 :type 'sexp)
2693 (make-variable-buffer-local 'org-display-custom-times)
2695 (defcustom org-time-stamp-custom-formats
2696 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2697 "Custom formats for time stamps. See `format-time-string' for the syntax.
2698 These are overlaid over the default ISO format if the variable
2699 `org-display-custom-times' is set. Time like %H:%M should be at the
2700 end of the second format. The custom formats are also honored by export
2701 commands, if custom time display is turned on at the time of export."
2702 :group 'org-time
2703 :type 'sexp)
2705 (defun org-time-stamp-format (&optional long inactive)
2706 "Get the right format for a time string."
2707 (let ((f (if long (cdr org-time-stamp-formats)
2708 (car org-time-stamp-formats))))
2709 (if inactive
2710 (concat "[" (substring f 1 -1) "]")
2711 f)))
2713 (defcustom org-time-clocksum-format "%d:%02d"
2714 "The format string used when creating CLOCKSUM lines.
2715 This is also used when org-mode generates a time duration."
2716 :group 'org-time
2717 :type 'string)
2719 (defcustom org-time-clocksum-use-fractional nil
2720 "If non-nil, \\[org-clock-display] uses fractional times.
2721 org-mode generates a time duration."
2722 :group 'org-time
2723 :type 'boolean)
2725 (defcustom org-time-clocksum-fractional-format "%.2f"
2726 "The format string used when creating CLOCKSUM lines, or when
2727 org-mode generates a time duration."
2728 :group 'org-time
2729 :type 'string)
2731 (defcustom org-deadline-warning-days 14
2732 "No. of days before expiration during which a deadline becomes active.
2733 This variable governs the display in sparse trees and in the agenda.
2734 When 0 or negative, it means use this number (the absolute value of it)
2735 even if a deadline has a different individual lead time specified.
2737 Custom commands can set this variable in the options section."
2738 :group 'org-time
2739 :group 'org-agenda-daily/weekly
2740 :type 'integer)
2742 (defcustom org-read-date-prefer-future t
2743 "Non-nil means assume future for incomplete date input from user.
2744 This affects the following situations:
2745 1. The user gives a month but not a year.
2746 For example, if it is April and you enter \"feb 2\", this will be read
2747 as Feb 2, *next* year. \"May 5\", however, will be this year.
2748 2. The user gives a day, but no month.
2749 For example, if today is the 15th, and you enter \"3\", Org-mode will
2750 read this as the third of *next* month. However, if you enter \"17\",
2751 it will be considered as *this* month.
2753 If you set this variable to the symbol `time', then also the following
2754 will work:
2756 3. If the user gives a time.
2757 If the time is before now, it will be interpreted as tomorrow.
2759 Currently none of this works for ISO week specifications.
2761 When this option is nil, the current day, month and year will always be
2762 used as defaults.
2764 See also `org-agenda-jump-prefer-future'."
2765 :group 'org-time
2766 :type '(choice
2767 (const :tag "Never" nil)
2768 (const :tag "Check month and day" t)
2769 (const :tag "Check month, day, and time" time)))
2771 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2772 "Should the agenda jump command prefer the future for incomplete dates?
2773 The default is to do the same as configured in `org-read-date-prefer-future'.
2774 But you can also set a deviating value here.
2775 This may t or nil, or the symbol `org-read-date-prefer-future'."
2776 :group 'org-agenda
2777 :group 'org-time
2778 :version "24.1"
2779 :type '(choice
2780 (const :tag "Use org-read-date-prefer-future"
2781 org-read-date-prefer-future)
2782 (const :tag "Never" nil)
2783 (const :tag "Always" t)))
2785 (defcustom org-read-date-force-compatible-dates t
2786 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2788 Depending on the system Emacs is running on, certain dates cannot
2789 be represented with the type used internally to represent time.
2790 Dates between 1970-1-1 and 2038-1-1 can always be represented
2791 correctly. Some systems allow for earlier dates, some for later,
2792 some for both. One way to find out it to insert any date into an
2793 Org buffer, putting the cursor on the year and hitting S-up and
2794 S-down to test the range.
2796 When this variable is set to t, the date/time prompt will not let
2797 you specify dates outside the 1970-2037 range, so it is certain that
2798 these dates will work in whatever version of Emacs you are
2799 running, and also that you can move a file from one Emacs implementation
2800 to another. WHenever Org is forcing the year for you, it will display
2801 a message and beep.
2803 When this variable is nil, Org will check if the date is
2804 representable in the specific Emacs implementation you are using.
2805 If not, it will force a year, usually the current year, and beep
2806 to remind you. Currently this setting is not recommended because
2807 the likelihood that you will open your Org files in an Emacs that
2808 has limited date range is not negligible.
2810 A workaround for this problem is to use diary sexp dates for time
2811 stamps outside of this range."
2812 :group 'org-time
2813 :version "24.1"
2814 :type 'boolean)
2816 (defcustom org-read-date-display-live t
2817 "Non-nil means display current interpretation of date prompt live.
2818 This display will be in an overlay, in the minibuffer."
2819 :group 'org-time
2820 :type 'boolean)
2822 (defcustom org-read-date-popup-calendar t
2823 "Non-nil means pop up a calendar when prompting for a date.
2824 In the calendar, the date can be selected with mouse-1. However, the
2825 minibuffer will also be active, and you can simply enter the date as well.
2826 When nil, only the minibuffer will be available."
2827 :group 'org-time
2828 :type 'boolean)
2829 (if (fboundp 'defvaralias)
2830 (defvaralias 'org-popup-calendar-for-date-prompt
2831 'org-read-date-popup-calendar))
2833 (defcustom org-read-date-minibuffer-setup-hook nil
2834 "Hook to be used to set up keys for the date/time interface.
2835 Add key definitions to `minibuffer-local-map', which will be a temporary
2836 copy."
2837 :group 'org-time
2838 :type 'hook)
2840 (defcustom org-extend-today-until 0
2841 "The hour when your day really ends. Must be an integer.
2842 This has influence for the following applications:
2843 - When switching the agenda to \"today\". It it is still earlier than
2844 the time given here, the day recognized as TODAY is actually yesterday.
2845 - When a date is read from the user and it is still before the time given
2846 here, the current date and time will be assumed to be yesterday, 23:59.
2847 Also, timestamps inserted in remember templates follow this rule.
2849 IMPORTANT: This is a feature whose implementation is and likely will
2850 remain incomplete. Really, it is only here because past midnight seems to
2851 be the favorite working time of John Wiegley :-)"
2852 :group 'org-time
2853 :type 'integer)
2855 (defcustom org-use-effective-time nil
2856 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2857 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2858 \"effective time\" of any timestamps between midnight and 8am will be
2859 23:59 of the previous day."
2860 :group 'org-time
2861 :version "24.1"
2862 :type 'boolean)
2864 (defcustom org-edit-timestamp-down-means-later nil
2865 "Non-nil means S-down will increase the time in a time stamp.
2866 When nil, S-up will increase."
2867 :group 'org-time
2868 :type 'boolean)
2870 (defcustom org-calendar-follow-timestamp-change t
2871 "Non-nil means make the calendar window follow timestamp changes.
2872 When a timestamp is modified and the calendar window is visible, it will be
2873 moved to the new date."
2874 :group 'org-time
2875 :type 'boolean)
2877 (defgroup org-tags nil
2878 "Options concerning tags in Org-mode."
2879 :tag "Org Tags"
2880 :group 'org)
2882 (defcustom org-tag-alist nil
2883 "List of tags allowed in Org-mode files.
2884 When this list is nil, Org-mode will base TAG input on what is already in the
2885 buffer.
2886 The value of this variable is an alist, the car of each entry must be a
2887 keyword as a string, the cdr may be a character that is used to select
2888 that tag through the fast-tag-selection interface.
2889 See the manual for details."
2890 :group 'org-tags
2891 :type '(repeat
2892 (choice
2893 (cons (string :tag "Tag name")
2894 (character :tag "Access char"))
2895 (list :tag "Start radio group"
2896 (const :startgroup)
2897 (option (string :tag "Group description")))
2898 (list :tag "End radio group"
2899 (const :endgroup)
2900 (option (string :tag "Group description")))
2901 (const :tag "New line" (:newline)))))
2903 (defcustom org-tag-persistent-alist nil
2904 "List of tags that will always appear in all Org-mode files.
2905 This is in addition to any in buffer settings or customizations
2906 of `org-tag-alist'.
2907 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2908 The value of this variable is an alist, the car of each entry must be a
2909 keyword as a string, the cdr may be a character that is used to select
2910 that tag through the fast-tag-selection interface.
2911 See the manual for details.
2912 To disable these tags on a per-file basis, insert anywhere in the file:
2913 #+STARTUP: noptag"
2914 :group 'org-tags
2915 :type '(repeat
2916 (choice
2917 (cons (string :tag "Tag name")
2918 (character :tag "Access char"))
2919 (const :tag "Start radio group" (:startgroup))
2920 (const :tag "End radio group" (:endgroup))
2921 (const :tag "New line" (:newline)))))
2923 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2924 "If non-nil, always offer completion for all tags of all agenda files.
2925 Instead of customizing this variable directly, you might want to
2926 set it locally for capture buffers, because there no list of
2927 tags in that file can be created dynamically (there are none).
2929 (add-hook 'org-capture-mode-hook
2930 (lambda ()
2931 (set (make-local-variable
2932 'org-complete-tags-always-offer-all-agenda-tags)
2933 t)))"
2934 :group 'org-tags
2935 :version "24.1"
2936 :type 'boolean)
2938 (defvar org-file-tags nil
2939 "List of tags that can be inherited by all entries in the file.
2940 The tags will be inherited if the variable `org-use-tag-inheritance'
2941 says they should be.
2942 This variable is populated from #+FILETAGS lines.")
2944 (defcustom org-use-fast-tag-selection 'auto
2945 "Non-nil means use fast tag selection scheme.
2946 This is a special interface to select and deselect tags with single keys.
2947 When nil, fast selection is never used.
2948 When the symbol `auto', fast selection is used if and only if selection
2949 characters for tags have been configured, either through the variable
2950 `org-tag-alist' or through a #+TAGS line in the buffer.
2951 When t, fast selection is always used and selection keys are assigned
2952 automatically if necessary."
2953 :group 'org-tags
2954 :type '(choice
2955 (const :tag "Always" t)
2956 (const :tag "Never" nil)
2957 (const :tag "When selection characters are configured" 'auto)))
2959 (defcustom org-fast-tag-selection-single-key nil
2960 "Non-nil means fast tag selection exits after first change.
2961 When nil, you have to press RET to exit it.
2962 During fast tag selection, you can toggle this flag with `C-c'.
2963 This variable can also have the value `expert'. In this case, the window
2964 displaying the tags menu is not even shown, until you press C-c again."
2965 :group 'org-tags
2966 :type '(choice
2967 (const :tag "No" nil)
2968 (const :tag "Yes" t)
2969 (const :tag "Expert" expert)))
2971 (defvar org-fast-tag-selection-include-todo nil
2972 "Non-nil means fast tags selection interface will also offer TODO states.
2973 This is an undocumented feature, you should not rely on it.")
2975 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2976 "The column to which tags should be indented in a headline.
2977 If this number is positive, it specifies the column. If it is negative,
2978 it means that the tags should be flushright to that column. For example,
2979 -80 works well for a normal 80 character screen.
2980 When 0, place tags directly after headline text, with only one space in
2981 between."
2982 :group 'org-tags
2983 :type 'integer)
2985 (defcustom org-auto-align-tags t
2986 "Non-nil keeps tags aligned when modifying headlines.
2987 Some operations (i.e. demoting) change the length of a headline and
2988 therefore shift the tags around. With this option turned on, after
2989 each such operation the tags are again aligned to `org-tags-column'."
2990 :group 'org-tags
2991 :type 'boolean)
2993 (defcustom org-use-tag-inheritance t
2994 "Non-nil means tags in levels apply also for sublevels.
2995 When nil, only the tags directly given in a specific line apply there.
2996 This may also be a list of tags that should be inherited, or a regexp that
2997 matches tags that should be inherited. Additional control is possible
2998 with the variable `org-tags-exclude-from-inheritance' which gives an
2999 explicit list of tags to be excluded from inheritance., even if the value of
3000 `org-use-tag-inheritance' would select it for inheritance.
3002 If this option is t, a match early-on in a tree can lead to a large
3003 number of matches in the subtree when constructing the agenda or creating
3004 a sparse tree. If you only want to see the first match in a tree during
3005 a search, check out the variable `org-tags-match-list-sublevels'."
3006 :group 'org-tags
3007 :type '(choice
3008 (const :tag "Not" nil)
3009 (const :tag "Always" t)
3010 (repeat :tag "Specific tags" (string :tag "Tag"))
3011 (regexp :tag "Tags matched by regexp")))
3013 (defcustom org-tags-exclude-from-inheritance nil
3014 "List of tags that should never be inherited.
3015 This is a way to exclude a few tags from inheritance. For way to do
3016 the opposite, to actively allow inheritance for selected tags,
3017 see the variable `org-use-tag-inheritance'."
3018 :group 'org-tags
3019 :type '(repeat (string :tag "Tag")))
3021 (defun org-tag-inherit-p (tag)
3022 "Check if TAG is one that should be inherited."
3023 (cond
3024 ((member tag org-tags-exclude-from-inheritance) nil)
3025 ((eq org-use-tag-inheritance t) t)
3026 ((not org-use-tag-inheritance) nil)
3027 ((stringp org-use-tag-inheritance)
3028 (string-match org-use-tag-inheritance tag))
3029 ((listp org-use-tag-inheritance)
3030 (member tag org-use-tag-inheritance))
3031 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3033 (defcustom org-tags-match-list-sublevels t
3034 "Non-nil means list also sublevels of headlines matching a search.
3035 This variable applies to tags/property searches, and also to stuck
3036 projects because this search is based on a tags match as well.
3038 When set to the symbol `indented', sublevels are indented with
3039 leading dots.
3041 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3042 the sublevels of a headline matching a tag search often also match
3043 the same search. Listing all of them can create very long lists.
3044 Setting this variable to nil causes subtrees of a match to be skipped.
3046 This variable is semi-obsolete and probably should always be true. It
3047 is better to limit inheritance to certain tags using the variables
3048 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3049 :group 'org-tags
3050 :type '(choice
3051 (const :tag "No, don't list them" nil)
3052 (const :tag "Yes, do list them" t)
3053 (const :tag "List them, indented with leading dots" indented)))
3055 (defcustom org-tags-sort-function nil
3056 "When set, tags are sorted using this function as a comparator."
3057 :group 'org-tags
3058 :type '(choice
3059 (const :tag "No sorting" nil)
3060 (const :tag "Alphabetical" string<)
3061 (const :tag "Reverse alphabetical" string>)
3062 (function :tag "Custom function" nil)))
3064 (defvar org-tags-history nil
3065 "History of minibuffer reads for tags.")
3066 (defvar org-last-tags-completion-table nil
3067 "The last used completion table for tags.")
3068 (defvar org-after-tags-change-hook nil
3069 "Hook that is run after the tags in a line have changed.")
3071 (defgroup org-properties nil
3072 "Options concerning properties in Org-mode."
3073 :tag "Org Properties"
3074 :group 'org)
3076 (defcustom org-property-format "%-10s %s"
3077 "How property key/value pairs should be formatted by `indent-line'.
3078 When `indent-line' hits a property definition, it will format the line
3079 according to this format, mainly to make sure that the values are
3080 lined-up with respect to each other."
3081 :group 'org-properties
3082 :type 'string)
3084 (defcustom org-properties-postprocess-alist nil
3085 "Alist of properties and functions to adjust inserted values.
3086 Elements of this alist must be of the form
3088 ([string] [function])
3090 where [string] must be a property name and [function] must be a
3091 lambda expression: this lambda expression must take one argument,
3092 the value to adjust, and return the new value as a string.
3094 For example, this element will allow the property \"Remaining\"
3095 to be updated wrt the relation between the \"Effort\" property
3096 and the clock summary:
3098 ((\"Remaining\" (lambda(value)
3099 (let ((clocksum (org-clock-sum-current-item))
3100 (effort (org-duration-string-to-minutes
3101 (org-entry-get (point) \"Effort\"))))
3102 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3103 :group 'org-properties
3104 :version "24.1"
3105 :type '(alist :key-type (string :tag "Property")
3106 :value-type (function :tag "Function")))
3108 (defcustom org-use-property-inheritance nil
3109 "Non-nil means properties apply also for sublevels.
3111 This setting is chiefly used during property searches. Turning it on can
3112 cause significant overhead when doing a search, which is why it is not
3113 on by default.
3115 When nil, only the properties directly given in the current entry count.
3116 When t, every property is inherited. The value may also be a list of
3117 properties that should have inheritance, or a regular expression matching
3118 properties that should be inherited.
3120 However, note that some special properties use inheritance under special
3121 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3122 and the properties ending in \"_ALL\" when they are used as descriptor
3123 for valid values of a property.
3125 Note for programmers:
3126 When querying an entry with `org-entry-get', you can control if inheritance
3127 should be used. By default, `org-entry-get' looks only at the local
3128 properties. You can request inheritance by setting the inherit argument
3129 to t (to force inheritance) or to `selective' (to respect the setting
3130 in this variable)."
3131 :group 'org-properties
3132 :type '(choice
3133 (const :tag "Not" nil)
3134 (const :tag "Always" t)
3135 (repeat :tag "Specific properties" (string :tag "Property"))
3136 (regexp :tag "Properties matched by regexp")))
3138 (defun org-property-inherit-p (property)
3139 "Check if PROPERTY is one that should be inherited."
3140 (cond
3141 ((eq org-use-property-inheritance t) t)
3142 ((not org-use-property-inheritance) nil)
3143 ((stringp org-use-property-inheritance)
3144 (string-match org-use-property-inheritance property))
3145 ((listp org-use-property-inheritance)
3146 (member property org-use-property-inheritance))
3147 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3149 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3150 "The default column format, if no other format has been defined.
3151 This variable can be set on the per-file basis by inserting a line
3153 #+COLUMNS: %25ITEM ....."
3154 :group 'org-properties
3155 :type 'string)
3157 (defcustom org-columns-ellipses ".."
3158 "The ellipses to be used when a field in column view is truncated.
3159 When this is the empty string, as many characters as possible are shown,
3160 but then there will be no visual indication that the field has been truncated.
3161 When this is a string of length N, the last N characters of a truncated
3162 field are replaced by this string. If the column is narrower than the
3163 ellipses string, only part of the ellipses string will be shown."
3164 :group 'org-properties
3165 :type 'string)
3167 (defcustom org-columns-modify-value-for-display-function nil
3168 "Function that modifies values for display in column view.
3169 For example, it can be used to cut out a certain part from a time stamp.
3170 The function must take 2 arguments:
3172 column-title The title of the column (*not* the property name)
3173 value The value that should be modified.
3175 The function should return the value that should be displayed,
3176 or nil if the normal value should be used."
3177 :group 'org-properties
3178 :type 'function)
3180 (defcustom org-effort-property "Effort"
3181 "The property that is being used to keep track of effort estimates.
3182 Effort estimates given in this property need to have the format H:MM."
3183 :group 'org-properties
3184 :group 'org-progress
3185 :type '(string :tag "Property"))
3187 (defconst org-global-properties-fixed
3188 '(("VISIBILITY_ALL" . "folded children content all")
3189 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3190 "List of property/value pairs that can be inherited by any entry.
3192 These are fixed values, for the preset properties. The user variable
3193 that can be used to add to this list is `org-global-properties'.
3195 The entries in this list are cons cells where the car is a property
3196 name and cdr is a string with the value. If the value represents
3197 multiple items like an \"_ALL\" property, separate the items by
3198 spaces.")
3200 (defcustom org-global-properties nil
3201 "List of property/value pairs that can be inherited by any entry.
3203 This list will be combined with the constant `org-global-properties-fixed'.
3205 The entries in this list are cons cells where the car is a property
3206 name and cdr is a string with the value.
3208 You can set buffer-local values for the same purpose in the variable
3209 `org-file-properties' this by adding lines like
3211 #+PROPERTY: NAME VALUE"
3212 :group 'org-properties
3213 :type '(repeat
3214 (cons (string :tag "Property")
3215 (string :tag "Value"))))
3217 (defvar org-file-properties nil
3218 "List of property/value pairs that can be inherited by any entry.
3219 Valid for the current buffer.
3220 This variable is populated from #+PROPERTY lines.")
3221 (make-variable-buffer-local 'org-file-properties)
3223 (defgroup org-agenda nil
3224 "Options concerning agenda views in Org-mode."
3225 :tag "Org Agenda"
3226 :group 'org)
3228 (defvar org-category nil
3229 "Variable used by org files to set a category for agenda display.
3230 Such files should use a file variable to set it, for example
3232 # -*- mode: org; org-category: \"ELisp\"
3234 or contain a special line
3236 #+CATEGORY: ELisp
3238 If the file does not specify a category, then file's base name
3239 is used instead.")
3240 (make-variable-buffer-local 'org-category)
3241 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3243 (defcustom org-agenda-files nil
3244 "The files to be used for agenda display.
3245 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3246 \\[org-remove-file]. You can also use customize to edit the list.
3248 If an entry is a directory, all files in that directory that are matched by
3249 `org-agenda-file-regexp' will be part of the file list.
3251 If the value of the variable is not a list but a single file name, then
3252 the list of agenda files is actually stored and maintained in that file, one
3253 agenda file per line. In this file paths can be given relative to
3254 `org-directory'. Tilde expansion and environment variable substitution
3255 are also made."
3256 :group 'org-agenda
3257 :type '(choice
3258 (repeat :tag "List of files and directories" file)
3259 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3261 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3262 "Regular expression to match files for `org-agenda-files'.
3263 If any element in the list in that variable contains a directory instead
3264 of a normal file, all files in that directory that are matched by this
3265 regular expression will be included."
3266 :group 'org-agenda
3267 :type 'regexp)
3269 (defcustom org-agenda-text-search-extra-files nil
3270 "List of extra files to be searched by text search commands.
3271 These files will be search in addition to the agenda files by the
3272 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3273 Note that these files will only be searched for text search commands,
3274 not for the other agenda views like todo lists, tag searches or the weekly
3275 agenda. This variable is intended to list notes and possibly archive files
3276 that should also be searched by these two commands.
3277 In fact, if the first element in the list is the symbol `agenda-archives',
3278 than all archive files of all agenda files will be added to the search
3279 scope."
3280 :group 'org-agenda
3281 :type '(set :greedy t
3282 (const :tag "Agenda Archives" agenda-archives)
3283 (repeat :inline t (file))))
3285 (if (fboundp 'defvaralias)
3286 (defvaralias 'org-agenda-multi-occur-extra-files
3287 'org-agenda-text-search-extra-files))
3289 (defcustom org-agenda-skip-unavailable-files nil
3290 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3291 A nil value means to remove them, after a query, from the list."
3292 :group 'org-agenda
3293 :type 'boolean)
3295 (defcustom org-calendar-to-agenda-key [?c]
3296 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3297 The command `org-calendar-goto-agenda' will be bound to this key. The
3298 default is the character `c' because then `c' can be used to switch back and
3299 forth between agenda and calendar."
3300 :group 'org-agenda
3301 :type 'sexp)
3303 (defcustom org-calendar-agenda-action-key [?k]
3304 "The key to be installed in `calendar-mode-map' for agenda-action.
3305 The command `org-agenda-action' will be bound to this key. The
3306 default is the character `k' because we use the same key in the agenda."
3307 :group 'org-agenda
3308 :type 'sexp)
3310 (defcustom org-calendar-insert-diary-entry-key [?i]
3311 "The key to be installed in `calendar-mode-map' for adding diary entries.
3312 This option is irrelevant until `org-agenda-diary-file' has been configured
3313 to point to an Org-mode file. When that is the case, the command
3314 `org-agenda-diary-entry' will be bound to the key given here, by default
3315 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3316 if you want to continue doing this, you need to change this to a different
3317 key."
3318 :group 'org-agenda
3319 :type 'sexp)
3321 (defcustom org-agenda-diary-file 'diary-file
3322 "File to which to add new entries with the `i' key in agenda and calendar.
3323 When this is the symbol `diary-file', the functionality in the Emacs
3324 calendar will be used to add entries to the `diary-file'. But when this
3325 points to a file, `org-agenda-diary-entry' will be used instead."
3326 :group 'org-agenda
3327 :type '(choice
3328 (const :tag "The standard Emacs diary file" diary-file)
3329 (file :tag "Special Org file diary entries")))
3331 (eval-after-load "calendar"
3332 '(progn
3333 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3334 'org-calendar-goto-agenda)
3335 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3336 'org-agenda-action)
3337 (add-hook 'calendar-mode-hook
3338 (lambda ()
3339 (unless (eq org-agenda-diary-file 'diary-file)
3340 (define-key calendar-mode-map
3341 org-calendar-insert-diary-entry-key
3342 'org-agenda-diary-entry))))))
3344 (defgroup org-latex nil
3345 "Options for embedding LaTeX code into Org-mode."
3346 :tag "Org LaTeX"
3347 :group 'org)
3349 (defcustom org-format-latex-options
3350 '(:foreground default :background default :scale 1.0
3351 :html-foreground "Black" :html-background "Transparent"
3352 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3353 "Options for creating images from LaTeX fragments.
3354 This is a property list with the following properties:
3355 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3356 `default' means use the foreground of the default face.
3357 :background the background color, or \"Transparent\".
3358 `default' means use the background of the default face.
3359 :scale a scaling factor for the size of the images, to get more pixels
3360 :html-foreground, :html-background, :html-scale
3361 the same numbers for HTML export.
3362 :matchers a list indicating which matchers should be used to
3363 find LaTeX fragments. Valid members of this list are:
3364 \"begin\" find environments
3365 \"$1\" find single characters surrounded by $.$
3366 \"$\" find math expressions surrounded by $...$
3367 \"$$\" find math expressions surrounded by $$....$$
3368 \"\\(\" find math expressions surrounded by \\(...\\)
3369 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3370 :group 'org-latex
3371 :type 'plist)
3373 (defcustom org-format-latex-signal-error t
3374 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3375 When nil, just push out a message."
3376 :group 'org-latex
3377 :version "24.1"
3378 :type 'boolean)
3380 (defcustom org-latex-to-mathml-jar-file nil
3381 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3382 Use this to specify additional executable file say a jar file.
3384 When using MathToWeb as the converter, specify the full-path to
3385 your mathtoweb.jar file."
3386 :group 'org-latex
3387 :version "24.1"
3388 :type '(choice
3389 (const :tag "None" nil)
3390 (file :tag "JAR file" :must-match t)))
3392 (defcustom org-latex-to-mathml-convert-command nil
3393 "Command to convert LaTeX fragments to MathML.
3394 Replace format-specifiers in the command as noted below and use
3395 `shell-command' to convert LaTeX to MathML.
3396 %j: Executable file in fully expanded form as specified by
3397 `org-latex-to-mathml-jar-file'.
3398 %I: Input LaTeX file in fully expanded form
3399 %o: Output MathML file
3400 This command is used by `org-create-math-formula'.
3402 When using MathToWeb as the converter, set this to
3403 \"java -jar %j -unicode -force -df %o %I\"."
3404 :group 'org-latex
3405 :version "24.1"
3406 :type '(choice
3407 (const :tag "None" nil)
3408 (string :tag "\nShell command")))
3410 (defcustom org-latex-create-formula-image-program 'dvipng
3411 "Program to convert LaTeX fragments with.
3413 dvipng Process the LaTeX fragments to dvi file, then convert
3414 dvi files to png files using dvipng.
3415 This will also include processing of non-math environments.
3416 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3417 to convert pdf files to png files"
3418 :group 'org-latex
3419 :version "24.1"
3420 :type '(choice
3421 (const :tag "dvipng" dvipng)
3422 (const :tag "imagemagick" imagemagick)))
3424 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3425 "Path to store latex preview images. A relative path here creates many
3426 directories relative to the processed org files paths. An absolute path
3427 puts all preview images at the same place."
3428 :group 'org-latex
3429 ;; :version "24.3"
3430 :type 'string)
3432 (defun org-format-latex-mathml-available-p ()
3433 "Return t if `org-latex-to-mathml-convert-command' is usable."
3434 (save-match-data
3435 (when (and (boundp 'org-latex-to-mathml-convert-command)
3436 org-latex-to-mathml-convert-command)
3437 (let ((executable (car (split-string
3438 org-latex-to-mathml-convert-command))))
3439 (when (executable-find executable)
3440 (if (string-match
3441 "%j" org-latex-to-mathml-convert-command)
3442 (file-readable-p org-latex-to-mathml-jar-file)
3443 t))))))
3445 (defcustom org-format-latex-header "\\documentclass{article}
3446 \\usepackage[usenames]{color}
3447 \\usepackage{amsmath}
3448 \\usepackage[mathscr]{eucal}
3449 \\pagestyle{empty} % do not remove
3450 \[PACKAGES]
3451 \[DEFAULT-PACKAGES]
3452 % The settings below are copied from fullpage.sty
3453 \\setlength{\\textwidth}{\\paperwidth}
3454 \\addtolength{\\textwidth}{-3cm}
3455 \\setlength{\\oddsidemargin}{1.5cm}
3456 \\addtolength{\\oddsidemargin}{-2.54cm}
3457 \\setlength{\\evensidemargin}{\\oddsidemargin}
3458 \\setlength{\\textheight}{\\paperheight}
3459 \\addtolength{\\textheight}{-\\headheight}
3460 \\addtolength{\\textheight}{-\\headsep}
3461 \\addtolength{\\textheight}{-\\footskip}
3462 \\addtolength{\\textheight}{-3cm}
3463 \\setlength{\\topmargin}{1.5cm}
3464 \\addtolength{\\topmargin}{-2.54cm}"
3465 "The document header used for processing LaTeX fragments.
3466 It is imperative that this header make sure that no page number
3467 appears on the page. The package defined in the variables
3468 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3469 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3470 will be appended."
3471 :group 'org-latex
3472 :type 'string)
3474 (defvar org-format-latex-header-extra nil)
3476 (defun org-set-packages-alist (var val)
3477 "Set the packages alist and make sure it has 3 elements per entry."
3478 (set var (mapcar (lambda (x)
3479 (if (and (consp x) (= (length x) 2))
3480 (list (car x) (nth 1 x) t)
3482 val)))
3484 (defun org-get-packages-alist (var)
3486 "Get the packages alist and make sure it has 3 elements per entry."
3487 (mapcar (lambda (x)
3488 (if (and (consp x) (= (length x) 2))
3489 (list (car x) (nth 1 x) t)
3491 (default-value var)))
3493 ;; The following variables are defined here because is it also used
3494 ;; when formatting latex fragments. Originally it was part of the
3495 ;; LaTeX exporter, which is why the name includes "export".
3496 (defcustom org-export-latex-default-packages-alist
3497 '(("AUTO" "inputenc" t)
3498 ("T1" "fontenc" t)
3499 ("" "fixltx2e" nil)
3500 ("" "graphicx" t)
3501 ("" "longtable" nil)
3502 ("" "float" nil)
3503 ("" "wrapfig" nil)
3504 ("" "soul" t)
3505 ("" "textcomp" t)
3506 ("" "marvosym" t)
3507 ("" "wasysym" t)
3508 ("" "latexsym" t)
3509 ("" "amssymb" t)
3510 ("" "hyperref" nil)
3511 "\\tolerance=1000"
3513 "Alist of default packages to be inserted in the header.
3514 Change this only if one of the packages here causes an incompatibility
3515 with another package you are using.
3516 The packages in this list are needed by one part or another of Org-mode
3517 to function properly.
3519 - inputenc, fontenc: for basic font and character selection
3520 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3521 for interpreting the entities in `org-entities'. You can skip some of these
3522 packages if you don't use any of the symbols in it.
3523 - graphicx: for including images
3524 - float, wrapfig: for figure placement
3525 - longtable: for long tables
3526 - hyperref: for cross references
3528 Therefore you should not modify this variable unless you know what you
3529 are doing. The one reason to change it anyway is that you might be loading
3530 some other package that conflicts with one of the default packages.
3531 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3532 If SNIPPET-FLAG is t, the package also needs to be included when
3533 compiling LaTeX snippets into images for inclusion into HTML."
3534 :group 'org-export-latex
3535 :set 'org-set-packages-alist
3536 :get 'org-get-packages-alist
3537 :version "24.1"
3538 :type '(repeat
3539 (choice
3540 (list :tag "options/package pair"
3541 (string :tag "options")
3542 (string :tag "package")
3543 (boolean :tag "Snippet"))
3544 (string :tag "A line of LaTeX"))))
3546 (defcustom org-export-latex-packages-alist nil
3547 "Alist of packages to be inserted in every LaTeX header.
3548 These will be inserted after `org-export-latex-default-packages-alist'.
3549 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3550 SNIPPET-FLAG, when t, indicates that this package is also needed when
3551 turning LaTeX snippets into images for inclusion into HTML.
3552 Make sure that you only list packages here which:
3553 - you want in every file
3554 - do not conflict with the default packages in
3555 `org-export-latex-default-packages-alist'
3556 - do not conflict with the setup in `org-format-latex-header'."
3557 :group 'org-export-latex
3558 :set 'org-set-packages-alist
3559 :get 'org-get-packages-alist
3560 :type '(repeat
3561 (choice
3562 (list :tag "options/package pair"
3563 (string :tag "options")
3564 (string :tag "package")
3565 (boolean :tag "Snippet"))
3566 (string :tag "A line of LaTeX"))))
3569 (defgroup org-appearance nil
3570 "Settings for Org-mode appearance."
3571 :tag "Org Appearance"
3572 :group 'org)
3574 (defcustom org-level-color-stars-only nil
3575 "Non-nil means fontify only the stars in each headline.
3576 When nil, the entire headline is fontified.
3577 Changing it requires restart of `font-lock-mode' to become effective
3578 also in regions already fontified."
3579 :group 'org-appearance
3580 :type 'boolean)
3582 (defcustom org-hide-leading-stars nil
3583 "Non-nil means hide the first N-1 stars in a headline.
3584 This works by using the face `org-hide' for these stars. This
3585 face is white for a light background, and black for a dark
3586 background. You may have to customize the face `org-hide' to
3587 make this work.
3588 Changing it requires restart of `font-lock-mode' to become effective
3589 also in regions already fontified.
3590 You may also set this on a per-file basis by adding one of the following
3591 lines to the buffer:
3593 #+STARTUP: hidestars
3594 #+STARTUP: showstars"
3595 :group 'org-appearance
3596 :type 'boolean)
3598 (defcustom org-hidden-keywords nil
3599 "List of symbols corresponding to keywords to be hidden the org buffer.
3600 For example, a value '(title) for this list will make the document's title
3601 appear in the buffer without the initial #+TITLE: keyword."
3602 :group 'org-appearance
3603 :version "24.1"
3604 :type '(set (const :tag "#+AUTHOR" author)
3605 (const :tag "#+DATE" date)
3606 (const :tag "#+EMAIL" email)
3607 (const :tag "#+TITLE" title)))
3609 (defcustom org-custom-properties nil
3610 "List of properties (as strings) with a special meaning.
3611 The default use of these custom properties is to let the user
3612 hide them with `org-toggle-custom-properties-visibility'."
3613 :group 'org-properties
3614 :group 'org-appearance
3615 ;; :version "24.3"
3616 :type '(repeat (string :tag "Property Name")))
3618 (defcustom org-fontify-done-headline nil
3619 "Non-nil means change the face of a headline if it is marked DONE.
3620 Normally, only the TODO/DONE keyword indicates the state of a headline.
3621 When this is non-nil, the headline after the keyword is set to the
3622 `org-headline-done' as an additional indication."
3623 :group 'org-appearance
3624 :type 'boolean)
3626 (defcustom org-fontify-emphasized-text t
3627 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3628 Changing this variable requires a restart of Emacs to take effect."
3629 :group 'org-appearance
3630 :type 'boolean)
3632 (defcustom org-fontify-whole-heading-line nil
3633 "Non-nil means fontify the whole line for headings.
3634 This is useful when setting a background color for the
3635 org-level-* faces."
3636 :group 'org-appearance
3637 :type 'boolean)
3639 (defcustom org-highlight-latex-fragments-and-specials nil
3640 "Non-nil means fontify what is treated specially by the exporters."
3641 :group 'org-appearance
3642 :type 'boolean)
3644 (defcustom org-hide-emphasis-markers nil
3645 "Non-nil mean font-lock should hide the emphasis marker characters."
3646 :group 'org-appearance
3647 :type 'boolean)
3649 (defcustom org-pretty-entities nil
3650 "Non-nil means show entities as UTF8 characters.
3651 When nil, the \\name form remains in the buffer."
3652 :group 'org-appearance
3653 :version "24.1"
3654 :type 'boolean)
3656 (defcustom org-pretty-entities-include-sub-superscripts t
3657 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3658 :group 'org-appearance
3659 :version "24.1"
3660 :type 'boolean)
3662 (defvar org-emph-re nil
3663 "Regular expression for matching emphasis.
3664 After a match, the match groups contain these elements:
3665 0 The match of the full regular expression, including the characters
3666 before and after the proper match
3667 1 The character before the proper match, or empty at beginning of line
3668 2 The proper match, including the leading and trailing markers
3669 3 The leading marker like * or /, indicating the type of highlighting
3670 4 The text between the emphasis markers, not including the markers
3671 5 The character after the match, empty at the end of a line")
3672 (defvar org-verbatim-re nil
3673 "Regular expression for matching verbatim text.")
3674 (defvar org-emphasis-regexp-components) ; defined just below
3675 (defvar org-emphasis-alist) ; defined just below
3676 (defun org-set-emph-re (var val)
3677 "Set variable and compute the emphasis regular expression."
3678 (set var val)
3679 (when (and (boundp 'org-emphasis-alist)
3680 (boundp 'org-emphasis-regexp-components)
3681 org-emphasis-alist org-emphasis-regexp-components)
3682 (let* ((e org-emphasis-regexp-components)
3683 (pre (car e))
3684 (post (nth 1 e))
3685 (border (nth 2 e))
3686 (body (nth 3 e))
3687 (nl (nth 4 e))
3688 (body1 (concat body "*?"))
3689 (markers (mapconcat 'car org-emphasis-alist ""))
3690 (vmarkers (mapconcat
3691 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3692 org-emphasis-alist "")))
3693 ;; make sure special characters appear at the right position in the class
3694 (if (string-match "\\^" markers)
3695 (setq markers (concat (replace-match "" t t markers) "^")))
3696 (if (string-match "-" markers)
3697 (setq markers (concat (replace-match "" t t markers) "-")))
3698 (if (string-match "\\^" vmarkers)
3699 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3700 (if (string-match "-" vmarkers)
3701 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3702 (if (> nl 0)
3703 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3704 (int-to-string nl) "\\}")))
3705 ;; Make the regexp
3706 (setq org-emph-re
3707 (concat "\\([" pre "]\\|^\\)"
3708 "\\("
3709 "\\([" markers "]\\)"
3710 "\\("
3711 "[^" border "]\\|"
3712 "[^" border "]"
3713 body1
3714 "[^" border "]"
3715 "\\)"
3716 "\\3\\)"
3717 "\\([" post "]\\|$\\)"))
3718 (setq org-verbatim-re
3719 (concat "\\([" pre "]\\|^\\)"
3720 "\\("
3721 "\\([" vmarkers "]\\)"
3722 "\\("
3723 "[^" border "]\\|"
3724 "[^" border "]"
3725 body1
3726 "[^" border "]"
3727 "\\)"
3728 "\\3\\)"
3729 "\\([" post "]\\|$\\)")))))
3731 (defcustom org-emphasis-regexp-components
3732 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3733 "Components used to build the regular expression for emphasis.
3734 This is a list with five entries. Terminology: In an emphasis string
3735 like \" *strong word* \", we call the initial space PREMATCH, the final
3736 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3737 and \"trong wor\" is the body. The different components in this variable
3738 specify what is allowed/forbidden in each part:
3740 pre Chars allowed as prematch. Beginning of line will be allowed too.
3741 post Chars allowed as postmatch. End of line will be allowed too.
3742 border The chars *forbidden* as border characters.
3743 body-regexp A regexp like \".\" to match a body character. Don't use
3744 non-shy groups here, and don't allow newline here.
3745 newline The maximum number of newlines allowed in an emphasis exp.
3747 Use customize to modify this, or restart Emacs after changing it."
3748 :group 'org-appearance
3749 :set 'org-set-emph-re
3750 :type '(list
3751 (sexp :tag "Allowed chars in pre ")
3752 (sexp :tag "Allowed chars in post ")
3753 (sexp :tag "Forbidden chars in border ")
3754 (sexp :tag "Regexp for body ")
3755 (integer :tag "number of newlines allowed")
3756 (option (boolean :tag "Please ignore this button"))))
3758 (defcustom org-emphasis-alist
3759 `(("*" bold "<b>" "</b>")
3760 ("/" italic "<i>" "</i>")
3761 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3762 ("=" org-code "<code>" "</code>" verbatim)
3763 ("~" org-verbatim "<code>" "</code>" verbatim)
3764 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3765 "<del>" "</del>")
3767 "Special syntax for emphasized text.
3768 Text starting and ending with a special character will be emphasized, for
3769 example *bold*, _underlined_ and /italic/. This variable sets the marker
3770 characters, the face to be used by font-lock for highlighting in Org-mode
3771 Emacs buffers, and the HTML tags to be used for this.
3772 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3773 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3774 Use customize to modify this, or restart Emacs after changing it."
3775 :group 'org-appearance
3776 :set 'org-set-emph-re
3777 :type '(repeat
3778 (list
3779 (string :tag "Marker character")
3780 (choice
3781 (face :tag "Font-lock-face")
3782 (plist :tag "Face property list"))
3783 (string :tag "HTML start tag")
3784 (string :tag "HTML end tag")
3785 (option (const verbatim)))))
3787 (defvar org-protecting-blocks
3788 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3789 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3790 This is needed for font-lock setup.")
3792 ;;; Miscellaneous options
3794 (defgroup org-completion nil
3795 "Completion in Org-mode."
3796 :tag "Org Completion"
3797 :group 'org)
3799 (defcustom org-completion-use-ido nil
3800 "Non-nil means use ido completion wherever possible.
3801 Note that `ido-mode' must be active for this variable to be relevant.
3802 If you decide to turn this variable on, you might well want to turn off
3803 `org-outline-path-complete-in-steps'.
3804 See also `org-completion-use-iswitchb'."
3805 :group 'org-completion
3806 :type 'boolean)
3808 (defcustom org-completion-use-iswitchb nil
3809 "Non-nil means use iswitchb completion wherever possible.
3810 Note that `iswitchb-mode' must be active for this variable to be relevant.
3811 If you decide to turn this variable on, you might well want to turn off
3812 `org-outline-path-complete-in-steps'.
3813 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3814 :group 'org-completion
3815 :type 'boolean)
3817 (defcustom org-completion-fallback-command 'hippie-expand
3818 "The expansion command called by \\[pcomplete] in normal context.
3819 Normal means, no org-mode-specific context."
3820 :group 'org-completion
3821 :type 'function)
3823 ;;; Functions and variables from their packages
3824 ;; Declared here to avoid compiler warnings
3826 ;; XEmacs only
3827 (defvar outline-mode-menu-heading)
3828 (defvar outline-mode-menu-show)
3829 (defvar outline-mode-menu-hide)
3830 (defvar zmacs-regions) ; XEmacs regions
3832 ;; Emacs only
3833 (defvar mark-active)
3835 ;; Various packages
3836 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3837 (declare-function calendar-forward-day "cal-move" (arg))
3838 (declare-function calendar-goto-date "cal-move" (date))
3839 (declare-function calendar-goto-today "cal-move" ())
3840 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3841 (defvar calc-embedded-close-formula)
3842 (defvar calc-embedded-open-formula)
3843 (declare-function cdlatex-tab "ext:cdlatex" ())
3844 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3845 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3846 (defvar font-lock-unfontify-region-function)
3847 (declare-function iswitchb-read-buffer "iswitchb"
3848 (prompt &optional default require-match start matches-set))
3849 (defvar iswitchb-temp-buflist)
3850 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3851 (defvar org-agenda-tags-todo-honor-ignore-options)
3852 (declare-function org-agenda-skip "org-agenda" ())
3853 (declare-function
3854 org-agenda-format-item "org-agenda"
3855 (extra txt &optional category tags dotime noprefix remove-re habitp))
3856 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3857 (declare-function org-agenda-change-all-lines "org-agenda"
3858 (newhead hdmarker &optional fixface just-this))
3859 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3860 (declare-function org-agenda-maybe-redo "org-agenda" ())
3861 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3862 (beg end))
3863 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3864 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3865 "org-agenda" (&optional end))
3866 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3867 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3868 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3869 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3870 (declare-function org-indent-mode "org-indent" (&optional arg))
3871 (declare-function parse-time-string "parse-time" (string))
3872 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3873 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3874 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3875 (defvar remember-data-file)
3876 (defvar texmathp-why)
3877 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3878 (declare-function table--at-cell-p "table" (position &optional object at-column))
3880 (defvar w3m-current-url)
3881 (defvar w3m-current-title)
3883 (defvar org-latex-regexps)
3885 ;;; Autoload and prepare some org modules
3887 ;; Some table stuff that needs to be defined here, because it is used
3888 ;; by the functions setting up org-mode or checking for table context.
3890 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3891 "Detect an org-type or table-type table.")
3892 (defconst org-table-line-regexp "^[ \t]*|"
3893 "Detect an org-type table line.")
3894 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3895 "Detect an org-type table line.")
3896 (defconst org-table-hline-regexp "^[ \t]*|-"
3897 "Detect an org-type table hline.")
3898 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3899 "Detect a table-type table hline.")
3900 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3901 "Detect the first line outside a table when searching from within it.
3902 This works for both table types.")
3904 ;; Autoload the functions in org-table.el that are needed by functions here.
3906 (eval-and-compile
3907 (org-autoload "org-table"
3908 '(org-table-align org-table-begin org-table-blank-field
3909 org-table-convert org-table-convert-region org-table-copy-down
3910 org-table-copy-region org-table-create
3911 org-table-create-or-convert-from-region
3912 org-table-create-with-table.el org-table-current-dline
3913 org-table-cut-region org-table-delete-column org-table-edit-field
3914 org-table-edit-formulas org-table-end org-table-eval-formula
3915 org-table-export org-table-field-info
3916 org-table-get-stored-formulas org-table-goto-column
3917 org-table-hline-and-move org-table-import org-table-insert-column
3918 org-table-insert-hline org-table-insert-row org-table-iterate
3919 org-table-justify-field-maybe org-table-kill-row
3920 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3921 org-table-move-column org-table-move-column-left
3922 org-table-move-column-right org-table-move-row
3923 org-table-move-row-down org-table-move-row-up
3924 org-table-next-field org-table-next-row org-table-paste-rectangle
3925 org-table-previous-field org-table-recalculate
3926 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3927 org-table-toggle-coordinate-overlays
3928 org-table-toggle-formula-debugger org-table-wrap-region
3929 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3930 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3931 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3933 (defun org-at-table-p (&optional table-type)
3934 "Return t if the cursor is inside an org-type table.
3935 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3936 (if org-enable-table-editor
3937 (save-excursion
3938 (beginning-of-line 1)
3939 (looking-at (if table-type org-table-any-line-regexp
3940 org-table-line-regexp)))
3941 nil))
3942 (defsubst org-table-p () (org-at-table-p))
3944 (defun org-at-table.el-p ()
3945 "Return t if and only if we are at a table.el table."
3946 (and (org-at-table-p 'any)
3947 (save-excursion
3948 (goto-char (org-table-begin 'any))
3949 (looking-at org-table1-hline-regexp))))
3950 (defun org-table-recognize-table.el ()
3951 "If there is a table.el table nearby, recognize it and move into it."
3952 (if org-table-tab-recognizes-table.el
3953 (if (org-at-table.el-p)
3954 (progn
3955 (beginning-of-line 1)
3956 (if (looking-at org-table-dataline-regexp)
3958 (if (looking-at org-table1-hline-regexp)
3959 (progn
3960 (beginning-of-line 2)
3961 (if (looking-at org-table-any-border-regexp)
3962 (beginning-of-line -1)))))
3963 (if (re-search-forward "|" (org-table-end t) t)
3964 (progn
3965 (require 'table)
3966 (if (table--at-cell-p (point))
3968 (message "recognizing table.el table...")
3969 (table-recognize-table)
3970 (message "recognizing table.el table...done")))
3971 (error "This should not happen"))
3973 nil)
3974 nil))
3976 (defun org-at-table-hline-p ()
3977 "Return t if the cursor is inside a hline in a table."
3978 (if org-enable-table-editor
3979 (save-excursion
3980 (beginning-of-line 1)
3981 (looking-at org-table-hline-regexp))
3982 nil))
3984 (defvar org-table-clean-did-remove-column nil)
3986 (defun org-table-map-tables (function &optional quietly)
3987 "Apply FUNCTION to the start of all tables in the buffer."
3988 (save-excursion
3989 (save-restriction
3990 (widen)
3991 (goto-char (point-min))
3992 (while (re-search-forward org-table-any-line-regexp nil t)
3993 (unless quietly
3994 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3995 (beginning-of-line 1)
3996 (when (and (looking-at org-table-line-regexp)
3997 ;; Exclude tables in src/example/verbatim/clocktable blocks
3998 (not (org-in-block-p '("src" "example"))))
3999 (save-excursion (funcall function))
4000 (or (looking-at org-table-line-regexp)
4001 (forward-char 1)))
4002 (re-search-forward org-table-any-border-regexp nil 1))))
4003 (unless quietly (message "Mapping tables: done")))
4005 ;; Declare and autoload functions from org-exp.el & Co
4007 (declare-function org-default-export-plist "org-exp")
4008 (declare-function org-infile-export-plist "org-exp")
4009 (declare-function org-get-current-options "org-exp")
4010 (eval-and-compile
4011 (org-autoload "org-exp"
4012 '(org-export org-export-visible
4013 org-insert-export-options-template
4014 org-table-clean-before-export))
4015 (org-autoload "org-ascii"
4016 '(org-export-as-ascii org-export-ascii-preprocess
4017 org-export-as-ascii-to-buffer org-replace-region-by-ascii
4018 org-export-region-as-ascii))
4019 (org-autoload "org-latex"
4020 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4021 org-replace-region-by-latex org-export-region-as-latex
4022 org-export-as-latex org-export-as-pdf
4023 org-export-as-pdf-and-open))
4024 (org-autoload "org-html"
4025 '(org-export-as-html-and-open
4026 org-export-as-html-batch org-export-as-html-to-buffer
4027 org-replace-region-by-html org-export-region-as-html
4028 org-export-as-html))
4029 (org-autoload "org-docbook"
4030 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4031 org-replace-region-by-docbook org-export-region-as-docbook
4032 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4033 org-export-as-docbook))
4034 (org-autoload "org-icalendar"
4035 '(org-export-icalendar-this-file
4036 org-export-icalendar-all-agenda-files
4037 org-export-icalendar-combine-agenda-files))
4038 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4039 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4041 ;; Declare and autoload functions from org-agenda.el
4043 (eval-and-compile
4044 (org-autoload "org-agenda"
4045 '(org-agenda org-agenda-list org-search-view
4046 org-todo-list org-tags-view org-agenda-list-stuck-projects
4047 org-diary org-agenda-to-appt
4048 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4050 ;; Autoload org-remember
4052 (eval-and-compile
4053 (org-autoload "org-remember"
4054 '(org-remember-insinuate org-remember-annotation
4055 org-remember-apply-template org-remember org-remember-handler)))
4057 (eval-and-compile
4058 (org-autoload "org-capture"
4059 '(org-capture org-capture-insert-template-here
4060 org-capture-import-remember-templates)))
4062 ;; Autoload org-clock.el
4064 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4065 (beg end))
4066 (declare-function org-clock-update-mode-line "org-clock" ())
4067 (declare-function org-resolve-clocks "org-clock"
4068 (&optional also-non-dangling-p prompt last-valid))
4069 (defvar org-clock-start-time)
4070 (defvar org-clock-marker (make-marker)
4071 "Marker recording the last clock-in.")
4072 (defvar org-clock-hd-marker (make-marker)
4073 "Marker recording the last clock-in, but the headline position.")
4074 (defvar org-clock-heading ""
4075 "The heading of the current clock entry.")
4076 (defun org-clock-is-active ()
4077 "Return non-nil if clock is currently running.
4078 The return value is actually the clock marker."
4079 (marker-buffer org-clock-marker))
4081 (eval-and-compile
4082 (org-autoload
4083 "org-clock"
4084 '(org-clock-in org-clock-out org-clock-cancel
4085 org-clock-goto org-clock-sum org-clock-display
4086 org-clock-remove-overlays org-clock-report
4087 org-clocktable-shift org-dblock-write:clocktable
4088 org-get-clocktable org-resolve-clocks)))
4090 (defun org-clock-update-time-maybe ()
4091 "If this is a CLOCK line, update it and return t.
4092 Otherwise, return nil."
4093 (interactive)
4094 (save-excursion
4095 (beginning-of-line 1)
4096 (skip-chars-forward " \t")
4097 (when (looking-at org-clock-string)
4098 (let ((re (concat "[ \t]*" org-clock-string
4099 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4100 "\\([ \t]*=>.*\\)?\\)?"))
4101 ts te h m s neg)
4102 (cond
4103 ((not (looking-at re))
4104 nil)
4105 ((not (match-end 2))
4106 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4107 (> org-clock-marker (point))
4108 (<= org-clock-marker (point-at-eol)))
4109 ;; The clock is running here
4110 (setq org-clock-start-time
4111 (apply 'encode-time
4112 (org-parse-time-string (match-string 1))))
4113 (org-clock-update-mode-line)))
4115 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4116 (end-of-line 1)
4117 (setq ts (match-string 1)
4118 te (match-string 3))
4119 (setq s (- (org-float-time
4120 (apply 'encode-time (org-parse-time-string te)))
4121 (org-float-time
4122 (apply 'encode-time (org-parse-time-string ts))))
4123 neg (< s 0)
4124 s (abs s)
4125 h (floor (/ s 3600))
4126 s (- s (* 3600 h))
4127 m (floor (/ s 60))
4128 s (- s (* 60 s)))
4129 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4130 t))))))
4132 (defun org-check-running-clock ()
4133 "Check if the current buffer contains the running clock.
4134 If yes, offer to stop it and to save the buffer with the changes."
4135 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4136 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4137 (buffer-name))))
4138 (org-clock-out)
4139 (when (y-or-n-p "Save changed buffer?")
4140 (save-buffer))))
4142 (defun org-clocktable-try-shift (dir n)
4143 "Check if this line starts a clock table, if yes, shift the time block."
4144 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4145 (org-clocktable-shift dir n)))
4147 ;; Autoload org-timer.el
4149 (eval-and-compile
4150 (org-autoload
4151 "org-timer"
4152 '(org-timer-start org-timer org-timer-item
4153 org-timer-change-times-in-region
4154 org-timer-set-timer
4155 org-timer-reset-timers
4156 org-timer-show-remaining-time)))
4158 ;; Autoload org-feed.el
4160 (eval-and-compile
4161 (org-autoload
4162 "org-feed"
4163 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4166 ;; Autoload org-indent.el
4168 ;; Define the variable already here, to make sure we have it.
4169 (defvar org-indent-mode nil
4170 "Non-nil if Org-Indent mode is enabled.
4171 Use the command `org-indent-mode' to change this variable.")
4173 (eval-and-compile
4174 (org-autoload
4175 "org-indent"
4176 '(org-indent-mode)))
4178 ;; Autoload org-mobile.el
4180 (eval-and-compile
4181 (org-autoload
4182 "org-mobile"
4183 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4185 ;; Autoload archiving code
4186 ;; The stuff that is needed for cycling and tags has to be defined here.
4188 (defgroup org-archive nil
4189 "Options concerning archiving in Org-mode."
4190 :tag "Org Archive"
4191 :group 'org-structure)
4193 (defcustom org-archive-location "%s_archive::"
4194 "The location where subtrees should be archived.
4196 The value of this variable is a string, consisting of two parts,
4197 separated by a double-colon. The first part is a filename and
4198 the second part is a headline.
4200 When the filename is omitted, archiving happens in the same file.
4201 %s in the filename will be replaced by the current file
4202 name (without the directory part). Archiving to a different file
4203 is useful to keep archived entries from contributing to the
4204 Org-mode Agenda.
4206 The archived entries will be filed as subtrees of the specified
4207 headline. When the headline is omitted, the subtrees are simply
4208 filed away at the end of the file, as top-level entries. Also in
4209 the heading you can use %s to represent the file name, this can be
4210 useful when using the same archive for a number of different files.
4212 Here are a few examples:
4213 \"%s_archive::\"
4214 If the current file is Projects.org, archive in file
4215 Projects.org_archive, as top-level trees. This is the default.
4217 \"::* Archived Tasks\"
4218 Archive in the current file, under the top-level headline
4219 \"* Archived Tasks\".
4221 \"~/org/archive.org::\"
4222 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4224 \"~/org/archive.org::* From %s\"
4225 Archive in file ~/org/archive.org (absolute path), under headlines
4226 \"From FILENAME\" where file name is the current file name.
4228 \"~/org/datetree.org::datetree/* Finished Tasks\"
4229 The \"datetree/\" string is special, signifying to archive
4230 items to the datetree. Items are placed in either the CLOSED
4231 date of the item, or the current date if there is no CLOSED date.
4232 The heading will be a subentry to the current date. There doesn't
4233 need to be a heading, but there always needs to be a slash after
4234 datetree. For example, to store archived items directly in the
4235 datetree, use \"~/org/datetree.org::datetree/\".
4237 \"basement::** Finished Tasks\"
4238 Archive in file ./basement (relative path), as level 3 trees
4239 below the level 2 heading \"** Finished Tasks\".
4241 You may set this option on a per-file basis by adding to the buffer a
4242 line like
4244 #+ARCHIVE: basement::** Finished Tasks
4246 You may also define it locally for a subtree by setting an ARCHIVE property
4247 in the entry. If such a property is found in an entry, or anywhere up
4248 the hierarchy, it will be used."
4249 :group 'org-archive
4250 :type 'string)
4252 (defcustom org-archive-tag "ARCHIVE"
4253 "The tag that marks a subtree as archived.
4254 An archived subtree does not open during visibility cycling, and does
4255 not contribute to the agenda listings.
4256 After changing this, font-lock must be restarted in the relevant buffers to
4257 get the proper fontification."
4258 :group 'org-archive
4259 :group 'org-keywords
4260 :type 'string)
4262 (defcustom org-agenda-skip-archived-trees t
4263 "Non-nil means the agenda will skip any items located in archived trees.
4264 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4265 variable is no longer recommended, you should leave it at the value t.
4266 Instead, use the key `v' to cycle the archives-mode in the agenda."
4267 :group 'org-archive
4268 :group 'org-agenda-skip
4269 :type 'boolean)
4271 (defcustom org-columns-skip-archived-trees t
4272 "Non-nil means ignore archived trees when creating column view."
4273 :group 'org-archive
4274 :group 'org-properties
4275 :type 'boolean)
4277 (defcustom org-cycle-open-archived-trees nil
4278 "Non-nil means `org-cycle' will open archived trees.
4279 An archived tree is a tree marked with the tag ARCHIVE.
4280 When nil, archived trees will stay folded. You can still open them with
4281 normal outline commands like `show-all', but not with the cycling commands."
4282 :group 'org-archive
4283 :group 'org-cycle
4284 :type 'boolean)
4286 (defcustom org-sparse-tree-open-archived-trees nil
4287 "Non-nil means sparse tree construction shows matches in archived trees.
4288 When nil, matches in these trees are highlighted, but the trees are kept in
4289 collapsed state."
4290 :group 'org-archive
4291 :group 'org-sparse-trees
4292 :type 'boolean)
4294 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4295 "The default date type when building a sparse tree.
4296 When this is nil, a date is a scheduled or a deadline timestamp.
4297 Otherwise, these types are allowed:
4299 all: all timestamps
4300 active: only active timestamps (<...>)
4301 inactive: only inactive timestamps (<...)
4302 scheduled: only scheduled timestamps
4303 deadline: only deadline timestamps"
4304 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4305 (const :tag "All timestamps" all)
4306 (const :tag "Only active timestamps" active)
4307 (const :tag "Only inactive timestamps" inactive)
4308 (const :tag "Only scheduled timestamps" scheduled)
4309 (const :tag "Only deadline timestamps" deadline))
4310 ;; :version "24.3"
4311 :group 'org-sparse-trees)
4313 (defun org-cycle-hide-archived-subtrees (state)
4314 "Re-hide all archived subtrees after a visibility state change."
4315 (when (and (not org-cycle-open-archived-trees)
4316 (not (memq state '(overview folded))))
4317 (save-excursion
4318 (let* ((globalp (memq state '(contents all)))
4319 (beg (if globalp (point-min) (point)))
4320 (end (if globalp (point-max) (org-end-of-subtree t))))
4321 (org-hide-archived-subtrees beg end)
4322 (goto-char beg)
4323 (if (looking-at (concat ".*:" org-archive-tag ":"))
4324 (message "%s" (substitute-command-keys
4325 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4327 (defun org-force-cycle-archived ()
4328 "Cycle subtree even if it is archived."
4329 (interactive)
4330 (setq this-command 'org-cycle)
4331 (let ((org-cycle-open-archived-trees t))
4332 (call-interactively 'org-cycle)))
4334 (defun org-hide-archived-subtrees (beg end)
4335 "Re-hide all archived subtrees after a visibility state change."
4336 (save-excursion
4337 (let* ((re (concat ":" org-archive-tag ":")))
4338 (goto-char beg)
4339 (while (re-search-forward re end t)
4340 (when (org-at-heading-p)
4341 (org-flag-subtree t)
4342 (org-end-of-subtree t))))))
4344 (declare-function outline-end-of-heading "outline" ())
4345 (declare-function outline-flag-region "outline" (from to flag))
4346 (defun org-flag-subtree (flag)
4347 (save-excursion
4348 (org-back-to-heading t)
4349 (outline-end-of-heading)
4350 (outline-flag-region (point)
4351 (progn (org-end-of-subtree t) (point))
4352 flag)))
4354 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4356 (eval-and-compile
4357 (org-autoload "org-archive"
4358 '(org-add-archive-files org-archive-subtree
4359 org-archive-to-archive-sibling org-toggle-archive-tag
4360 org-archive-subtree-default
4361 org-archive-subtree-default-with-confirmation)))
4363 ;; Autoload Column View Code
4365 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4366 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4367 (declare-function org-columns-compute "org-colview" (property))
4369 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4370 '(org-columns-number-to-string org-columns-get-format-and-top-level
4371 org-columns-compute org-agenda-columns org-columns-remove-overlays
4372 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4374 ;; Autoload ID code
4376 (declare-function org-id-store-link "org-id")
4377 (declare-function org-id-locations-load "org-id")
4378 (declare-function org-id-locations-save "org-id")
4379 (defvar org-id-track-globally)
4380 (org-autoload "org-id"
4381 '(org-id-get-create org-id-new org-id-copy org-id-get
4382 org-id-get-with-outline-path-completion
4383 org-id-get-with-outline-drilling org-id-store-link
4384 org-id-goto org-id-find org-id-store-link))
4386 ;; Autoload Plotting Code
4388 (org-autoload "org-plot"
4389 '(org-plot/gnuplot))
4391 ;;; Variables for pre-computed regular expressions, all buffer local
4393 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4394 "Matches first line of a hidden block.")
4395 (make-variable-buffer-local 'org-drawer-regexp)
4396 (defvar org-todo-regexp nil
4397 "Matches any of the TODO state keywords.")
4398 (make-variable-buffer-local 'org-todo-regexp)
4399 (defvar org-not-done-regexp nil
4400 "Matches any of the TODO state keywords except the last one.")
4401 (make-variable-buffer-local 'org-not-done-regexp)
4402 (defvar org-not-done-heading-regexp nil
4403 "Matches a TODO headline that is not done.")
4404 (make-variable-buffer-local 'org-not-done-regexp)
4405 (defvar org-todo-line-regexp nil
4406 "Matches a headline and puts TODO state into group 2 if present.")
4407 (make-variable-buffer-local 'org-todo-line-regexp)
4408 (defvar org-complex-heading-regexp nil
4409 "Matches a headline and puts everything into groups:
4410 group 1: the stars
4411 group 2: The todo keyword, maybe
4412 group 3: Priority cookie
4413 group 4: True headline
4414 group 5: Tags")
4415 (make-variable-buffer-local 'org-complex-heading-regexp)
4416 (defvar org-complex-heading-regexp-format nil
4417 "Printf format to make regexp to match an exact headline.
4418 This regexp will match the headline of any node which has the
4419 exact headline text that is put into the format, but may have any
4420 TODO state, priority and tags.")
4421 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4422 (defvar org-todo-line-tags-regexp nil
4423 "Matches a headline and puts TODO state into group 2 if present.
4424 Also put tags into group 4 if tags are present.")
4425 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4426 (defvar org-ds-keyword-length 12
4427 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4428 (make-variable-buffer-local 'org-ds-keyword-length)
4429 (defvar org-deadline-regexp nil
4430 "Matches the DEADLINE keyword.")
4431 (make-variable-buffer-local 'org-deadline-regexp)
4432 (defvar org-deadline-time-regexp nil
4433 "Matches the DEADLINE keyword together with a time stamp.")
4434 (make-variable-buffer-local 'org-deadline-time-regexp)
4435 (defvar org-deadline-line-regexp nil
4436 "Matches the DEADLINE keyword and the rest of the line.")
4437 (make-variable-buffer-local 'org-deadline-line-regexp)
4438 (defvar org-scheduled-regexp nil
4439 "Matches the SCHEDULED keyword.")
4440 (make-variable-buffer-local 'org-scheduled-regexp)
4441 (defvar org-scheduled-time-regexp nil
4442 "Matches the SCHEDULED keyword together with a time stamp.")
4443 (make-variable-buffer-local 'org-scheduled-time-regexp)
4444 (defvar org-closed-time-regexp nil
4445 "Matches the CLOSED keyword together with a time stamp.")
4446 (make-variable-buffer-local 'org-closed-time-regexp)
4448 (defvar org-keyword-time-regexp nil
4449 "Matches any of the 4 keywords, together with the time stamp.")
4450 (make-variable-buffer-local 'org-keyword-time-regexp)
4451 (defvar org-keyword-time-not-clock-regexp nil
4452 "Matches any of the 3 keywords, together with the time stamp.")
4453 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4454 (defvar org-maybe-keyword-time-regexp nil
4455 "Matches a timestamp, possibly preceded by a keyword.")
4456 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4457 (defvar org-all-time-keywords nil
4458 "List of time keywords.")
4459 (make-variable-buffer-local 'org-all-time-keywords)
4461 (defconst org-plain-time-of-day-regexp
4462 (concat
4463 "\\(\\<[012]?[0-9]"
4464 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4465 "\\(--?"
4466 "\\(\\<[012]?[0-9]"
4467 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4468 "\\)?")
4469 "Regular expression to match a plain time or time range.
4470 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4471 groups carry important information:
4472 0 the full match
4473 1 the first time, range or not
4474 8 the second time, if it is a range.")
4476 (defconst org-plain-time-extension-regexp
4477 (concat
4478 "\\(\\<[012]?[0-9]"
4479 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4480 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4481 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4482 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4483 groups carry important information:
4484 0 the full match
4485 7 hours of duration
4486 9 minutes of duration")
4488 (defconst org-stamp-time-of-day-regexp
4489 (concat
4490 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4491 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4492 "\\(--?"
4493 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4494 "Regular expression to match a timestamp time or time range.
4495 After a match, the following groups carry important information:
4496 0 the full match
4497 1 date plus weekday, for back referencing to make sure both times are on the same day
4498 2 the first time, range or not
4499 4 the second time, if it is a range.")
4501 (defconst org-startup-options
4502 '(("fold" org-startup-folded t)
4503 ("overview" org-startup-folded t)
4504 ("nofold" org-startup-folded nil)
4505 ("showall" org-startup-folded nil)
4506 ("showeverything" org-startup-folded showeverything)
4507 ("content" org-startup-folded content)
4508 ("indent" org-startup-indented t)
4509 ("noindent" org-startup-indented nil)
4510 ("hidestars" org-hide-leading-stars t)
4511 ("showstars" org-hide-leading-stars nil)
4512 ("odd" org-odd-levels-only t)
4513 ("oddeven" org-odd-levels-only nil)
4514 ("align" org-startup-align-all-tables t)
4515 ("noalign" org-startup-align-all-tables nil)
4516 ("inlineimages" org-startup-with-inline-images t)
4517 ("noinlineimages" org-startup-with-inline-images nil)
4518 ("customtime" org-display-custom-times t)
4519 ("logdone" org-log-done time)
4520 ("lognotedone" org-log-done note)
4521 ("nologdone" org-log-done nil)
4522 ("lognoteclock-out" org-log-note-clock-out t)
4523 ("nolognoteclock-out" org-log-note-clock-out nil)
4524 ("logrepeat" org-log-repeat state)
4525 ("lognoterepeat" org-log-repeat note)
4526 ("nologrepeat" org-log-repeat nil)
4527 ("logreschedule" org-log-reschedule time)
4528 ("lognotereschedule" org-log-reschedule note)
4529 ("nologreschedule" org-log-reschedule nil)
4530 ("logredeadline" org-log-redeadline time)
4531 ("lognoteredeadline" org-log-redeadline note)
4532 ("nologredeadline" org-log-redeadline nil)
4533 ("logrefile" org-log-refile time)
4534 ("lognoterefile" org-log-refile note)
4535 ("nologrefile" org-log-refile nil)
4536 ("fninline" org-footnote-define-inline t)
4537 ("nofninline" org-footnote-define-inline nil)
4538 ("fnlocal" org-footnote-section nil)
4539 ("fnauto" org-footnote-auto-label t)
4540 ("fnprompt" org-footnote-auto-label nil)
4541 ("fnconfirm" org-footnote-auto-label confirm)
4542 ("fnplain" org-footnote-auto-label plain)
4543 ("fnadjust" org-footnote-auto-adjust t)
4544 ("nofnadjust" org-footnote-auto-adjust nil)
4545 ("constcgs" constants-unit-system cgs)
4546 ("constSI" constants-unit-system SI)
4547 ("noptag" org-tag-persistent-alist nil)
4548 ("hideblocks" org-hide-block-startup t)
4549 ("nohideblocks" org-hide-block-startup nil)
4550 ("beamer" org-startup-with-beamer-mode t)
4551 ("entitiespretty" org-pretty-entities t)
4552 ("entitiesplain" org-pretty-entities nil))
4553 "Variable associated with STARTUP options for org-mode.
4554 Each element is a list of three items: the startup options (as written
4555 in the #+STARTUP line), the corresponding variable, and the value to set
4556 this variable to if the option is found. An optional forth element PUSH
4557 means to push this value onto the list in the variable.")
4559 (defun org-update-property-plist (key val props)
4560 "Update PROPS with KEY and VAL."
4561 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4562 (key (if appending (substring key 0 (- (length key) 1)) key))
4563 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4564 (previous (cdr (assoc key props))))
4565 (if appending
4566 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4567 (cons (cons key val) remainder))))
4569 (defconst org-block-regexp
4570 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4571 "Regular expression for hiding blocks.")
4572 (defconst org-heading-keyword-regexp-format
4573 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4574 "Printf format for a regexp matching an headline with some keyword.
4575 This regexp will match the headline of any node which has the
4576 exact keyword that is put into the format. The keyword isn't in
4577 any group by default, but the stars and the body are.")
4578 (defconst org-heading-keyword-maybe-regexp-format
4579 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4580 "Printf format for a regexp matching an headline, possibly with some keyword.
4581 This regexp can match any headline with the specified keyword, or
4582 without a keyword. The keyword isn't in any group by default,
4583 but the stars and the body are.")
4585 (defun org-set-regexps-and-options ()
4586 "Precompute regular expressions for current buffer."
4587 (when (derived-mode-p 'org-mode)
4588 (org-set-local 'org-todo-kwd-alist nil)
4589 (org-set-local 'org-todo-key-alist nil)
4590 (org-set-local 'org-todo-key-trigger nil)
4591 (org-set-local 'org-todo-keywords-1 nil)
4592 (org-set-local 'org-done-keywords nil)
4593 (org-set-local 'org-todo-heads nil)
4594 (org-set-local 'org-todo-sets nil)
4595 (org-set-local 'org-todo-log-states nil)
4596 (org-set-local 'org-file-properties nil)
4597 (org-set-local 'org-file-tags nil)
4598 (let ((re (org-make-options-regexp
4599 '("CATEGORY" "TODO" "COLUMNS"
4600 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4601 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4602 "OPTIONS")
4603 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4604 (splitre "[ \t]+")
4605 (scripts org-use-sub-superscripts)
4606 kwds kws0 kwsa key log value cat arch tags const links hw dws
4607 tail sep kws1 prio props ftags drawers beamer-p
4608 ext-setup-or-nil setup-contents (start 0))
4609 (save-excursion
4610 (save-restriction
4611 (widen)
4612 (goto-char (point-min))
4613 (while (or (and ext-setup-or-nil
4614 (string-match re ext-setup-or-nil start)
4615 (setq start (match-end 0)))
4616 (and (setq ext-setup-or-nil nil start 0)
4617 (re-search-forward re nil t)))
4618 (setq key (upcase (match-string 1 ext-setup-or-nil))
4619 value (org-match-string-no-properties 2 ext-setup-or-nil))
4620 (if (stringp value) (setq value (org-trim value)))
4621 (cond
4622 ((equal key "CATEGORY")
4623 (setq cat value))
4624 ((member key '("SEQ_TODO" "TODO"))
4625 (push (cons 'sequence (org-split-string value splitre)) kwds))
4626 ((equal key "TYP_TODO")
4627 (push (cons 'type (org-split-string value splitre)) kwds))
4628 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4629 ;; general TODO-like setup
4630 (push (cons (intern (downcase (match-string 1 key)))
4631 (org-split-string value splitre)) kwds))
4632 ((equal key "TAGS")
4633 (setq tags (append tags (if tags '("\\n") nil)
4634 (org-split-string value splitre))))
4635 ((equal key "COLUMNS")
4636 (org-set-local 'org-columns-default-format value))
4637 ((equal key "LINK")
4638 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4639 (push (cons (match-string 1 value)
4640 (org-trim (match-string 2 value)))
4641 links)))
4642 ((equal key "PRIORITIES")
4643 (setq prio (org-split-string value " +")))
4644 ((equal key "PROPERTY")
4645 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4646 (setq props (org-update-property-plist (match-string 1 value)
4647 (match-string 2 value)
4648 props))))
4649 ((equal key "FILETAGS")
4650 (when (string-match "\\S-" value)
4651 (setq ftags
4652 (append
4653 ftags
4654 (apply 'append
4655 (mapcar (lambda (x) (org-split-string x ":"))
4656 (org-split-string value)))))))
4657 ((equal key "DRAWERS")
4658 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4659 ((equal key "CONSTANTS")
4660 (setq const (append const (org-split-string value splitre))))
4661 ((equal key "STARTUP")
4662 (let ((opts (org-split-string value splitre))
4663 l var val)
4664 (while (setq l (pop opts))
4665 (when (setq l (assoc l org-startup-options))
4666 (setq var (nth 1 l) val (nth 2 l))
4667 (if (not (nth 3 l))
4668 (set (make-local-variable var) val)
4669 (if (not (listp (symbol-value var)))
4670 (set (make-local-variable var) nil))
4671 (set (make-local-variable var) (symbol-value var))
4672 (add-to-list var val))))))
4673 ((equal key "ARCHIVE")
4674 (setq arch value)
4675 (remove-text-properties 0 (length arch)
4676 '(face t fontified t) arch))
4677 ((equal key "LATEX_CLASS")
4678 (setq beamer-p (equal value "beamer")))
4679 ((equal key "OPTIONS")
4680 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4681 (setq scripts (read (match-string 2 value)))))
4682 ((equal key "SETUPFILE")
4683 (setq setup-contents (org-file-contents
4684 (expand-file-name
4685 (org-remove-double-quotes value))
4686 'noerror))
4687 (if (not ext-setup-or-nil)
4688 (setq ext-setup-or-nil setup-contents start 0)
4689 (setq ext-setup-or-nil
4690 (concat (substring ext-setup-or-nil 0 start)
4691 "\n" setup-contents "\n"
4692 (substring ext-setup-or-nil start)))))))
4693 ;; search for property blocks
4694 (goto-char (point-min))
4695 (while (re-search-forward org-block-regexp nil t)
4696 (when (equal "PROPERTY" (upcase (match-string 1)))
4697 (setq value (replace-regexp-in-string
4698 "[\n\r]" " " (match-string 4)))
4699 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4700 (setq props (org-update-property-plist (match-string 1 value)
4701 (match-string 2 value)
4702 props)))))))
4703 (org-set-local 'org-use-sub-superscripts scripts)
4704 (when cat
4705 (org-set-local 'org-category (intern cat))
4706 (push (cons "CATEGORY" cat) props))
4707 (when prio
4708 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4709 (setq prio (mapcar 'string-to-char prio))
4710 (org-set-local 'org-highest-priority (nth 0 prio))
4711 (org-set-local 'org-lowest-priority (nth 1 prio))
4712 (org-set-local 'org-default-priority (nth 2 prio)))
4713 (and props (org-set-local 'org-file-properties (nreverse props)))
4714 (and ftags (org-set-local 'org-file-tags
4715 (mapcar 'org-add-prop-inherited ftags)))
4716 (and drawers (org-set-local 'org-drawers drawers))
4717 (and arch (org-set-local 'org-archive-location arch))
4718 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4719 ;; Process the TODO keywords
4720 (unless kwds
4721 ;; Use the global values as if they had been given locally.
4722 (setq kwds (default-value 'org-todo-keywords))
4723 (if (stringp (car kwds))
4724 (setq kwds (list (cons org-todo-interpretation
4725 (default-value 'org-todo-keywords)))))
4726 (setq kwds (reverse kwds)))
4727 (setq kwds (nreverse kwds))
4728 (let (inter kws kw)
4729 (while (setq kws (pop kwds))
4730 (let ((kws (or
4731 (run-hook-with-args-until-success
4732 'org-todo-setup-filter-hook kws)
4733 kws)))
4734 (setq inter (pop kws) sep (member "|" kws)
4735 kws0 (delete "|" (copy-sequence kws))
4736 kwsa nil
4737 kws1 (mapcar
4738 (lambda (x)
4739 ;; 1 2
4740 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4741 (progn
4742 (setq kw (match-string 1 x)
4743 key (and (match-end 2) (match-string 2 x))
4744 log (org-extract-log-state-settings x))
4745 (push (cons kw (and key (string-to-char key))) kwsa)
4746 (and log (push log org-todo-log-states))
4748 (error "Invalid TODO keyword %s" x)))
4749 kws0)
4750 kwsa (if kwsa (append '((:startgroup))
4751 (nreverse kwsa)
4752 '((:endgroup))))
4753 hw (car kws1)
4754 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4755 tail (list inter hw (car dws) (org-last dws))))
4756 (add-to-list 'org-todo-heads hw 'append)
4757 (push kws1 org-todo-sets)
4758 (setq org-done-keywords (append org-done-keywords dws nil))
4759 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4760 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4761 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4762 (setq org-todo-sets (nreverse org-todo-sets)
4763 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4764 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4765 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4766 ;; Process the constants
4767 (when const
4768 (let (e cst)
4769 (while (setq e (pop const))
4770 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4771 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4772 (setq org-table-formula-constants-local cst)))
4774 ;; Process the tags.
4775 (when tags
4776 (let (e tgs)
4777 (while (setq e (pop tags))
4778 (cond
4779 ((equal e "{") (push '(:startgroup) tgs))
4780 ((equal e "}") (push '(:endgroup) tgs))
4781 ((equal e "\\n") (push '(:newline) tgs))
4782 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4783 (push (cons (match-string 1 e)
4784 (string-to-char (match-string 2 e)))
4785 tgs))
4786 (t (push (list e) tgs))))
4787 (org-set-local 'org-tag-alist nil)
4788 (while (setq e (pop tgs))
4789 (or (and (stringp (car e))
4790 (assoc (car e) org-tag-alist))
4791 (push e org-tag-alist)))))
4793 ;; Compute the regular expressions and other local variables.
4794 ;; Using `org-outline-regexp-bol' would complicate them much,
4795 ;; because of the fixed white space at the end of that string.
4796 (if (not org-done-keywords)
4797 (setq org-done-keywords (and org-todo-keywords-1
4798 (list (org-last org-todo-keywords-1)))))
4799 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4800 (length org-scheduled-string)
4801 (length org-clock-string)
4802 (length org-closed-string)))
4803 org-drawer-regexp
4804 (concat "^[ \t]*:\\("
4805 (mapconcat 'regexp-quote org-drawers "\\|")
4806 "\\):[ \t]*$")
4807 org-not-done-keywords
4808 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4809 org-todo-regexp
4810 (concat "\\("
4811 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4812 "\\)")
4813 org-not-done-regexp
4814 (concat "\\("
4815 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4816 "\\)")
4817 org-not-done-heading-regexp
4818 (format org-heading-keyword-regexp-format org-not-done-regexp)
4819 org-todo-line-regexp
4820 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4821 org-complex-heading-regexp
4822 (concat "^\\(\\*+\\)"
4823 "\\(?: +" org-todo-regexp "\\)?"
4824 "\\(?: +\\(\\[#.\\]\\)\\)?"
4825 "\\(?: +\\(.*?\\)\\)?"
4826 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4827 "[ \t]*$")
4828 org-complex-heading-regexp-format
4829 (concat "^\\(\\*+\\)"
4830 "\\(?: +" org-todo-regexp "\\)?"
4831 "\\(?: +\\(\\[#.\\]\\)\\)?"
4832 "\\(?: +"
4833 ;; Stats cookies can be stuck to body.
4834 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4835 "\\(%s\\)"
4836 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4837 "\\)"
4838 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4839 "[ \t]*$")
4840 org-todo-line-tags-regexp
4841 (concat "^\\(\\*+\\)"
4842 "\\(?: +" org-todo-regexp "\\)?"
4843 "\\(?: +\\(.*?\\)\\)?"
4844 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4845 "[ \t]*$")
4846 org-deadline-regexp (concat "\\<" org-deadline-string)
4847 org-deadline-time-regexp
4848 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4849 org-deadline-line-regexp
4850 (concat "\\<\\(" org-deadline-string "\\).*")
4851 org-scheduled-regexp
4852 (concat "\\<" org-scheduled-string)
4853 org-scheduled-time-regexp
4854 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4855 org-closed-time-regexp
4856 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4857 org-keyword-time-regexp
4858 (concat "\\<\\(" org-scheduled-string
4859 "\\|" org-deadline-string
4860 "\\|" org-closed-string
4861 "\\|" org-clock-string "\\)"
4862 " *[[<]\\([^]>]+\\)[]>]")
4863 org-keyword-time-not-clock-regexp
4864 (concat "\\<\\(" org-scheduled-string
4865 "\\|" org-deadline-string
4866 "\\|" org-closed-string
4867 "\\)"
4868 " *[[<]\\([^]>]+\\)[]>]")
4869 org-maybe-keyword-time-regexp
4870 (concat "\\(\\<\\(" org-scheduled-string
4871 "\\|" org-deadline-string
4872 "\\|" org-closed-string
4873 "\\|" org-clock-string "\\)\\)?"
4874 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4875 org-all-time-keywords
4876 (mapcar (lambda (w) (substring w 0 -1))
4877 (list org-scheduled-string org-deadline-string
4878 org-clock-string org-closed-string))
4880 (org-compute-latex-and-specials-regexp)
4881 (org-set-font-lock-defaults))))
4883 (defun org-file-contents (file &optional noerror)
4884 "Return the contents of FILE, as a string."
4885 (if (or (not file)
4886 (not (file-readable-p file)))
4887 (if noerror
4888 (progn
4889 (message "Cannot read file \"%s\"" file)
4890 (ding) (sit-for 2)
4892 (error "Cannot read file \"%s\"" file))
4893 (with-temp-buffer
4894 (insert-file-contents file)
4895 (buffer-string))))
4897 (defun org-extract-log-state-settings (x)
4898 "Extract the log state setting from a TODO keyword string.
4899 This will extract info from a string like \"WAIT(w@/!)\"."
4900 (let (kw key log1 log2)
4901 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4902 (setq kw (match-string 1 x)
4903 key (and (match-end 2) (match-string 2 x))
4904 log1 (and (match-end 3) (match-string 3 x))
4905 log2 (and (match-end 4) (match-string 4 x)))
4906 (and (or log1 log2)
4907 (list kw
4908 (and log1 (if (equal log1 "!") 'time 'note))
4909 (and log2 (if (equal log2 "!") 'time 'note)))))))
4911 (defun org-remove-keyword-keys (list)
4912 "Remove a pair of parenthesis at the end of each string in LIST."
4913 (mapcar (lambda (x)
4914 (if (string-match "(.*)$" x)
4915 (substring x 0 (match-beginning 0))
4917 list))
4919 (defun org-assign-fast-keys (alist)
4920 "Assign fast keys to a keyword-key alist.
4921 Respect keys that are already there."
4922 (let (new e (alt ?0))
4923 (while (setq e (pop alist))
4924 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4925 (cdr e)) ;; Key already assigned.
4926 (push e new)
4927 (let ((clist (string-to-list (downcase (car e))))
4928 (used (append new alist)))
4929 (when (= (car clist) ?@)
4930 (pop clist))
4931 (while (and clist (rassoc (car clist) used))
4932 (pop clist))
4933 (unless clist
4934 (while (rassoc alt used)
4935 (incf alt)))
4936 (push (cons (car e) (or (car clist) alt)) new))))
4937 (nreverse new)))
4939 ;;; Some variables used in various places
4941 (defvar org-window-configuration nil
4942 "Used in various places to store a window configuration.")
4943 (defvar org-selected-window nil
4944 "Used in various places to store a window configuration.")
4945 (defvar org-finish-function nil
4946 "Function to be called when `C-c C-c' is used.
4947 This is for getting out of special buffers like remember.")
4950 ;; FIXME: Occasionally check by commenting these, to make sure
4951 ;; no other functions uses these, forgetting to let-bind them.
4952 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4953 (defvar org-last-state)
4954 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4956 ;; Defined somewhere in this file, but used before definition.
4957 (defvar org-entities) ;; defined in org-entities.el
4958 (defvar org-struct-menu)
4959 (defvar org-org-menu)
4960 (defvar org-tbl-menu)
4962 ;;;; Define the Org-mode
4964 ;; We use a before-change function to check if a table might need
4965 ;; an update.
4966 (defvar org-table-may-need-update t
4967 "Indicates that a table might need an update.
4968 This variable is set by `org-before-change-function'.
4969 `org-table-align' sets it back to nil.")
4970 (defun org-before-change-function (beg end)
4971 "Every change indicates that a table might need an update."
4972 (setq org-table-may-need-update t))
4973 (defvar org-mode-map)
4974 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4975 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4976 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4977 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4978 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4979 (defvar org-table-buffer-is-an nil)
4981 (defvar bidi-paragraph-direction)
4982 (defvar buffer-face-mode-face)
4984 (require 'outline)
4985 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4986 (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"))
4987 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4989 ;; Other stuff we need.
4990 (require 'time-date)
4991 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4992 (require 'easymenu)
4993 (require 'overlay)
4995 (require 'org-macs)
4996 (require 'org-entities)
4997 ;; (require 'org-compat) moved higher up in the file before it is first used
4998 (require 'org-faces)
4999 (require 'org-list)
5000 (require 'org-pcomplete)
5001 (require 'org-src)
5002 (require 'org-footnote)
5004 ;; babel
5005 (require 'ob)
5006 (require 'ob-table)
5007 (require 'ob-lob)
5008 (require 'ob-ref)
5009 (require 'ob-tangle)
5010 (require 'ob-comint)
5011 (require 'ob-keys)
5013 ;;;###autoload
5014 (define-derived-mode org-mode outline-mode "Org"
5015 "Outline-based notes management and organizer, alias
5016 \"Carsten's outline-mode for keeping track of everything.\"
5018 Org-mode develops organizational tasks around a NOTES file which
5019 contains information about projects as plain text. Org-mode is
5020 implemented on top of outline-mode, which is ideal to keep the content
5021 of large files well structured. It supports ToDo items, deadlines and
5022 time stamps, which magically appear in the diary listing of the Emacs
5023 calendar. Tables are easily created with a built-in table editor.
5024 Plain text URL-like links connect to websites, emails (VM), Usenet
5025 messages (Gnus), BBDB entries, and any files related to the project.
5026 For printing and sharing of notes, an Org-mode file (or a part of it)
5027 can be exported as a structured ASCII or HTML file.
5029 The following commands are available:
5031 \\{org-mode-map}"
5033 ;; Get rid of Outline menus, they are not needed
5034 ;; Need to do this here because define-derived-mode sets up
5035 ;; the keymap so late. Still, it is a waste to call this each time
5036 ;; we switch another buffer into org-mode.
5037 (if (featurep 'xemacs)
5038 (when (boundp 'outline-mode-menu-heading)
5039 ;; Assume this is Greg's port, it uses easymenu
5040 (easy-menu-remove outline-mode-menu-heading)
5041 (easy-menu-remove outline-mode-menu-show)
5042 (easy-menu-remove outline-mode-menu-hide))
5043 (define-key org-mode-map [menu-bar headings] 'undefined)
5044 (define-key org-mode-map [menu-bar hide] 'undefined)
5045 (define-key org-mode-map [menu-bar show] 'undefined))
5047 (org-load-modules-maybe)
5048 (easy-menu-add org-org-menu)
5049 (easy-menu-add org-tbl-menu)
5050 (org-install-agenda-files-menu)
5051 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5052 (add-to-invisibility-spec '(org-cwidth))
5053 (add-to-invisibility-spec '(org-hide-block . t))
5054 (when (featurep 'xemacs)
5055 (org-set-local 'line-move-ignore-invisible t))
5056 (org-set-local 'outline-regexp org-outline-regexp)
5057 (org-set-local 'outline-level 'org-outline-level)
5058 (setq bidi-paragraph-direction 'left-to-right)
5059 (when (and org-ellipsis
5060 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5061 (fboundp 'make-glyph-code))
5062 (unless org-display-table
5063 (setq org-display-table (make-display-table)))
5064 (set-display-table-slot
5065 org-display-table 4
5066 (vconcat (mapcar
5067 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5068 org-ellipsis)))
5069 (if (stringp org-ellipsis) org-ellipsis "..."))))
5070 (setq buffer-display-table org-display-table))
5071 (org-set-regexps-and-options)
5072 (when (and org-tag-faces (not org-tags-special-faces-re))
5073 ;; tag faces set outside customize.... force initialization.
5074 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5075 ;; Calc embedded
5076 (org-set-local 'calc-embedded-open-mode "# ")
5077 (modify-syntax-entry ?@ "w")
5078 (if org-startup-truncated (setq truncate-lines t))
5079 (org-set-local 'font-lock-unfontify-region-function
5080 'org-unfontify-region)
5081 ;; Activate before-change-function
5082 (org-set-local 'org-table-may-need-update t)
5083 (org-add-hook 'before-change-functions 'org-before-change-function nil
5084 'local)
5085 ;; Check for running clock before killing a buffer
5086 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5087 ;; Indentation.
5088 (org-set-local 'indent-line-function 'org-indent-line)
5089 (org-set-local 'indent-region-function 'org-indent-region)
5090 ;; Initialize radio targets.
5091 (org-update-radio-target-regexp)
5092 ;; Filling and auto-filling.
5093 (org-setup-filling)
5094 ;; Comments.
5095 (org-setup-comments-handling)
5096 ;; Beginning/end of defun
5097 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5098 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5099 ;; Next error for sparse trees
5100 (org-set-local 'next-error-function 'org-occur-next-match)
5101 ;; Make sure dependence stuff works reliably, even for users who set it
5102 ;; too late :-(
5103 (if org-enforce-todo-dependencies
5104 (add-hook 'org-blocker-hook
5105 'org-block-todo-from-children-or-siblings-or-parent)
5106 (remove-hook 'org-blocker-hook
5107 'org-block-todo-from-children-or-siblings-or-parent))
5108 (if org-enforce-todo-checkbox-dependencies
5109 (add-hook 'org-blocker-hook
5110 'org-block-todo-from-checkboxes)
5111 (remove-hook 'org-blocker-hook
5112 'org-block-todo-from-checkboxes))
5114 ;; Align options lines
5115 (org-set-local
5116 'align-mode-rules-list
5117 '((org-in-buffer-settings
5118 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5119 (modes . '(org-mode)))))
5121 ;; Imenu
5122 (org-set-local 'imenu-create-index-function
5123 'org-imenu-get-tree)
5125 ;; Make isearch reveal context
5126 (if (or (featurep 'xemacs)
5127 (not (boundp 'outline-isearch-open-invisible-function)))
5128 ;; Emacs 21 and XEmacs make use of the hook
5129 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5130 ;; Emacs 22 deals with this through a special variable
5131 (org-set-local 'outline-isearch-open-invisible-function
5132 (lambda (&rest ignore) (org-show-context 'isearch))))
5134 ;; Turn on org-beamer-mode?
5135 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5137 ;; Setup the pcomplete hooks
5138 (set (make-local-variable 'pcomplete-command-completion-function)
5139 'org-pcomplete-initial)
5140 (set (make-local-variable 'pcomplete-command-name-function)
5141 'org-command-at-point)
5142 (set (make-local-variable 'pcomplete-default-completion-function)
5143 'ignore)
5144 (set (make-local-variable 'pcomplete-parse-arguments-function)
5145 'org-parse-arguments)
5146 (set (make-local-variable 'pcomplete-termination-string) "")
5147 (when (>= emacs-major-version 23)
5148 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5150 ;; If empty file that did not turn on org-mode automatically, make it to.
5151 (if (and org-insert-mode-line-in-empty-file
5152 (org-called-interactively-p 'any)
5153 (= (point-min) (point-max)))
5154 (insert "# -*- mode: org -*-\n\n"))
5155 (unless org-inhibit-startup
5156 (when org-startup-align-all-tables
5157 (let ((bmp (buffer-modified-p)))
5158 (org-table-map-tables 'org-table-align 'quietly)
5159 (set-buffer-modified-p bmp)))
5160 (when org-startup-with-inline-images
5161 (org-display-inline-images))
5162 (when org-startup-indented
5163 (require 'org-indent)
5164 (org-indent-mode 1))
5165 (unless org-inhibit-startup-visibility-stuff
5166 (org-set-startup-visibility))))
5168 (when (fboundp 'abbrev-table-put)
5169 (abbrev-table-put org-mode-abbrev-table
5170 :parents (list text-mode-abbrev-table)))
5172 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5174 (defun org-current-time ()
5175 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5176 (if (> (car org-time-stamp-rounding-minutes) 1)
5177 (let ((r (car org-time-stamp-rounding-minutes))
5178 (time (decode-time)))
5179 (apply 'encode-time
5180 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5181 (nthcdr 2 time))))
5182 (current-time)))
5184 (defun org-today ()
5185 "Return today date, considering `org-extend-today-until'."
5186 (time-to-days
5187 (time-subtract (current-time)
5188 (list 0 (* 3600 org-extend-today-until) 0))))
5190 ;;;; Font-Lock stuff, including the activators
5192 (defvar org-mouse-map (make-sparse-keymap))
5193 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5194 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5195 (when org-mouse-1-follows-link
5196 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5197 (when org-tab-follows-link
5198 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5199 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5201 (require 'font-lock)
5203 (defconst org-non-link-chars "]\t\n\r<>")
5204 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5205 "shell" "elisp" "doi" "message"))
5206 (defvar org-link-types-re nil
5207 "Matches a link that has a url-like prefix like \"http:\"")
5208 (defvar org-link-re-with-space nil
5209 "Matches a link with spaces, optional angular brackets around it.")
5210 (defvar org-link-re-with-space2 nil
5211 "Matches a link with spaces, optional angular brackets around it.")
5212 (defvar org-link-re-with-space3 nil
5213 "Matches a link with spaces, only for internal part in bracket links.")
5214 (defvar org-angle-link-re nil
5215 "Matches link with angular brackets, spaces are allowed.")
5216 (defvar org-plain-link-re nil
5217 "Matches plain link, without spaces.")
5218 (defvar org-bracket-link-regexp nil
5219 "Matches a link in double brackets.")
5220 (defvar org-bracket-link-analytic-regexp nil
5221 "Regular expression used to analyze links.
5222 Here is what the match groups contain after a match:
5223 1: http:
5224 2: http
5225 3: path
5226 4: [desc]
5227 5: desc")
5228 (defvar org-bracket-link-analytic-regexp++ nil
5229 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5230 (defvar org-any-link-re nil
5231 "Regular expression matching any link.")
5233 (defcustom org-match-sexp-depth 3
5234 "Number of stacked braces for sub/superscript matching.
5235 This has to be set before loading org.el to be effective."
5236 :group 'org-export-translation ; ??????????????????????????/
5237 :type 'integer)
5239 (defun org-create-multibrace-regexp (left right n)
5240 "Create a regular expression which will match a balanced sexp.
5241 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5242 as single character strings.
5243 The regexp returned will match the entire expression including the
5244 delimiters. It will also define a single group which contains the
5245 match except for the outermost delimiters. The maximum depth of
5246 stacked delimiters is N. Escaping delimiters is not possible."
5247 (let* ((nothing (concat "[^" left right "]*?"))
5248 (or "\\|")
5249 (re nothing)
5250 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5251 (while (> n 1)
5252 (setq n (1- n)
5253 re (concat re or next)
5254 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5255 (concat left "\\(" re "\\)" right)))
5257 (defvar org-match-substring-regexp
5258 (concat
5259 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5260 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5261 "\\|"
5262 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5263 "\\|"
5264 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5265 "The regular expression matching a sub- or superscript.")
5267 (defvar org-match-substring-with-braces-regexp
5268 (concat
5269 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5270 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5271 "\\)")
5272 "The regular expression matching a sub- or superscript, forcing braces.")
5274 (defun org-make-link-regexps ()
5275 "Update the link regular expressions.
5276 This should be called after the variable `org-link-types' has changed."
5277 (setq org-link-types-re
5278 (concat
5279 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5280 org-link-re-with-space
5281 (concat
5282 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5283 "\\([^" org-non-link-chars " ]"
5284 "[^" org-non-link-chars "]*"
5285 "[^" org-non-link-chars " ]\\)>?")
5286 org-link-re-with-space2
5287 (concat
5288 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5289 "\\([^" org-non-link-chars " ]"
5290 "[^\t\n\r]*"
5291 "[^" org-non-link-chars " ]\\)>?")
5292 org-link-re-with-space3
5293 (concat
5294 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5295 "\\([^" org-non-link-chars " ]"
5296 "[^\t\n\r]*\\)")
5297 org-angle-link-re
5298 (concat
5299 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5300 "\\([^" org-non-link-chars " ]"
5301 "[^" org-non-link-chars "]*"
5302 "\\)>")
5303 org-plain-link-re
5304 (concat
5305 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5306 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5307 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5308 org-bracket-link-regexp
5309 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5310 org-bracket-link-analytic-regexp
5311 (concat
5312 "\\[\\["
5313 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5314 "\\([^]]+\\)"
5315 "\\]"
5316 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5317 "\\]")
5318 org-bracket-link-analytic-regexp++
5319 (concat
5320 "\\[\\["
5321 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5322 "\\([^]]+\\)"
5323 "\\]"
5324 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5325 "\\]")
5326 org-any-link-re
5327 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5328 org-angle-link-re "\\)\\|\\("
5329 org-plain-link-re "\\)")))
5331 (org-make-link-regexps)
5333 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5334 "Regular expression for fast time stamp matching.")
5335 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5336 "Regular expression for fast time stamp matching.")
5337 (defconst org-ts-regexp0
5338 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5339 "Regular expression matching time strings for analysis.
5340 This one does not require the space after the date, so it can be used
5341 on a string that terminates immediately after the date.")
5342 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5343 "Regular expression matching time strings for analysis.")
5344 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5345 "Regular expression matching time stamps, with groups.")
5346 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5347 "Regular expression matching time stamps (also [..]), with groups.")
5348 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5349 "Regular expression matching a time stamp range.")
5350 (defconst org-tr-regexp-both
5351 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5352 "Regular expression matching a time stamp range.")
5353 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5354 org-ts-regexp "\\)?")
5355 "Regular expression matching a time stamp or time stamp range.")
5356 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5357 org-ts-regexp-both "\\)?")
5358 "Regular expression matching a time stamp or time stamp range.
5359 The time stamps may be either active or inactive.")
5361 (defvar org-emph-face nil)
5363 (defun org-do-emphasis-faces (limit)
5364 "Run through the buffer and add overlays to emphasized strings."
5365 (let (rtn a)
5366 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5367 (if (not (= (char-after (match-beginning 3))
5368 (char-after (match-beginning 4))))
5369 (progn
5370 (setq rtn t)
5371 (setq a (assoc (match-string 3) org-emphasis-alist))
5372 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5373 'face
5374 (nth 1 a))
5375 (and (nth 4 a)
5376 (org-remove-flyspell-overlays-in
5377 (match-beginning 0) (match-end 0)))
5378 (add-text-properties (match-beginning 2) (match-end 2)
5379 '(font-lock-multiline t org-emphasis t))
5380 (when org-hide-emphasis-markers
5381 (add-text-properties (match-end 4) (match-beginning 5)
5382 '(invisible org-link))
5383 (add-text-properties (match-beginning 3) (match-end 3)
5384 '(invisible org-link)))))
5385 (backward-char 1))
5386 rtn))
5388 (defun org-emphasize (&optional char)
5389 "Insert or change an emphasis, i.e. a font like bold or italic.
5390 If there is an active region, change that region to a new emphasis.
5391 If there is no region, just insert the marker characters and position
5392 the cursor between them.
5393 CHAR should be either the marker character, or the first character of the
5394 HTML tag associated with that emphasis. If CHAR is a space, the means
5395 to remove the emphasis of the selected region.
5396 If char is not given (for example in an interactive call) it
5397 will be prompted for."
5398 (interactive)
5399 (let ((eal org-emphasis-alist) e det
5400 (erc org-emphasis-regexp-components)
5401 (prompt "")
5402 (string "") beg end move tag c s)
5403 (if (org-region-active-p)
5404 (setq beg (region-beginning) end (region-end)
5405 string (buffer-substring beg end))
5406 (setq move t))
5408 (while (setq e (pop eal))
5409 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5410 c (aref tag 0))
5411 (push (cons c (string-to-char (car e))) det)
5412 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5413 (substring tag 1)))))
5414 (setq det (nreverse det))
5415 (unless char
5416 (message "%s" (concat "Emphasis marker or tag:" prompt))
5417 (setq char (read-char-exclusive)))
5418 (setq char (or (cdr (assoc char det)) char))
5419 (if (equal char ?\ )
5420 (setq s "" move nil)
5421 (unless (assoc (char-to-string char) org-emphasis-alist)
5422 (error "No such emphasis marker: \"%c\"" char))
5423 (setq s (char-to-string char)))
5424 (while (and (> (length string) 1)
5425 (equal (substring string 0 1) (substring string -1))
5426 (assoc (substring string 0 1) org-emphasis-alist))
5427 (setq string (substring string 1 -1)))
5428 (setq string (concat s string s))
5429 (if beg (delete-region beg end))
5430 (unless (or (bolp)
5431 (string-match (concat "[" (nth 0 erc) "\n]")
5432 (char-to-string (char-before (point)))))
5433 (insert " "))
5434 (unless (or (eobp)
5435 (string-match (concat "[" (nth 1 erc) "\n]")
5436 (char-to-string (char-after (point)))))
5437 (insert " ") (backward-char 1))
5438 (insert string)
5439 (and move (backward-char 1))))
5441 (defconst org-nonsticky-props
5442 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5444 (defsubst org-rear-nonsticky-at (pos)
5445 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5447 (defun org-activate-plain-links (limit)
5448 "Run through the buffer and add overlays to links."
5449 (catch 'exit
5450 (let (f)
5451 (if (and (re-search-forward (concat org-plain-link-re) limit t)
5452 (or (not (member 'bracket org-activate-links))
5453 (save-excursion
5454 (save-match-data
5455 (goto-char (match-beginning 0))
5456 (not (looking-back "\\[\\["))))))
5457 (progn
5458 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5459 (setq f (get-text-property (match-beginning 0) 'face))
5460 (if (or (eq f 'org-tag)
5461 (and (listp f) (memq 'org-tag f)))
5463 (add-text-properties (match-beginning 0) (match-end 0)
5464 (list 'mouse-face 'highlight
5465 'face 'org-link
5466 'keymap org-mouse-map))
5467 (org-rear-nonsticky-at (match-end 0)))
5468 t)))))
5470 (defun org-activate-code (limit)
5471 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5472 (progn
5473 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5474 (remove-text-properties (match-beginning 0) (match-end 0)
5475 '(display t invisible t intangible t))
5476 t)))
5478 (defcustom org-src-fontify-natively nil
5479 "When non-nil, fontify code in code blocks."
5480 :type 'boolean
5481 :version "24.1"
5482 :group 'org-appearance
5483 :group 'org-babel)
5485 (defcustom org-allow-promoting-top-level-subtree nil
5486 "When non-nil, allow promoting a top level subtree.
5487 The leading star of the top level headline will be replaced
5488 by a #."
5489 :type 'boolean
5490 :version "24.1"
5491 :group 'org-appearance)
5493 (defun org-fontify-meta-lines-and-blocks (limit)
5494 (condition-case nil
5495 (org-fontify-meta-lines-and-blocks-1 limit)
5496 (error (message "org-mode fontification error"))))
5498 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5499 "Fontify #+ lines and blocks, in the correct ways."
5500 (let ((case-fold-search t))
5501 (if (re-search-forward
5502 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5503 limit t)
5504 (let ((beg (match-beginning 0))
5505 (block-start (match-end 0))
5506 (block-end nil)
5507 (lang (match-string 7))
5508 (beg1 (line-beginning-position 2))
5509 (dc1 (downcase (match-string 2)))
5510 (dc3 (downcase (match-string 3)))
5511 end end1 quoting block-type ovl)
5512 (cond
5513 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5514 ;; a single line of backend-specific content
5515 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5516 (remove-text-properties (match-beginning 0) (match-end 0)
5517 '(display t invisible t intangible t))
5518 (add-text-properties (match-beginning 1) (match-end 3)
5519 '(font-lock-fontified t face org-meta-line))
5520 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5521 '(font-lock-fontified t face org-block))
5522 ; for backend-specific code
5524 ((and (match-end 4) (equal dc3 "+begin"))
5525 ;; Truly a block
5526 (setq block-type (downcase (match-string 5))
5527 quoting (member block-type org-protecting-blocks))
5528 (when (re-search-forward
5529 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5530 nil t) ;; on purpose, we look further than LIMIT
5531 (setq end (min (point-max) (match-end 0))
5532 end1 (min (point-max) (1- (match-beginning 0))))
5533 (setq block-end (match-beginning 0))
5534 (when quoting
5535 (remove-text-properties beg end
5536 '(display t invisible t intangible t)))
5537 (add-text-properties
5538 beg end
5539 '(font-lock-fontified t font-lock-multiline t))
5540 (add-text-properties beg beg1 '(face org-meta-line))
5541 (add-text-properties end1 (min (point-max) (1+ end))
5542 '(face org-meta-line)) ; for end_src
5543 (cond
5544 ((and lang (not (string= lang "")) org-src-fontify-natively)
5545 (org-src-font-lock-fontify-block lang block-start block-end)
5546 ;; remove old background overlays
5547 (mapc (lambda (ov)
5548 (if (eq (overlay-get ov 'face) 'org-block-background)
5549 (delete-overlay ov)))
5550 (overlays-at (/ (+ beg1 block-end) 2)))
5551 ;; add a background overlay
5552 (setq ovl (make-overlay beg1 block-end))
5553 (overlay-put ovl 'face 'org-block-background)
5554 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5555 (quoting
5556 (add-text-properties beg1 (min (point-max) (1+ end1))
5557 '(face org-block))) ; end of source block
5558 ((not org-fontify-quote-and-verse-blocks))
5559 ((string= block-type "quote")
5560 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5561 ((string= block-type "verse")
5562 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5563 (add-text-properties beg beg1 '(face org-block-begin-line))
5564 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5565 '(face org-block-end-line))
5567 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5568 (add-text-properties
5569 beg (match-end 3)
5570 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5571 '(font-lock-fontified t invisible t)
5572 '(font-lock-fontified t face org-document-info-keyword)))
5573 (add-text-properties
5574 (match-beginning 6) (match-end 6)
5575 (if (string-equal dc1 "+title:")
5576 '(font-lock-fontified t face org-document-title)
5577 '(font-lock-fontified t face org-document-info))))
5578 ((or (equal dc1 "+results")
5579 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5580 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5581 "+call:" "+header:" "+headers:" "+name:"))
5582 (and (match-end 4) (equal dc3 "+attr")))
5583 (add-text-properties
5584 beg (match-end 0)
5585 '(font-lock-fontified t face org-meta-line))
5587 ((member dc3 '(" " ""))
5588 (add-text-properties
5589 beg (match-end 0)
5590 '(font-lock-fontified t face font-lock-comment-face)))
5591 ((not (member (char-after beg) '(?\ ?\t)))
5592 ;; just any other in-buffer setting, but not indented
5593 (add-text-properties
5594 beg (match-end 0)
5595 '(font-lock-fontified t face org-meta-line))
5597 (t nil))))))
5599 (defun org-strip-protective-commas (beg end)
5600 "Strip protective commas between BEG and END in the current buffer."
5601 (interactive "r")
5602 (save-excursion
5603 (save-match-data
5604 (goto-char beg)
5605 (let ((front-line (save-excursion
5606 (re-search-forward
5607 "[^[:space:]]" end t)
5608 (goto-char (match-beginning 0))
5609 (current-column))))
5610 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5611 (goto-char (match-beginning 1))
5612 (when (= (current-column) front-line)
5613 (replace-match "" nil nil nil 1)))))))
5615 (defun org-activate-angle-links (limit)
5616 "Run through the buffer and add overlays to links."
5617 (if (re-search-forward org-angle-link-re limit t)
5618 (progn
5619 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5620 (add-text-properties (match-beginning 0) (match-end 0)
5621 (list 'mouse-face 'highlight
5622 'keymap org-mouse-map))
5623 (org-rear-nonsticky-at (match-end 0))
5624 t)))
5626 (defun org-activate-footnote-links (limit)
5627 "Run through the buffer and add overlays to footnotes."
5628 (let ((fn (org-footnote-next-reference-or-definition limit)))
5629 (when fn
5630 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5631 (org-remove-flyspell-overlays-in beg end)
5632 (add-text-properties beg end
5633 (list 'mouse-face 'highlight
5634 'keymap org-mouse-map
5635 'help-echo
5636 (if (= (point-at-bol) beg)
5637 "Footnote definition"
5638 "Footnote reference")
5639 'font-lock-fontified t
5640 'font-lock-multiline t
5641 'face 'org-footnote))))))
5643 (defun org-activate-bracket-links (limit)
5644 "Run through the buffer and add overlays to bracketed links."
5645 (if (re-search-forward org-bracket-link-regexp limit t)
5646 (let* ((help (concat "LINK: "
5647 (org-match-string-no-properties 1)))
5648 ;; FIXME: above we should remove the escapes.
5649 ;; but that requires another match, protecting match data,
5650 ;; a lot of overhead for font-lock.
5651 (ip (org-maybe-intangible
5652 (list 'invisible 'org-link
5653 'keymap org-mouse-map 'mouse-face 'highlight
5654 'font-lock-multiline t 'help-echo help)))
5655 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5656 'font-lock-multiline t 'help-echo help)))
5657 ;; We need to remove the invisible property here. Table narrowing
5658 ;; may have made some of this invisible.
5659 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5660 (remove-text-properties (match-beginning 0) (match-end 0)
5661 '(invisible nil))
5662 (if (match-end 3)
5663 (progn
5664 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5665 (org-rear-nonsticky-at (match-beginning 3))
5666 (add-text-properties (match-beginning 3) (match-end 3) vp)
5667 (org-rear-nonsticky-at (match-end 3))
5668 (add-text-properties (match-end 3) (match-end 0) ip)
5669 (org-rear-nonsticky-at (match-end 0)))
5670 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5671 (org-rear-nonsticky-at (match-beginning 1))
5672 (add-text-properties (match-beginning 1) (match-end 1) vp)
5673 (org-rear-nonsticky-at (match-end 1))
5674 (add-text-properties (match-end 1) (match-end 0) ip)
5675 (org-rear-nonsticky-at (match-end 0)))
5676 t)))
5678 (defun org-activate-dates (limit)
5679 "Run through the buffer and add overlays to dates."
5680 (if (re-search-forward org-tsr-regexp-both limit t)
5681 (progn
5682 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5683 (add-text-properties (match-beginning 0) (match-end 0)
5684 (list 'mouse-face 'highlight
5685 'keymap org-mouse-map))
5686 (org-rear-nonsticky-at (match-end 0))
5687 (when org-display-custom-times
5688 (if (match-end 3)
5689 (org-display-custom-time (match-beginning 3) (match-end 3)))
5690 (org-display-custom-time (match-beginning 1) (match-end 1)))
5691 t)))
5693 (defvar org-target-link-regexp nil
5694 "Regular expression matching radio targets in plain text.")
5695 (make-variable-buffer-local 'org-target-link-regexp)
5696 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5697 "Regular expression matching a link target.")
5698 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5699 "Regular expression matching a radio target.")
5700 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5701 "Regular expression matching any target.")
5703 (defun org-activate-target-links (limit)
5704 "Run through the buffer and add overlays to target matches."
5705 (when org-target-link-regexp
5706 (let ((case-fold-search t))
5707 (if (re-search-forward org-target-link-regexp limit t)
5708 (progn
5709 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5710 (add-text-properties (match-beginning 0) (match-end 0)
5711 (list 'mouse-face 'highlight
5712 'keymap org-mouse-map
5713 'help-echo "Radio target link"
5714 'org-linked-text t))
5715 (org-rear-nonsticky-at (match-end 0))
5716 t)))))
5718 (defun org-update-radio-target-regexp ()
5719 "Find all radio targets in this file and update the regular expression."
5720 (interactive)
5721 (when (memq 'radio org-activate-links)
5722 (setq org-target-link-regexp
5723 (org-make-target-link-regexp (org-all-targets 'radio)))
5724 (org-restart-font-lock)))
5726 (defun org-hide-wide-columns (limit)
5727 (let (s e)
5728 (setq s (text-property-any (point) (or limit (point-max))
5729 'org-cwidth t))
5730 (when s
5731 (setq e (next-single-property-change s 'org-cwidth))
5732 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5733 (goto-char e)
5734 t)))
5736 (defvar org-latex-and-specials-regexp nil
5737 "Regular expression for highlighting export special stuff.")
5738 (defvar org-match-substring-regexp)
5739 (defvar org-match-substring-with-braces-regexp)
5741 ;; This should be with the exporter code, but we also use if for font-locking
5742 (defconst org-export-html-special-string-regexps
5743 '(("\\\\-" . "&shy;")
5744 ("---\\([^-]\\)" . "&mdash;\\1")
5745 ("--\\([^-]\\)" . "&ndash;\\1")
5746 ("\\.\\.\\." . "&hellip;"))
5747 "Regular expressions for special string conversion.")
5750 (defun org-compute-latex-and-specials-regexp ()
5751 "Compute regular expression for stuff treated specially by exporters."
5752 (if (not org-highlight-latex-fragments-and-specials)
5753 (org-set-local 'org-latex-and-specials-regexp nil)
5754 (require 'org-exp)
5755 (let*
5756 ((matchers (plist-get org-format-latex-options :matchers))
5757 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5758 org-latex-regexps)))
5759 (org-export-allow-BIND nil)
5760 (options (org-combine-plists (org-default-export-plist)
5761 (org-infile-export-plist)))
5762 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5763 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5764 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5765 (org-export-html-expand (plist-get options :expand-quoted-html))
5766 (org-export-with-special-strings (plist-get options :special-strings))
5767 (re-sub
5768 (cond
5769 ((equal org-export-with-sub-superscripts '{})
5770 (list org-match-substring-with-braces-regexp))
5771 (org-export-with-sub-superscripts
5772 (list org-match-substring-regexp))))
5773 (re-latex
5774 (if org-export-with-LaTeX-fragments
5775 (mapcar (lambda (x) (nth 1 x)) latexs)))
5776 (re-macros
5777 (if org-export-with-TeX-macros
5778 (list (concat "\\\\"
5779 (regexp-opt
5780 (append
5782 (delq nil
5783 (mapcar 'car-safe
5784 (append org-entities-user
5785 org-entities)))
5786 (if (boundp 'org-latex-entities)
5787 (mapcar (lambda (x)
5788 (or (car-safe x) x))
5789 org-latex-entities)
5790 nil))
5791 'words))) ; FIXME
5793 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5794 (re-special (if org-export-with-special-strings
5795 (mapcar (lambda (x) (car x))
5796 org-export-html-special-string-regexps)))
5797 (re-rest
5798 (delq nil
5799 (list
5800 (if org-export-html-expand "@<[^>\n]+>")
5801 ))))
5802 (org-set-local
5803 'org-latex-and-specials-regexp
5804 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5805 re-rest) "\\|")))))
5807 (defun org-do-latex-and-special-faces (limit)
5808 "Run through the buffer and add overlays to links."
5809 (when org-latex-and-specials-regexp
5810 (let (rtn d)
5811 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5812 limit t))
5813 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5814 'face))
5815 '(org-code org-verbatim underline)))
5816 (progn
5817 (setq rtn t
5818 d (cond ((member (char-after (1+ (match-beginning 0)))
5819 '(?_ ?^)) 1)
5820 (t 0)))
5821 (font-lock-prepend-text-property
5822 (+ d (match-beginning 0)) (match-end 0)
5823 'face 'org-latex-and-export-specials)
5824 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5825 '(font-lock-multiline t)))))
5826 rtn)))
5828 (defun org-restart-font-lock ()
5829 "Restart `font-lock-mode', to force refontification."
5830 (when (and (boundp 'font-lock-mode) font-lock-mode)
5831 (font-lock-mode -1)
5832 (font-lock-mode 1)))
5834 (defun org-all-targets (&optional radio)
5835 "Return a list of all targets in this file.
5836 With optional argument RADIO, only find radio targets."
5837 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5838 rtn)
5839 (save-excursion
5840 (goto-char (point-min))
5841 (while (re-search-forward re nil t)
5842 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5843 rtn)))
5845 (defun org-make-target-link-regexp (targets)
5846 "Make regular expression matching all strings in TARGETS.
5847 The regular expression finds the targets also if there is a line break
5848 between words."
5849 (and targets
5850 (concat
5851 "\\<\\("
5852 (mapconcat
5853 (lambda (x)
5854 (setq x (regexp-quote x))
5855 (while (string-match " +" x)
5856 (setq x (replace-match "\\s-+" t t x)))
5858 targets
5859 "\\|")
5860 "\\)\\>")))
5862 (defun org-activate-tags (limit)
5863 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5864 (progn
5865 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5866 (add-text-properties (match-beginning 1) (match-end 1)
5867 (list 'mouse-face 'highlight
5868 'keymap org-mouse-map))
5869 (org-rear-nonsticky-at (match-end 1))
5870 t)))
5872 (defun org-outline-level ()
5873 "Compute the outline level of the heading at point.
5874 This function assumes that the cursor is at the beginning of a line matched
5875 by `outline-regexp'. Otherwise it returns garbage.
5876 If this is called at a normal headline, the level is the number of stars.
5877 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5878 (save-excursion
5879 (looking-at org-outline-regexp)
5880 (1- (- (match-end 0) (match-beginning 0)))))
5882 (defvar org-font-lock-keywords nil)
5884 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5885 "Regular expression matching a property line.")
5887 (defvar org-font-lock-hook nil
5888 "Functions to be called for special font lock stuff.")
5890 (defvar org-font-lock-set-keywords-hook nil
5891 "Functions that can manipulate `org-font-lock-extra-keywords'.
5892 This is called after `org-font-lock-extra-keywords' is defined, but before
5893 it is installed to be used by font lock. This can be useful if something
5894 needs to be inserted at a specific position in the font-lock sequence.")
5896 (defun org-font-lock-hook (limit)
5897 (run-hook-with-args 'org-font-lock-hook limit))
5899 (defun org-set-font-lock-defaults ()
5900 (let* ((em org-fontify-emphasized-text)
5901 (lk org-activate-links)
5902 (org-font-lock-extra-keywords
5903 (list
5904 ;; Call the hook
5905 '(org-font-lock-hook)
5906 ;; Headlines
5907 `(,(if org-fontify-whole-heading-line
5908 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5909 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5910 (1 (org-get-level-face 1))
5911 (2 (org-get-level-face 2))
5912 (3 (org-get-level-face 3)))
5913 ;; Table lines
5914 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5915 (1 'org-table t))
5916 ;; Table internals
5917 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5918 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5919 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5920 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5921 ;; Drawers
5922 (list org-drawer-regexp '(0 'org-special-keyword t))
5923 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5924 ;; Properties
5925 (list org-property-re
5926 '(1 'org-special-keyword t)
5927 '(3 'org-property-value t))
5928 ;; Links
5929 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5930 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5931 (if (memq 'plain lk) '(org-activate-plain-links))
5932 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5933 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5934 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5935 (if (memq 'footnote lk) '(org-activate-footnote-links))
5936 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5937 '(org-hide-wide-columns (0 nil append))
5938 ;; TODO keyword
5939 (list (format org-heading-keyword-regexp-format
5940 org-todo-regexp)
5941 '(2 (org-get-todo-face 2) t))
5942 ;; DONE
5943 (if org-fontify-done-headline
5944 (list (format org-heading-keyword-regexp-format
5945 (concat
5946 "\\(?:"
5947 (mapconcat 'regexp-quote org-done-keywords "\\|")
5948 "\\)"))
5949 '(2 'org-headline-done t))
5950 nil)
5951 ;; Priorities
5952 '(org-font-lock-add-priority-faces)
5953 ;; Tags
5954 '(org-font-lock-add-tag-faces)
5955 ;; Special keywords
5956 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5957 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5958 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5959 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5960 ;; Emphasis
5961 (if em
5962 (if (featurep 'xemacs)
5963 '(org-do-emphasis-faces (0 nil append))
5964 '(org-do-emphasis-faces)))
5965 ;; Checkboxes
5966 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5967 1 'org-checkbox prepend)
5968 (if (cdr (assq 'checkbox org-list-automatic-rules))
5969 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5970 (0 (org-get-checkbox-statistics-face) t)))
5971 ;; Description list items
5972 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5973 1 'org-list-dt prepend)
5974 ;; ARCHIVEd headings
5975 (list (concat
5976 org-outline-regexp-bol
5977 "\\(.*:" org-archive-tag ":.*\\)")
5978 '(1 'org-archived prepend))
5979 ;; Specials
5980 '(org-do-latex-and-special-faces)
5981 '(org-fontify-entities)
5982 '(org-raise-scripts)
5983 ;; Code
5984 '(org-activate-code (1 'org-code t))
5985 ;; COMMENT
5986 (list (format org-heading-keyword-regexp-format
5987 (concat "\\("
5988 org-comment-string "\\|" org-quote-string
5989 "\\)"))
5990 '(2 'org-special-keyword t))
5991 ;; Blocks and meta lines
5992 '(org-fontify-meta-lines-and-blocks)
5994 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5995 (run-hooks 'org-font-lock-set-keywords-hook)
5996 ;; Now set the full font-lock-keywords
5997 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5998 (org-set-local 'font-lock-defaults
5999 '(org-font-lock-keywords t nil nil backward-paragraph))
6000 (kill-local-variable 'font-lock-keywords) nil))
6002 (defun org-toggle-pretty-entities ()
6003 "Toggle the composition display of entities as UTF8 characters."
6004 (interactive)
6005 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6006 (org-restart-font-lock)
6007 (if org-pretty-entities
6008 (message "Entities are displayed as UTF8 characters")
6009 (save-restriction
6010 (widen)
6011 (org-decompose-region (point-min) (point-max))
6012 (message "Entities are displayed plain"))))
6014 (defvar org-custom-properties-overlays nil
6015 "List of overlays used for custom properties.")
6016 (make-variable-buffer-local 'org-custom-properties-overlays)
6018 (defun org-toggle-custom-properties-visibility ()
6019 "Display or hide properties in `org-custom-properties'."
6020 (interactive)
6021 (if org-custom-properties-overlays
6022 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6023 (setq org-custom-properties-overlays nil))
6024 (unless (not org-custom-properties)
6025 (save-excursion
6026 (save-restriction
6027 (widen)
6028 (goto-char (point-min))
6029 (while (re-search-forward org-property-re nil t)
6030 (mapc (lambda(p)
6031 (when (equal p (substring (match-string 1) 1 -1))
6032 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6033 (overlay-put o 'invisible t)
6034 (overlay-put o 'org-custom-property t)
6035 (push o org-custom-properties-overlays))))
6036 org-custom-properties)))))))
6038 (defun org-fontify-entities (limit)
6039 "Find an entity to fontify."
6040 (let (ee)
6041 (when org-pretty-entities
6042 (catch 'match
6043 (while (re-search-forward
6044 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6045 limit t)
6046 (if (and (not (org-in-indented-comment-line))
6047 (setq ee (org-entity-get (match-string 1)))
6048 (= (length (nth 6 ee)) 1))
6049 (let*
6050 ((end (if (equal (match-string 2) "{}")
6051 (match-end 2)
6052 (match-end 1))))
6053 (add-text-properties
6054 (match-beginning 0) end
6055 (list 'font-lock-fontified t))
6056 (compose-region (match-beginning 0) end
6057 (nth 6 ee) nil)
6058 (backward-char 1)
6059 (throw 'match t))))
6060 nil))))
6062 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6063 "Fontify string S like in Org-mode."
6064 (with-temp-buffer
6065 (insert s)
6066 (let ((org-odd-levels-only odd-levels))
6067 (org-mode)
6068 (font-lock-fontify-buffer)
6069 (buffer-string))))
6071 (defvar org-m nil)
6072 (defvar org-l nil)
6073 (defvar org-f nil)
6074 (defun org-get-level-face (n)
6075 "Get the right face for match N in font-lock matching of headlines."
6076 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6077 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6078 (if org-cycle-level-faces
6079 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6080 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6081 (cond
6082 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6083 ((eq n 2) org-f)
6084 (t (if org-level-color-stars-only nil org-f))))
6087 (defun org-get-todo-face (kwd)
6088 "Get the right face for a TODO keyword KWD.
6089 If KWD is a number, get the corresponding match group."
6090 (if (numberp kwd) (setq kwd (match-string kwd)))
6091 (or (org-face-from-face-or-color
6092 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6093 (and (member kwd org-done-keywords) 'org-done)
6094 'org-todo))
6096 (defun org-face-from-face-or-color (context inherit face-or-color)
6097 "Create a face list that inherits INHERIT, but sets the foreground color.
6098 When FACE-OR-COLOR is not a string, just return it."
6099 (if (stringp face-or-color)
6100 (list :inherit inherit
6101 (cdr (assoc context org-faces-easy-properties))
6102 face-or-color)
6103 face-or-color))
6105 (defun org-font-lock-add-tag-faces (limit)
6106 "Add the special tag faces."
6107 (when (and org-tag-faces org-tags-special-faces-re)
6108 (while (re-search-forward org-tags-special-faces-re limit t)
6109 (add-text-properties (match-beginning 1) (match-end 1)
6110 (list 'face (org-get-tag-face 1)
6111 'font-lock-fontified t))
6112 (backward-char 1))))
6114 (defun org-font-lock-add-priority-faces (limit)
6115 "Add the special priority faces."
6116 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6117 (when (save-match-data (org-at-heading-p))
6118 (add-text-properties
6119 (match-beginning 0) (match-end 0)
6120 (list 'face (or (org-face-from-face-or-color
6121 'priority 'org-special-keyword
6122 (cdr (assoc (char-after (match-beginning 1))
6123 org-priority-faces)))
6124 'org-special-keyword)
6125 'font-lock-fontified t)))))
6127 (defun org-get-tag-face (kwd)
6128 "Get the right face for a TODO keyword KWD.
6129 If KWD is a number, get the corresponding match group."
6130 (if (numberp kwd) (setq kwd (match-string kwd)))
6131 (or (org-face-from-face-or-color
6132 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6133 'org-tag))
6135 (defun org-unfontify-region (beg end &optional maybe_loudly)
6136 "Remove fontification and activation overlays from links."
6137 (font-lock-default-unfontify-region beg end)
6138 (let* ((buffer-undo-list t)
6139 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6140 (inhibit-modification-hooks t)
6141 deactivate-mark buffer-file-name buffer-file-truename)
6142 (org-decompose-region beg end)
6143 (remove-text-properties beg end
6144 '(mouse-face t keymap t org-linked-text t
6145 invisible t intangible t
6146 org-no-flyspell t org-emphasis t))
6147 (org-remove-font-lock-display-properties beg end)))
6149 (defconst org-script-display '(((raise -0.3) (height 0.7))
6150 ((raise 0.3) (height 0.7))
6151 ((raise -0.5))
6152 ((raise 0.5)))
6153 "Display properties for showing superscripts and subscripts.")
6155 (defun org-remove-font-lock-display-properties (beg end)
6156 "Remove specific display properties that have been added by font lock.
6157 The will remove the raise properties that are used to show superscripts
6158 and subscripts."
6159 (let (next prop)
6160 (while (< beg end)
6161 (setq next (next-single-property-change beg 'display nil end)
6162 prop (get-text-property beg 'display))
6163 (if (member prop org-script-display)
6164 (put-text-property beg next 'display nil))
6165 (setq beg next))))
6167 (defun org-raise-scripts (limit)
6168 "Add raise properties to sub/superscripts."
6169 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6170 (if (re-search-forward
6171 (if (eq org-use-sub-superscripts t)
6172 org-match-substring-regexp
6173 org-match-substring-with-braces-regexp)
6174 limit t)
6175 (let* ((pos (point)) table-p comment-p
6176 (mpos (match-beginning 3))
6177 (emph-p (get-text-property mpos 'org-emphasis))
6178 (link-p (get-text-property mpos 'mouse-face))
6179 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6180 (goto-char (point-at-bol))
6181 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6182 comment-p (org-looking-at-p "[ \t]*#"))
6183 (goto-char pos)
6184 ;; FIXME: Should we go back one character here, for a_b^c
6185 ;; (goto-char (1- pos)) ;????????????????????
6186 (if (or comment-p emph-p link-p keyw-p)
6188 (put-text-property (match-beginning 3) (match-end 0)
6189 'display
6190 (if (equal (char-after (match-beginning 2)) ?^)
6191 (nth (if table-p 3 1) org-script-display)
6192 (nth (if table-p 2 0) org-script-display)))
6193 (add-text-properties (match-beginning 2) (match-end 2)
6194 (list 'invisible t
6195 'org-dwidth t 'org-dwidth-n 1))
6196 (if (and (eq (char-after (match-beginning 3)) ?{)
6197 (eq (char-before (match-end 3)) ?}))
6198 (progn
6199 (add-text-properties
6200 (match-beginning 3) (1+ (match-beginning 3))
6201 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6202 (add-text-properties
6203 (1- (match-end 3)) (match-end 3)
6204 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6205 t)))))
6207 ;;;; Visibility cycling, including org-goto and indirect buffer
6209 ;;; Cycling
6211 (defvar org-cycle-global-status nil)
6212 (make-variable-buffer-local 'org-cycle-global-status)
6213 (defvar org-cycle-subtree-status nil)
6214 (make-variable-buffer-local 'org-cycle-subtree-status)
6216 ;;;###autoload
6218 (defvar org-inlinetask-min-level)
6220 (defun org-cycle (&optional arg)
6221 "TAB-action and visibility cycling for Org-mode.
6223 This is the command invoked in Org-mode by the TAB key. Its main purpose
6224 is outline visibility cycling, but it also invokes other actions
6225 in special contexts.
6227 - When this function is called with a prefix argument, rotate the entire
6228 buffer through 3 states (global cycling)
6229 1. OVERVIEW: Show only top-level headlines.
6230 2. CONTENTS: Show all headlines of all levels, but no body text.
6231 3. SHOW ALL: Show everything.
6232 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6233 determined by the variable `org-startup-folded', and by any VISIBILITY
6234 properties in the buffer.
6235 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6236 including any drawers.
6238 - When inside a table, re-align the table and move to the next field.
6240 - When point is at the beginning of a headline, rotate the subtree started
6241 by this line through 3 different states (local cycling)
6242 1. FOLDED: Only the main headline is shown.
6243 2. CHILDREN: The main headline and the direct children are shown.
6244 From this state, you can move to one of the children
6245 and zoom in further.
6246 3. SUBTREE: Show the entire subtree, including body text.
6247 If there is no subtree, switch directly from CHILDREN to FOLDED.
6249 - When point is at the beginning of an empty headline and the variable
6250 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6251 of the headline by demoting and promoting it to likely levels. This
6252 speeds up creation document structure by pressing TAB once or several
6253 times right after creating a new headline.
6255 - When there is a numeric prefix, go up to a heading with level ARG, do
6256 a `show-subtree' and return to the previous cursor position. If ARG
6257 is negative, go up that many levels.
6259 - When point is not at the beginning of a headline, execute the global
6260 binding for TAB, which is re-indenting the line. See the option
6261 `org-cycle-emulate-tab' for details.
6263 - Special case: if point is at the beginning of the buffer and there is
6264 no headline in line 1, this function will act as if called with prefix arg
6265 (C-u TAB, same as S-TAB) also when called without prefix arg.
6266 But only if also the variable `org-cycle-global-at-bob' is t."
6267 (interactive "P")
6268 (org-load-modules-maybe)
6269 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6270 (and org-cycle-level-after-item/entry-creation
6271 (or (org-cycle-level)
6272 (org-cycle-item-indentation))))
6273 (let* ((limit-level
6274 (or org-cycle-max-level
6275 (and (boundp 'org-inlinetask-min-level)
6276 org-inlinetask-min-level
6277 (1- org-inlinetask-min-level))))
6278 (nstars (and limit-level
6279 (if org-odd-levels-only
6280 (and limit-level (1- (* limit-level 2)))
6281 limit-level)))
6282 (org-outline-regexp
6283 (if (not (derived-mode-p 'org-mode))
6284 outline-regexp
6285 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6286 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6287 (not (looking-at org-outline-regexp))))
6288 (org-cycle-hook
6289 (if bob-special
6290 (delq 'org-optimize-window-after-visibility-change
6291 (copy-sequence org-cycle-hook))
6292 org-cycle-hook))
6293 (pos (point)))
6295 (if (or bob-special (equal arg '(4)))
6296 ;; special case: use global cycling
6297 (setq arg t))
6299 (cond
6301 ((equal arg '(16))
6302 (setq last-command 'dummy)
6303 (org-set-startup-visibility)
6304 (message "Startup visibility, plus VISIBILITY properties"))
6306 ((equal arg '(64))
6307 (show-all)
6308 (message "Entire buffer visible, including drawers"))
6310 ;; Table: enter it or move to the next field.
6311 ((org-at-table-p 'any)
6312 (if (org-at-table.el-p)
6313 (message "Use C-c ' to edit table.el tables")
6314 (if arg (org-table-edit-field t)
6315 (org-table-justify-field-maybe)
6316 (call-interactively 'org-table-next-field))))
6318 ((run-hook-with-args-until-success
6319 'org-tab-after-check-for-table-hook))
6321 ;; Global cycling: delegate to `org-cycle-internal-global'.
6322 ((eq arg t) (org-cycle-internal-global))
6324 ;; Drawers: delegate to `org-flag-drawer'.
6325 ((and org-drawers org-drawer-regexp
6326 (save-excursion
6327 (beginning-of-line 1)
6328 (looking-at org-drawer-regexp)))
6329 (org-flag-drawer ; toggle block visibility
6330 (not (get-char-property (match-end 0) 'invisible))))
6332 ;; Show-subtree, ARG levels up from here.
6333 ((integerp arg)
6334 (save-excursion
6335 (org-back-to-heading)
6336 (outline-up-heading (if (< arg 0) (- arg)
6337 (- (funcall outline-level) arg)))
6338 (org-show-subtree)))
6340 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6341 ((and (featurep 'org-inlinetask)
6342 (org-inlinetask-at-task-p)
6343 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6344 (org-inlinetask-toggle-visibility))
6346 ((org-try-cdlatex-tab))
6348 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6349 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6350 (save-excursion (beginning-of-line 1)
6351 (looking-at org-outline-regexp)))
6352 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6353 (org-cycle-internal-local))
6355 ;; From there: TAB emulation and template completion.
6356 (buffer-read-only (org-back-to-heading))
6358 ((run-hook-with-args-until-success
6359 'org-tab-after-check-for-cycling-hook))
6361 ((org-try-structure-completion))
6363 ((run-hook-with-args-until-success
6364 'org-tab-before-tab-emulation-hook))
6366 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6367 (or (not (bolp))
6368 (not (looking-at org-outline-regexp))))
6369 (call-interactively (global-key-binding "\t")))
6371 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6372 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6373 (or (and (eq org-cycle-emulate-tab 'white)
6374 (= (match-end 0) (point-at-eol)))
6375 (and (eq org-cycle-emulate-tab 'whitestart)
6376 (>= (match-end 0) pos))))
6378 (eq org-cycle-emulate-tab t))
6379 (call-interactively (global-key-binding "\t")))
6381 (t (save-excursion
6382 (org-back-to-heading)
6383 (org-cycle)))))))
6385 (defun org-cycle-internal-global ()
6386 "Do the global cycling action."
6387 ;; Hack to avoid display of messages for .org attachments in Gnus
6388 (let ((ga (string-match "\\*fontification" (buffer-name))))
6389 (cond
6390 ((and (eq last-command this-command)
6391 (eq org-cycle-global-status 'overview))
6392 ;; We just created the overview - now do table of contents
6393 ;; This can be slow in very large buffers, so indicate action
6394 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6395 (unless ga (message "CONTENTS..."))
6396 (org-content)
6397 (unless ga (message "CONTENTS...done"))
6398 (setq org-cycle-global-status 'contents)
6399 (run-hook-with-args 'org-cycle-hook 'contents))
6401 ((and (eq last-command this-command)
6402 (eq org-cycle-global-status 'contents))
6403 ;; We just showed the table of contents - now show everything
6404 (run-hook-with-args 'org-pre-cycle-hook 'all)
6405 (show-all)
6406 (unless ga (message "SHOW ALL"))
6407 (setq org-cycle-global-status 'all)
6408 (run-hook-with-args 'org-cycle-hook 'all))
6411 ;; Default action: go to overview
6412 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6413 (org-overview)
6414 (unless ga (message "OVERVIEW"))
6415 (setq org-cycle-global-status 'overview)
6416 (run-hook-with-args 'org-cycle-hook 'overview)))))
6418 (defun org-cycle-internal-local ()
6419 "Do the local cycling action."
6420 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6421 ;; First, determine end of headline (EOH), end of subtree or item
6422 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6423 (save-excursion
6424 (if (org-at-item-p)
6425 (progn
6426 (beginning-of-line)
6427 (setq struct (org-list-struct))
6428 (setq eoh (point-at-eol))
6429 (setq eos (org-list-get-item-end-before-blank (point) struct))
6430 (setq has-children (org-list-has-child-p (point) struct)))
6431 (org-back-to-heading)
6432 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6433 (setq eos (save-excursion
6434 (org-end-of-subtree t)
6435 (unless (eobp)
6436 (skip-chars-forward " \t\n"))
6437 (if (eobp) (point) (1- (point)))))
6438 (setq has-children
6439 (or (save-excursion
6440 (let ((level (funcall outline-level)))
6441 (outline-next-heading)
6442 (and (org-at-heading-p t)
6443 (> (funcall outline-level) level))))
6444 (save-excursion
6445 (org-list-search-forward (org-item-beginning-re) eos t)))))
6446 ;; Determine end invisible part of buffer (EOL)
6447 (beginning-of-line 2)
6448 ;; XEmacs doesn't have `next-single-char-property-change'
6449 (if (featurep 'xemacs)
6450 (while (and (not (eobp)) ;; this is like `next-line'
6451 (get-char-property (1- (point)) 'invisible))
6452 (beginning-of-line 2))
6453 (while (and (not (eobp)) ;; this is like `next-line'
6454 (get-char-property (1- (point)) 'invisible))
6455 (goto-char (next-single-char-property-change (point) 'invisible))
6456 (and (eolp) (beginning-of-line 2))))
6457 (setq eol (point)))
6458 ;; Find out what to do next and set `this-command'
6459 (cond
6460 ((= eos eoh)
6461 ;; Nothing is hidden behind this heading
6462 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6463 (message "EMPTY ENTRY")
6464 (setq org-cycle-subtree-status nil)
6465 (save-excursion
6466 (goto-char eos)
6467 (outline-next-heading)
6468 (if (outline-invisible-p) (org-flag-heading nil))))
6469 ((and (or (>= eol eos)
6470 (not (string-match "\\S-" (buffer-substring eol eos))))
6471 (or has-children
6472 (not (setq children-skipped
6473 org-cycle-skip-children-state-if-no-children))))
6474 ;; Entire subtree is hidden in one line: children view
6475 (run-hook-with-args 'org-pre-cycle-hook 'children)
6476 (if (org-at-item-p)
6477 (org-list-set-item-visibility (point-at-bol) struct 'children)
6478 (org-show-entry)
6479 (org-with-limited-levels (show-children))
6480 ;; FIXME: This slows down the func way too much.
6481 ;; How keep drawers hidden in subtree anyway?
6482 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6483 ;; (org-cycle-hide-drawers 'subtree))
6485 ;; Fold every list in subtree to top-level items.
6486 (when (eq org-cycle-include-plain-lists 'integrate)
6487 (save-excursion
6488 (org-back-to-heading)
6489 (while (org-list-search-forward (org-item-beginning-re) eos t)
6490 (beginning-of-line 1)
6491 (let* ((struct (org-list-struct))
6492 (prevs (org-list-prevs-alist struct))
6493 (end (org-list-get-bottom-point struct)))
6494 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6495 (org-list-get-all-items (point) struct prevs))
6496 (goto-char end))))))
6497 (message "CHILDREN")
6498 (save-excursion
6499 (goto-char eos)
6500 (outline-next-heading)
6501 (if (outline-invisible-p) (org-flag-heading nil)))
6502 (setq org-cycle-subtree-status 'children)
6503 (run-hook-with-args 'org-cycle-hook 'children))
6504 ((or children-skipped
6505 (and (eq last-command this-command)
6506 (eq org-cycle-subtree-status 'children)))
6507 ;; We just showed the children, or no children are there,
6508 ;; now show everything.
6509 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6510 (outline-flag-region eoh eos nil)
6511 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6512 (setq org-cycle-subtree-status 'subtree)
6513 (run-hook-with-args 'org-cycle-hook 'subtree))
6515 ;; Default action: hide the subtree.
6516 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6517 (outline-flag-region eoh eos t)
6518 (message "FOLDED")
6519 (setq org-cycle-subtree-status 'folded)
6520 (run-hook-with-args 'org-cycle-hook 'folded)))))
6522 ;;;###autoload
6523 (defun org-global-cycle (&optional arg)
6524 "Cycle the global visibility. For details see `org-cycle'.
6525 With \\[universal-argument] prefix arg, switch to startup visibility.
6526 With a numeric prefix, show all headlines up to that level."
6527 (interactive "P")
6528 (let ((org-cycle-include-plain-lists
6529 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6530 (cond
6531 ((integerp arg)
6532 (show-all)
6533 (hide-sublevels arg)
6534 (setq org-cycle-global-status 'contents))
6535 ((equal arg '(4))
6536 (org-set-startup-visibility)
6537 (message "Startup visibility, plus VISIBILITY properties."))
6539 (org-cycle '(4))))))
6541 (defun org-set-startup-visibility ()
6542 "Set the visibility required by startup options and properties."
6543 (cond
6544 ((eq org-startup-folded t)
6545 (org-cycle '(4)))
6546 ((eq org-startup-folded 'content)
6547 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6548 (org-cycle '(4)) (org-cycle '(4)))))
6549 (unless (eq org-startup-folded 'showeverything)
6550 (if org-hide-block-startup (org-hide-block-all))
6551 (org-set-visibility-according-to-property 'no-cleanup)
6552 (org-cycle-hide-archived-subtrees 'all)
6553 (org-cycle-hide-drawers 'all)
6554 (org-cycle-show-empty-lines t)))
6556 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6557 "Switch subtree visibilities according to :VISIBILITY: property."
6558 (interactive)
6559 (let (org-show-entry-below state)
6560 (save-excursion
6561 (goto-char (point-min))
6562 (while (re-search-forward
6563 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6564 nil t)
6565 (setq state (match-string 1))
6566 (save-excursion
6567 (org-back-to-heading t)
6568 (hide-subtree)
6569 (org-reveal)
6570 (cond
6571 ((equal state '("fold" "folded"))
6572 (hide-subtree))
6573 ((equal state "children")
6574 (org-show-hidden-entry)
6575 (show-children))
6576 ((equal state "content")
6577 (save-excursion
6578 (save-restriction
6579 (org-narrow-to-subtree)
6580 (org-content))))
6581 ((member state '("all" "showall"))
6582 (show-subtree)))))
6583 (unless no-cleanup
6584 (org-cycle-hide-archived-subtrees 'all)
6585 (org-cycle-hide-drawers 'all)
6586 (org-cycle-show-empty-lines 'all)))))
6588 ;; This function uses outline-regexp instead of the more fundamental
6589 ;; org-outline-regexp so that org-cycle-global works outside of Org
6590 ;; buffers, where outline-regexp is needed.
6591 (defun org-overview ()
6592 "Switch to overview mode, showing only top-level headlines.
6593 Really, this shows all headlines with level equal or greater than the level
6594 of the first headline in the buffer. This is important, because if the
6595 first headline is not level one, then (hide-sublevels 1) gives confusing
6596 results."
6597 (interactive)
6598 (let ((level (save-excursion
6599 (goto-char (point-min))
6600 (if (re-search-forward (concat "^" outline-regexp) nil t)
6601 (progn
6602 (goto-char (match-beginning 0))
6603 (funcall outline-level))))))
6604 (and level (hide-sublevels level))))
6606 (defun org-content (&optional arg)
6607 "Show all headlines in the buffer, like a table of contents.
6608 With numerical argument N, show content up to level N."
6609 (interactive "P")
6610 (save-excursion
6611 ;; Visit all headings and show their offspring
6612 (and (integerp arg) (org-overview))
6613 (goto-char (point-max))
6614 (catch 'exit
6615 (while (and (progn (condition-case nil
6616 (outline-previous-visible-heading 1)
6617 (error (goto-char (point-min))))
6619 (looking-at org-outline-regexp))
6620 (if (integerp arg)
6621 (show-children (1- arg))
6622 (show-branches))
6623 (if (bobp) (throw 'exit nil))))))
6626 (defun org-optimize-window-after-visibility-change (state)
6627 "Adjust the window after a change in outline visibility.
6628 This function is the default value of the hook `org-cycle-hook'."
6629 (when (get-buffer-window (current-buffer))
6630 (cond
6631 ((eq state 'content) nil)
6632 ((eq state 'all) nil)
6633 ((eq state 'folded) nil)
6634 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6635 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6637 (defun org-remove-empty-overlays-at (pos)
6638 "Remove outline overlays that do not contain non-white stuff."
6639 (mapc
6640 (lambda (o)
6641 (and (eq 'outline (overlay-get o 'invisible))
6642 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6643 (overlay-end o))))
6644 (delete-overlay o)))
6645 (overlays-at pos)))
6647 (defun org-clean-visibility-after-subtree-move ()
6648 "Fix visibility issues after moving a subtree."
6649 ;; First, find a reasonable region to look at:
6650 ;; Start two siblings above, end three below
6651 (let* ((beg (save-excursion
6652 (and (org-get-last-sibling)
6653 (org-get-last-sibling))
6654 (point)))
6655 (end (save-excursion
6656 (and (org-get-next-sibling)
6657 (org-get-next-sibling)
6658 (org-get-next-sibling))
6659 (if (org-at-heading-p)
6660 (point-at-eol)
6661 (point))))
6662 (level (looking-at "\\*+"))
6663 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6664 (save-excursion
6665 (save-restriction
6666 (narrow-to-region beg end)
6667 (when re
6668 ;; Properly fold already folded siblings
6669 (goto-char (point-min))
6670 (while (re-search-forward re nil t)
6671 (if (and (not (outline-invisible-p))
6672 (save-excursion
6673 (goto-char (point-at-eol)) (outline-invisible-p)))
6674 (hide-entry))))
6675 (org-cycle-show-empty-lines 'overview)
6676 (org-cycle-hide-drawers 'overview)))))
6678 (defun org-cycle-show-empty-lines (state)
6679 "Show empty lines above all visible headlines.
6680 The region to be covered depends on STATE when called through
6681 `org-cycle-hook'. Lisp program can use t for STATE to get the
6682 entire buffer covered. Note that an empty line is only shown if there
6683 are at least `org-cycle-separator-lines' empty lines before the headline."
6684 (when (not (= org-cycle-separator-lines 0))
6685 (save-excursion
6686 (let* ((n (abs org-cycle-separator-lines))
6687 (re (cond
6688 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6689 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6690 (t (let ((ns (number-to-string (- n 2))))
6691 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6692 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6693 beg end b e)
6694 (cond
6695 ((memq state '(overview contents t))
6696 (setq beg (point-min) end (point-max)))
6697 ((memq state '(children folded))
6698 (setq beg (point) end (progn (org-end-of-subtree t t)
6699 (beginning-of-line 2)
6700 (point)))))
6701 (when beg
6702 (goto-char beg)
6703 (while (re-search-forward re end t)
6704 (unless (get-char-property (match-end 1) 'invisible)
6705 (setq e (match-end 1))
6706 (if (< org-cycle-separator-lines 0)
6707 (setq b (save-excursion
6708 (goto-char (match-beginning 0))
6709 (org-back-over-empty-lines)
6710 (if (save-excursion
6711 (goto-char (max (point-min) (1- (point))))
6712 (org-at-heading-p))
6713 (1- (point))
6714 (point))))
6715 (setq b (match-beginning 1)))
6716 (outline-flag-region b e nil)))))))
6717 ;; Never hide empty lines at the end of the file.
6718 (save-excursion
6719 (goto-char (point-max))
6720 (outline-previous-heading)
6721 (outline-end-of-heading)
6722 (if (and (looking-at "[ \t\n]+")
6723 (= (match-end 0) (point-max)))
6724 (outline-flag-region (point) (match-end 0) nil))))
6726 (defun org-show-empty-lines-in-parent ()
6727 "Move to the parent and re-show empty lines before visible headlines."
6728 (save-excursion
6729 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6730 (org-cycle-show-empty-lines context))))
6732 (defun org-files-list ()
6733 "Return `org-agenda-files' list, plus all open org-mode files.
6734 This is useful for operations that need to scan all of a user's
6735 open and agenda-wise Org files."
6736 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6737 (dolist (buf (buffer-list))
6738 (with-current-buffer buf
6739 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6740 (let ((file (expand-file-name (buffer-file-name))))
6741 (unless (member file files)
6742 (push file files))))))
6743 files))
6745 (defsubst org-entry-beginning-position ()
6746 "Return the beginning position of the current entry."
6747 (save-excursion (outline-back-to-heading t) (point)))
6749 (defsubst org-entry-end-position ()
6750 "Return the end position of the current entry."
6751 (save-excursion (outline-next-heading) (point)))
6753 (defun org-cycle-hide-drawers (state)
6754 "Re-hide all drawers after a visibility state change."
6755 (when (and (derived-mode-p 'org-mode)
6756 (not (memq state '(overview folded contents))))
6757 (save-excursion
6758 (let* ((globalp (memq state '(contents all)))
6759 (beg (if globalp (point-min) (point)))
6760 (end (if globalp (point-max)
6761 (if (eq state 'children)
6762 (save-excursion (outline-next-heading) (point))
6763 (org-end-of-subtree t)))))
6764 (goto-char beg)
6765 (while (re-search-forward org-drawer-regexp end t)
6766 (org-flag-drawer t))))))
6768 (defun org-flag-drawer (flag)
6769 "When FLAG is non-nil, hide the drawer we are within.
6770 Otherwise make it visible."
6771 (save-excursion
6772 (beginning-of-line 1)
6773 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6774 (let ((b (match-end 0)))
6775 (if (re-search-forward
6776 "^[ \t]*:END:"
6777 (save-excursion (outline-next-heading) (point)) t)
6778 (outline-flag-region b (point-at-eol) flag)
6779 (error ":END: line missing at position %s" b))))))
6781 (defun org-subtree-end-visible-p ()
6782 "Is the end of the current subtree visible?"
6783 (pos-visible-in-window-p
6784 (save-excursion (org-end-of-subtree t) (point))))
6786 (defun org-first-headline-recenter (&optional N)
6787 "Move cursor to the first headline and recenter the headline.
6788 Optional argument N means put the headline into the Nth line of the window."
6789 (goto-char (point-min))
6790 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6791 (beginning-of-line)
6792 (recenter (prefix-numeric-value N))))
6794 ;;; Saving and restoring visibility
6796 (defun org-outline-overlay-data (&optional use-markers)
6797 "Return a list of the locations of all outline overlays.
6798 These are overlays with the `invisible' property value `outline'.
6799 The return value is a list of cons cells, with start and stop
6800 positions for each overlay.
6801 If USE-MARKERS is set, return the positions as markers."
6802 (let (beg end)
6803 (save-excursion
6804 (save-restriction
6805 (widen)
6806 (delq nil
6807 (mapcar (lambda (o)
6808 (when (eq (overlay-get o 'invisible) 'outline)
6809 (setq beg (overlay-start o)
6810 end (overlay-end o))
6811 (and beg end (> end beg)
6812 (if use-markers
6813 (cons (move-marker (make-marker) beg)
6814 (move-marker (make-marker) end))
6815 (cons beg end)))))
6816 (overlays-in (point-min) (point-max))))))))
6818 (defun org-set-outline-overlay-data (data)
6819 "Create visibility overlays for all positions in DATA.
6820 DATA should have been made by `org-outline-overlay-data'."
6821 (let (o)
6822 (save-excursion
6823 (save-restriction
6824 (widen)
6825 (show-all)
6826 (mapc (lambda (c)
6827 (outline-flag-region (car c) (cdr c) t))
6828 data)))))
6830 ;;; Folding of blocks
6832 (defvar org-hide-block-overlays nil
6833 "Overlays hiding blocks.")
6834 (make-variable-buffer-local 'org-hide-block-overlays)
6836 (defun org-block-map (function &optional start end)
6837 "Call FUNCTION at the head of all source blocks in the current buffer.
6838 Optional arguments START and END can be used to limit the range."
6839 (let ((start (or start (point-min)))
6840 (end (or end (point-max))))
6841 (save-excursion
6842 (goto-char start)
6843 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6844 (save-excursion
6845 (save-match-data
6846 (goto-char (match-beginning 0))
6847 (funcall function)))))))
6849 (defun org-hide-block-toggle-all ()
6850 "Toggle the visibility of all blocks in the current buffer."
6851 (org-block-map #'org-hide-block-toggle))
6853 (defun org-hide-block-all ()
6854 "Fold all blocks in the current buffer."
6855 (interactive)
6856 (org-show-block-all)
6857 (org-block-map #'org-hide-block-toggle-maybe))
6859 (defun org-show-block-all ()
6860 "Unfold all blocks in the current buffer."
6861 (interactive)
6862 (mapc 'delete-overlay org-hide-block-overlays)
6863 (setq org-hide-block-overlays nil))
6865 (defun org-hide-block-toggle-maybe ()
6866 "Toggle visibility of block at point."
6867 (interactive)
6868 (let ((case-fold-search t))
6869 (if (save-excursion
6870 (beginning-of-line 1)
6871 (looking-at org-block-regexp))
6872 (progn (org-hide-block-toggle)
6873 t) ;; to signal that we took action
6874 nil))) ;; to signal that we did not
6876 (defun org-hide-block-toggle (&optional force)
6877 "Toggle the visibility of the current block."
6878 (interactive)
6879 (save-excursion
6880 (beginning-of-line)
6881 (if (re-search-forward org-block-regexp nil t)
6882 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6883 (end (match-end 0)) ;; end of entire body
6885 (if (memq t (mapcar (lambda (overlay)
6886 (eq (overlay-get overlay 'invisible)
6887 'org-hide-block))
6888 (overlays-at start)))
6889 (if (or (not force) (eq force 'off))
6890 (mapc (lambda (ov)
6891 (when (member ov org-hide-block-overlays)
6892 (setq org-hide-block-overlays
6893 (delq ov org-hide-block-overlays)))
6894 (when (eq (overlay-get ov 'invisible)
6895 'org-hide-block)
6896 (delete-overlay ov)))
6897 (overlays-at start)))
6898 (setq ov (make-overlay start end))
6899 (overlay-put ov 'invisible 'org-hide-block)
6900 ;; make the block accessible to isearch
6901 (overlay-put
6902 ov 'isearch-open-invisible
6903 (lambda (ov)
6904 (when (member ov org-hide-block-overlays)
6905 (setq org-hide-block-overlays
6906 (delq ov org-hide-block-overlays)))
6907 (when (eq (overlay-get ov 'invisible)
6908 'org-hide-block)
6909 (delete-overlay ov))))
6910 (push ov org-hide-block-overlays)))
6911 (error "Not looking at a source block"))))
6913 ;; org-tab-after-check-for-cycling-hook
6914 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6915 ;; Remove overlays when changing major mode
6916 (add-hook 'org-mode-hook
6917 (lambda () (org-add-hook 'change-major-mode-hook
6918 'org-show-block-all 'append 'local)))
6920 ;;; Org-goto
6922 (defvar org-goto-window-configuration nil)
6923 (defvar org-goto-marker nil)
6924 (defvar org-goto-map
6925 (let ((map (make-sparse-keymap)))
6926 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6927 (while (setq cmd (pop cmds))
6928 (substitute-key-definition cmd cmd map global-map)))
6929 (suppress-keymap map)
6930 (org-defkey map "\C-m" 'org-goto-ret)
6931 (org-defkey map [(return)] 'org-goto-ret)
6932 (org-defkey map [(left)] 'org-goto-left)
6933 (org-defkey map [(right)] 'org-goto-right)
6934 (org-defkey map [(control ?g)] 'org-goto-quit)
6935 (org-defkey map "\C-i" 'org-cycle)
6936 (org-defkey map [(tab)] 'org-cycle)
6937 (org-defkey map [(down)] 'outline-next-visible-heading)
6938 (org-defkey map [(up)] 'outline-previous-visible-heading)
6939 (if org-goto-auto-isearch
6940 (if (fboundp 'define-key-after)
6941 (define-key-after map [t] 'org-goto-local-auto-isearch)
6942 nil)
6943 (org-defkey map "q" 'org-goto-quit)
6944 (org-defkey map "n" 'outline-next-visible-heading)
6945 (org-defkey map "p" 'outline-previous-visible-heading)
6946 (org-defkey map "f" 'outline-forward-same-level)
6947 (org-defkey map "b" 'outline-backward-same-level)
6948 (org-defkey map "u" 'outline-up-heading))
6949 (org-defkey map "/" 'org-occur)
6950 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6951 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6952 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6953 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6954 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6955 map))
6957 (defconst org-goto-help
6958 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6959 RET=jump to location [Q]uit and return to previous location
6960 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6962 (defvar org-goto-start-pos) ; dynamically scoped parameter
6964 ;; FIXME: Docstring does not mention both interfaces
6965 (defun org-goto (&optional alternative-interface)
6966 "Look up a different location in the current file, keeping current visibility.
6968 When you want look-up or go to a different location in a
6969 document, the fastest way is often to fold the entire buffer and
6970 then dive into the tree. This method has the disadvantage, that
6971 the previous location will be folded, which may not be what you
6972 want.
6974 This command works around this by showing a copy of the current
6975 buffer in an indirect buffer, in overview mode. You can dive
6976 into the tree in that copy, use org-occur and incremental search
6977 to find a location. When pressing RET or `Q', the command
6978 returns to the original buffer in which the visibility is still
6979 unchanged. After RET it will also jump to the location selected
6980 in the indirect buffer and expose the headline hierarchy above.
6982 With a prefix argument, use the alternative interface: e.g. if
6983 `org-goto-interface' is 'outline use 'outline-path-completion."
6984 (interactive "P")
6985 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6986 (org-refile-use-outline-path t)
6987 (org-refile-target-verify-function nil)
6988 (interface
6989 (if (not alternative-interface)
6990 org-goto-interface
6991 (if (eq org-goto-interface 'outline)
6992 'outline-path-completion
6993 'outline)))
6994 (org-goto-start-pos (point))
6995 (selected-point
6996 (if (eq interface 'outline)
6997 (car (org-get-location (current-buffer) org-goto-help))
6998 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6999 (org-refile-check-position pa)
7000 (nth 3 pa)))))
7001 (if selected-point
7002 (progn
7003 (org-mark-ring-push org-goto-start-pos)
7004 (goto-char selected-point)
7005 (if (or (outline-invisible-p) (org-invisible-p2))
7006 (org-show-context 'org-goto)))
7007 (message "Quit"))))
7009 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7010 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7011 (defvar org-goto-local-auto-isearch-map) ; defined below
7013 (defun org-get-location (buf help)
7014 "Let the user select a location in the Org-mode buffer BUF.
7015 This function uses a recursive edit. It returns the selected position
7016 or nil."
7017 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7018 (isearch-hide-immediately nil)
7019 (isearch-search-fun-function
7020 (lambda () 'org-goto-local-search-headings))
7021 (org-goto-selected-point org-goto-exit-command)
7022 (pop-up-frames nil)
7023 (special-display-buffer-names nil)
7024 (special-display-regexps nil)
7025 (special-display-function nil))
7026 (save-excursion
7027 (save-window-excursion
7028 (delete-other-windows)
7029 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7030 (org-pop-to-buffer-same-window
7031 (condition-case nil
7032 (make-indirect-buffer (current-buffer) "*org-goto*")
7033 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7034 (with-output-to-temp-buffer "*Help*"
7035 (princ help))
7036 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7037 (setq buffer-read-only nil)
7038 (let ((org-startup-truncated t)
7039 (org-startup-folded nil)
7040 (org-startup-align-all-tables nil))
7041 (org-mode)
7042 (org-overview))
7043 (setq buffer-read-only t)
7044 (if (and (boundp 'org-goto-start-pos)
7045 (integer-or-marker-p org-goto-start-pos))
7046 (let ((org-show-hierarchy-above t)
7047 (org-show-siblings t)
7048 (org-show-following-heading t))
7049 (goto-char org-goto-start-pos)
7050 (and (outline-invisible-p) (org-show-context)))
7051 (goto-char (point-min)))
7052 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7053 (message "Select location and press RET")
7054 (use-local-map org-goto-map)
7055 (recursive-edit)
7057 (kill-buffer "*org-goto*")
7058 (cons org-goto-selected-point org-goto-exit-command)))
7060 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7061 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7062 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7063 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7065 (defun org-goto-local-search-headings (string bound noerror)
7066 "Search and make sure that any matches are in headlines."
7067 (catch 'return
7068 (while (if isearch-forward
7069 (search-forward string bound noerror)
7070 (search-backward string bound noerror))
7071 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7072 (and (member :headline context)
7073 (not (member :tags context))))
7074 (throw 'return (point))))))
7076 (defun org-goto-local-auto-isearch ()
7077 "Start isearch."
7078 (interactive)
7079 (goto-char (point-min))
7080 (let ((keys (this-command-keys)))
7081 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7082 (isearch-mode t)
7083 (isearch-process-search-char (string-to-char keys)))))
7085 (defun org-goto-ret (&optional arg)
7086 "Finish `org-goto' by going to the new location."
7087 (interactive "P")
7088 (setq org-goto-selected-point (point)
7089 org-goto-exit-command 'return)
7090 (throw 'exit nil))
7092 (defun org-goto-left ()
7093 "Finish `org-goto' by going to the new location."
7094 (interactive)
7095 (if (org-at-heading-p)
7096 (progn
7097 (beginning-of-line 1)
7098 (setq org-goto-selected-point (point)
7099 org-goto-exit-command 'left)
7100 (throw 'exit nil))
7101 (error "Not on a heading")))
7103 (defun org-goto-right ()
7104 "Finish `org-goto' by going to the new location."
7105 (interactive)
7106 (if (org-at-heading-p)
7107 (progn
7108 (setq org-goto-selected-point (point)
7109 org-goto-exit-command 'right)
7110 (throw 'exit nil))
7111 (error "Not on a heading")))
7113 (defun org-goto-quit ()
7114 "Finish `org-goto' without cursor motion."
7115 (interactive)
7116 (setq org-goto-selected-point nil)
7117 (setq org-goto-exit-command 'quit)
7118 (throw 'exit nil))
7120 ;;; Indirect buffer display of subtrees
7122 (defvar org-indirect-dedicated-frame nil
7123 "This is the frame being used for indirect tree display.")
7124 (defvar org-last-indirect-buffer nil)
7126 (defun org-tree-to-indirect-buffer (&optional arg)
7127 "Create indirect buffer and narrow it to current subtree.
7128 With numerical prefix ARG, go up to this level and then take that tree.
7129 If ARG is negative, go up that many levels.
7130 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7131 indirect buffer previously made with this command, to avoid proliferation of
7132 indirect buffers. However, when you call the command with a \
7133 \\[universal-argument] prefix, or
7134 when `org-indirect-buffer-display' is `new-frame', the last buffer
7135 is kept so that you can work with several indirect buffers at the same time.
7136 If `org-indirect-buffer-display' is `dedicated-frame', the \
7137 \\[universal-argument] prefix also
7138 requests that a new frame be made for the new buffer, so that the dedicated
7139 frame is not changed."
7140 (interactive "P")
7141 (let ((cbuf (current-buffer))
7142 (cwin (selected-window))
7143 (pos (point))
7144 beg end level heading ibuf)
7145 (save-excursion
7146 (org-back-to-heading t)
7147 (when (numberp arg)
7148 (setq level (org-outline-level))
7149 (if (< arg 0) (setq arg (+ level arg)))
7150 (while (> (setq level (org-outline-level)) arg)
7151 (outline-up-heading 1 t)))
7152 (setq beg (point)
7153 heading (org-get-heading))
7154 (org-end-of-subtree t t)
7155 (if (org-at-heading-p) (backward-char 1))
7156 (setq end (point)))
7157 (if (and (buffer-live-p org-last-indirect-buffer)
7158 (not (eq org-indirect-buffer-display 'new-frame))
7159 (not arg))
7160 (kill-buffer org-last-indirect-buffer))
7161 (setq ibuf (org-get-indirect-buffer cbuf)
7162 org-last-indirect-buffer ibuf)
7163 (cond
7164 ((or (eq org-indirect-buffer-display 'new-frame)
7165 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7166 (select-frame (make-frame))
7167 (delete-other-windows)
7168 (org-pop-to-buffer-same-window ibuf)
7169 (org-set-frame-title heading))
7170 ((eq org-indirect-buffer-display 'dedicated-frame)
7171 (raise-frame
7172 (select-frame (or (and org-indirect-dedicated-frame
7173 (frame-live-p org-indirect-dedicated-frame)
7174 org-indirect-dedicated-frame)
7175 (setq org-indirect-dedicated-frame (make-frame)))))
7176 (delete-other-windows)
7177 (org-pop-to-buffer-same-window ibuf)
7178 (org-set-frame-title (concat "Indirect: " heading)))
7179 ((eq org-indirect-buffer-display 'current-window)
7180 (org-pop-to-buffer-same-window ibuf))
7181 ((eq org-indirect-buffer-display 'other-window)
7182 (pop-to-buffer ibuf))
7183 (t (error "Invalid value")))
7184 (if (featurep 'xemacs)
7185 (save-excursion (org-mode) (turn-on-font-lock)))
7186 (narrow-to-region beg end)
7187 (show-all)
7188 (goto-char pos)
7189 (run-hook-with-args 'org-cycle-hook 'all)
7190 (and (window-live-p cwin) (select-window cwin))))
7192 (defun org-get-indirect-buffer (&optional buffer)
7193 (setq buffer (or buffer (current-buffer)))
7194 (let ((n 1) (base (buffer-name buffer)) bname)
7195 (while (buffer-live-p
7196 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7197 (setq n (1+ n)))
7198 (condition-case nil
7199 (make-indirect-buffer buffer bname 'clone)
7200 (error (make-indirect-buffer buffer bname)))))
7202 (defun org-set-frame-title (title)
7203 "Set the title of the current frame to the string TITLE."
7204 ;; FIXME: how to name a single frame in XEmacs???
7205 (unless (featurep 'xemacs)
7206 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7208 ;;;; Structure editing
7210 ;;; Inserting headlines
7212 (defun org-previous-line-empty-p ()
7213 (save-excursion
7214 (and (not (bobp))
7215 (or (beginning-of-line 0) t)
7216 (save-match-data
7217 (looking-at "[ \t]*$")))))
7219 (defun org-insert-heading (&optional force-heading invisible-ok)
7220 "Insert a new heading or item with same depth at point.
7221 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7222 If point is at the beginning of a headline, insert a sibling before the
7223 current headline. If point is not at the beginning, split the line,
7224 create the new headline with the text in the current line after point
7225 \(but see also the variable `org-M-RET-may-split-line').
7227 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7228 This is important for non-interactive uses of the command."
7229 (interactive "P")
7230 (if (or (= (buffer-size) 0)
7231 (and (not (save-excursion
7232 (and (ignore-errors (org-back-to-heading invisible-ok))
7233 (org-at-heading-p))))
7234 (or force-heading (not (org-in-item-p)))))
7235 (progn
7236 (insert "\n* ")
7237 (run-hooks 'org-insert-heading-hook))
7238 (when (or force-heading (not (org-insert-item)))
7239 (let* ((empty-line-p nil)
7240 (level nil)
7241 (on-heading (org-at-heading-p))
7242 (head (save-excursion
7243 (condition-case nil
7244 (progn
7245 (org-back-to-heading invisible-ok)
7246 (when (and (not on-heading)
7247 (featurep 'org-inlinetask)
7248 (integerp org-inlinetask-min-level)
7249 (>= (length (match-string 0))
7250 org-inlinetask-min-level))
7251 ;; Find a heading level before the inline task
7252 (while (and (setq level (org-up-heading-safe))
7253 (>= level org-inlinetask-min-level)))
7254 (if (org-at-heading-p)
7255 (org-back-to-heading invisible-ok)
7256 (error "This should not happen")))
7257 (setq empty-line-p (org-previous-line-empty-p))
7258 (match-string 0))
7259 (error "*"))))
7260 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7261 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7262 pos hide-previous previous-pos)
7263 (cond
7264 ((and (org-at-heading-p) (bolp)
7265 (or (bobp)
7266 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7267 ;; insert before the current line
7268 (open-line (if blank 2 1)))
7269 ((and (bolp)
7270 (not org-insert-heading-respect-content)
7271 (or (bobp)
7272 (save-excursion
7273 (backward-char 1) (not (outline-invisible-p)))))
7274 ;; insert right here
7275 nil)
7277 ;; somewhere in the line
7278 (save-excursion
7279 (setq previous-pos (point-at-bol))
7280 (end-of-line)
7281 (setq hide-previous (outline-invisible-p)))
7282 (and org-insert-heading-respect-content (org-show-subtree))
7283 (let ((split
7284 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7285 (save-excursion
7286 (let ((p (point)))
7287 (goto-char (point-at-bol))
7288 (and (looking-at org-complex-heading-regexp)
7289 (match-beginning 4)
7290 (> p (match-beginning 4)))))))
7291 tags pos)
7292 (cond
7293 (org-insert-heading-respect-content
7294 (org-end-of-subtree nil t)
7295 (when (featurep 'org-inlinetask)
7296 (while (and (not (eobp))
7297 (looking-at "\\(\\*+\\)[ \t]+")
7298 (>= (length (match-string 1))
7299 org-inlinetask-min-level))
7300 (org-end-of-subtree nil t)))
7301 (or (bolp) (newline))
7302 (or (org-previous-line-empty-p)
7303 (and blank (newline)))
7304 (open-line 1))
7305 ((org-at-heading-p)
7306 (when hide-previous
7307 (show-children)
7308 (org-show-entry))
7309 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7310 (setq tags (and (match-end 2) (match-string 2)))
7311 (and (match-end 1)
7312 (delete-region (match-beginning 1) (match-end 1)))
7313 (setq pos (point-at-bol))
7314 (or split (end-of-line 1))
7315 (delete-horizontal-space)
7316 (if (string-match "\\`\\*+\\'"
7317 (buffer-substring (point-at-bol) (point)))
7318 (insert " "))
7319 (newline (if blank 2 1))
7320 (when tags
7321 (save-excursion
7322 (goto-char pos)
7323 (end-of-line 1)
7324 (insert " " tags)
7325 (org-set-tags nil 'align))))
7327 (or split (end-of-line 1))
7328 (newline (if blank 2 1)))))))
7329 (insert head) (just-one-space)
7330 (setq pos (point))
7331 (end-of-line 1)
7332 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7333 (when (and org-insert-heading-respect-content hide-previous)
7334 (save-excursion
7335 (goto-char previous-pos)
7336 (hide-subtree)))
7337 (run-hooks 'org-insert-heading-hook)))))
7339 (defun org-get-heading (&optional no-tags no-todo)
7340 "Return the heading of the current entry, without the stars.
7341 When NO-TAGS is non-nil, don't include tags.
7342 When NO-TODO is non-nil, don't include TODO keywords."
7343 (save-excursion
7344 (org-back-to-heading t)
7345 (cond
7346 ((and no-tags no-todo)
7347 (looking-at org-complex-heading-regexp)
7348 (match-string 4))
7349 (no-tags
7350 (looking-at (concat org-outline-regexp
7351 "\\(.*?\\)"
7352 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7353 (match-string 1))
7354 (no-todo
7355 (looking-at org-todo-line-regexp)
7356 (match-string 3))
7357 (t (looking-at org-heading-regexp)
7358 (match-string 2)))))
7360 (defun org-heading-components ()
7361 "Return the components of the current heading.
7362 This is a list with the following elements:
7363 - the level as an integer
7364 - the reduced level, different if `org-odd-levels-only' is set.
7365 - the TODO keyword, or nil
7366 - the priority character, like ?A, or nil if no priority is given
7367 - the headline text itself, or the tags string if no headline text
7368 - the tags string, or nil."
7369 (save-excursion
7370 (org-back-to-heading t)
7371 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7372 (list (length (match-string 1))
7373 (org-reduced-level (length (match-string 1)))
7374 (org-match-string-no-properties 2)
7375 (and (match-end 3) (aref (match-string 3) 2))
7376 (org-match-string-no-properties 4)
7377 (org-match-string-no-properties 5)))))
7379 (defun org-get-entry ()
7380 "Get the entry text, after heading, entire subtree."
7381 (save-excursion
7382 (org-back-to-heading t)
7383 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7385 (defun org-insert-heading-after-current ()
7386 "Insert a new heading with same level as current, after current subtree."
7387 (interactive)
7388 (org-back-to-heading)
7389 (org-insert-heading)
7390 (org-move-subtree-down)
7391 (end-of-line 1))
7393 (defun org-insert-heading-respect-content ()
7394 (interactive)
7395 (let ((org-insert-heading-respect-content t))
7396 (org-insert-heading t)))
7398 (defun org-insert-todo-heading-respect-content (&optional force-state)
7399 (interactive "P")
7400 (let ((org-insert-heading-respect-content t))
7401 (org-insert-todo-heading force-state t)))
7403 (defun org-insert-todo-heading (arg &optional force-heading)
7404 "Insert a new heading with the same level and TODO state as current heading.
7405 If the heading has no TODO state, or if the state is DONE, use the first
7406 state (TODO by default). Also with prefix arg, force first state."
7407 (interactive "P")
7408 (when (or force-heading (not (org-insert-item 'checkbox)))
7409 (org-insert-heading force-heading)
7410 (save-excursion
7411 (org-back-to-heading)
7412 (outline-previous-heading)
7413 (looking-at org-todo-line-regexp))
7414 (let*
7415 ((new-mark-x
7416 (if (or arg
7417 (not (match-beginning 2))
7418 (member (match-string 2) org-done-keywords))
7419 (car org-todo-keywords-1)
7420 (match-string 2)))
7421 (new-mark
7423 (run-hook-with-args-until-success
7424 'org-todo-get-default-hook new-mark-x nil)
7425 new-mark-x)))
7426 (beginning-of-line 1)
7427 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7428 (if org-treat-insert-todo-heading-as-state-change
7429 (org-todo new-mark)
7430 (insert new-mark " "))))
7431 (when org-provide-todo-statistics
7432 (org-update-parent-todo-statistics))))
7434 (defun org-insert-subheading (arg)
7435 "Insert a new subheading and demote it.
7436 Works for outline headings and for plain lists alike."
7437 (interactive "P")
7438 (org-insert-heading arg)
7439 (cond
7440 ((org-at-heading-p) (org-do-demote))
7441 ((org-at-item-p) (org-indent-item))))
7443 (defun org-insert-todo-subheading (arg)
7444 "Insert a new subheading with TODO keyword or checkbox and demote it.
7445 Works for outline headings and for plain lists alike."
7446 (interactive "P")
7447 (org-insert-todo-heading arg)
7448 (cond
7449 ((org-at-heading-p) (org-do-demote))
7450 ((org-at-item-p) (org-indent-item))))
7452 ;;; Promotion and Demotion
7454 (defvar org-after-demote-entry-hook nil
7455 "Hook run after an entry has been demoted.
7456 The cursor will be at the beginning of the entry.
7457 When a subtree is being demoted, the hook will be called for each node.")
7459 (defvar org-after-promote-entry-hook nil
7460 "Hook run after an entry has been promoted.
7461 The cursor will be at the beginning of the entry.
7462 When a subtree is being promoted, the hook will be called for each node.")
7464 (defun org-promote-subtree ()
7465 "Promote the entire subtree.
7466 See also `org-promote'."
7467 (interactive)
7468 (save-excursion
7469 (org-with-limited-levels (org-map-tree 'org-promote)))
7470 (org-fix-position-after-promote))
7472 (defun org-demote-subtree ()
7473 "Demote the entire subtree. See `org-demote'.
7474 See also `org-promote'."
7475 (interactive)
7476 (save-excursion
7477 (org-with-limited-levels (org-map-tree 'org-demote)))
7478 (org-fix-position-after-promote))
7481 (defun org-do-promote ()
7482 "Promote the current heading higher up the tree.
7483 If the region is active in `transient-mark-mode', promote all headings
7484 in the region."
7485 (interactive)
7486 (save-excursion
7487 (if (org-region-active-p)
7488 (org-map-region 'org-promote (region-beginning) (region-end))
7489 (org-promote)))
7490 (org-fix-position-after-promote))
7492 (defun org-do-demote ()
7493 "Demote the current heading lower down the tree.
7494 If the region is active in `transient-mark-mode', demote all headings
7495 in the region."
7496 (interactive)
7497 (save-excursion
7498 (if (org-region-active-p)
7499 (org-map-region 'org-demote (region-beginning) (region-end))
7500 (org-demote)))
7501 (org-fix-position-after-promote))
7503 (defun org-fix-position-after-promote ()
7504 "Make sure that after pro/demotion cursor position is right."
7505 (let ((pos (point)))
7506 (when (save-excursion
7507 (beginning-of-line 1)
7508 (looking-at org-todo-line-regexp)
7509 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7510 (cond ((eobp) (insert " "))
7511 ((eolp) (insert " "))
7512 ((equal (char-after) ?\ ) (forward-char 1))))))
7514 (defun org-current-level ()
7515 "Return the level of the current entry, or nil if before the first headline.
7516 The level is the number of stars at the beginning of the headline."
7517 (save-excursion
7518 (org-with-limited-levels
7519 (if (ignore-errors (org-back-to-heading t))
7520 (funcall outline-level)))))
7522 (defun org-get-previous-line-level ()
7523 "Return the outline depth of the last headline before the current line.
7524 Returns 0 for the first headline in the buffer, and nil if before the
7525 first headline."
7526 (let ((current-level (org-current-level))
7527 (prev-level (when (> (line-number-at-pos) 1)
7528 (save-excursion
7529 (beginning-of-line 0)
7530 (org-current-level)))))
7531 (cond ((null current-level) nil) ; Before first headline
7532 ((null prev-level) 0) ; At first headline
7533 (prev-level))))
7535 (defun org-reduced-level (l)
7536 "Compute the effective level of a heading.
7537 This takes into account the setting of `org-odd-levels-only'."
7538 (cond
7539 ((zerop l) 0)
7540 (org-odd-levels-only (1+ (floor (/ l 2))))
7541 (t l)))
7543 (defun org-level-increment ()
7544 "Return the number of stars that will be added or removed at a
7545 time to headlines when structure editing, based on the value of
7546 `org-odd-levels-only'."
7547 (if org-odd-levels-only 2 1))
7549 (defun org-get-valid-level (level &optional change)
7550 "Rectify a level change under the influence of `org-odd-levels-only'
7551 LEVEL is a current level, CHANGE is by how much the level should be
7552 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7553 even level numbers will become the next higher odd number."
7554 (if org-odd-levels-only
7555 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7556 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7557 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7558 (max 1 (+ level (or change 0)))))
7560 (if (boundp 'define-obsolete-function-alias)
7561 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7562 (define-obsolete-function-alias 'org-get-legal-level
7563 'org-get-valid-level)
7564 (define-obsolete-function-alias 'org-get-legal-level
7565 'org-get-valid-level "23.1")))
7567 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7568 ;; ̀org-with-limited-levels'
7569 (defun org-promote ()
7570 "Promote the current heading higher up the tree.
7571 If the region is active in `transient-mark-mode', promote all headings
7572 in the region."
7573 (org-back-to-heading t)
7574 (let* ((level (save-match-data (funcall outline-level)))
7575 (after-change-functions (remove 'flyspell-after-change-function
7576 after-change-functions))
7577 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7578 (diff (abs (- level (length up-head) -1))))
7579 (cond ((and (= level 1) org-called-with-limited-levels
7580 org-allow-promoting-top-level-subtree)
7581 (replace-match "# " nil t))
7582 ((= level 1)
7583 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7584 (t (replace-match up-head nil t)))
7585 ;; Fixup tag positioning
7586 (unless (= level 1)
7587 (and org-auto-align-tags (org-set-tags nil t))
7588 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7589 (run-hooks 'org-after-promote-entry-hook)))
7591 (defun org-demote ()
7592 "Demote the current heading lower down the tree.
7593 If the region is active in `transient-mark-mode', demote all headings
7594 in the region."
7595 (org-back-to-heading t)
7596 (let* ((level (save-match-data (funcall outline-level)))
7597 (after-change-functions (remove 'flyspell-after-change-function
7598 after-change-functions))
7599 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7600 (diff (abs (- level (length down-head) -1))))
7601 (replace-match down-head nil t)
7602 ;; Fixup tag positioning
7603 (and org-auto-align-tags (org-set-tags nil t))
7604 (if org-adapt-indentation (org-fixup-indentation diff))
7605 (run-hooks 'org-after-demote-entry-hook)))
7607 (defun org-cycle-level ()
7608 "Cycle the level of an empty headline through possible states.
7609 This goes first to child, then to parent, level, then up the hierarchy.
7610 After top level, it switches back to sibling level."
7611 (interactive)
7612 (let ((org-adapt-indentation nil))
7613 (when (org-point-at-end-of-empty-headline)
7614 (setq this-command 'org-cycle-level) ; Only needed for caching
7615 (let ((cur-level (org-current-level))
7616 (prev-level (org-get-previous-line-level)))
7617 (cond
7618 ;; If first headline in file, promote to top-level.
7619 ((= prev-level 0)
7620 (loop repeat (/ (- cur-level 1) (org-level-increment))
7621 do (org-do-promote)))
7622 ;; If same level as prev, demote one.
7623 ((= prev-level cur-level)
7624 (org-do-demote))
7625 ;; If parent is top-level, promote to top level if not already.
7626 ((= prev-level 1)
7627 (loop repeat (/ (- cur-level 1) (org-level-increment))
7628 do (org-do-promote)))
7629 ;; If top-level, return to prev-level.
7630 ((= cur-level 1)
7631 (loop repeat (/ (- prev-level 1) (org-level-increment))
7632 do (org-do-demote)))
7633 ;; If less than prev-level, promote one.
7634 ((< cur-level prev-level)
7635 (org-do-promote))
7636 ;; If deeper than prev-level, promote until higher than
7637 ;; prev-level.
7638 ((> cur-level prev-level)
7639 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7640 do (org-do-promote))))
7641 t))))
7643 (defun org-map-tree (fun)
7644 "Call FUN for every heading underneath the current one."
7645 (org-back-to-heading)
7646 (let ((level (funcall outline-level)))
7647 (save-excursion
7648 (funcall fun)
7649 (while (and (progn
7650 (outline-next-heading)
7651 (> (funcall outline-level) level))
7652 (not (eobp)))
7653 (funcall fun)))))
7655 (defun org-map-region (fun beg end)
7656 "Call FUN for every heading between BEG and END."
7657 (let ((org-ignore-region t))
7658 (save-excursion
7659 (setq end (copy-marker end))
7660 (goto-char beg)
7661 (if (and (re-search-forward org-outline-regexp-bol nil t)
7662 (< (point) end))
7663 (funcall fun))
7664 (while (and (progn
7665 (outline-next-heading)
7666 (< (point) end))
7667 (not (eobp)))
7668 (funcall fun)))))
7670 (defvar org-property-end-re) ; silence byte-compiler
7671 (defun org-fixup-indentation (diff)
7672 "Change the indentation in the current entry by DIFF.
7673 However, if any line in the current entry has no indentation, or if it
7674 would end up with no indentation after the change, nothing at all is done."
7675 (save-excursion
7676 (let ((end (save-excursion (outline-next-heading)
7677 (point-marker)))
7678 (prohibit (if (> diff 0)
7679 "^\\S-"
7680 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7681 col)
7682 (unless (save-excursion (end-of-line 1)
7683 (re-search-forward prohibit end t))
7684 (while (and (< (point) end)
7685 (re-search-forward "^[ \t]+" end t))
7686 (goto-char (match-end 0))
7687 (setq col (current-column))
7688 (if (< diff 0) (replace-match ""))
7689 (org-indent-to-column (+ diff col))))
7690 (move-marker end nil))))
7692 (defun org-convert-to-odd-levels ()
7693 "Convert an org-mode file with all levels allowed to one with odd levels.
7694 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7695 level 5 etc."
7696 (interactive)
7697 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7698 (let ((outline-level 'org-outline-level)
7699 (org-odd-levels-only nil) n)
7700 (save-excursion
7701 (goto-char (point-min))
7702 (while (re-search-forward "^\\*\\*+ " nil t)
7703 (setq n (- (length (match-string 0)) 2))
7704 (while (>= (setq n (1- n)) 0)
7705 (org-demote))
7706 (end-of-line 1))))))
7708 (defun org-convert-to-oddeven-levels ()
7709 "Convert an org-mode file with only odd levels to one with odd/even levels.
7710 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7711 file contains a section with an even level, conversion would
7712 destroy the structure of the file. An error is signaled in this
7713 case."
7714 (interactive)
7715 (goto-char (point-min))
7716 ;; First check if there are no even levels
7717 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7718 (org-show-context t)
7719 (error "Not all levels are odd in this file. Conversion not possible"))
7720 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7721 (let ((outline-regexp org-outline-regexp)
7722 (outline-level 'org-outline-level)
7723 (org-odd-levels-only nil) n)
7724 (save-excursion
7725 (goto-char (point-min))
7726 (while (re-search-forward "^\\*\\*+ " nil t)
7727 (setq n (/ (1- (length (match-string 0))) 2))
7728 (while (>= (setq n (1- n)) 0)
7729 (org-promote))
7730 (end-of-line 1))))))
7732 (defun org-tr-level (n)
7733 "Make N odd if required."
7734 (if org-odd-levels-only (1+ (/ n 2)) n))
7736 ;;; Vertical tree motion, cutting and pasting of subtrees
7738 (defun org-move-subtree-up (&optional arg)
7739 "Move the current subtree up past ARG headlines of the same level."
7740 (interactive "p")
7741 (org-move-subtree-down (- (prefix-numeric-value arg))))
7743 (defun org-move-subtree-down (&optional arg)
7744 "Move the current subtree down past ARG headlines of the same level."
7745 (interactive "p")
7746 (setq arg (prefix-numeric-value arg))
7747 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7748 'org-get-last-sibling))
7749 (ins-point (make-marker))
7750 (cnt (abs arg))
7751 (col (current-column))
7752 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7753 ;; Select the tree
7754 (org-back-to-heading)
7755 (setq beg0 (point))
7756 (save-excursion
7757 (setq ne-beg (org-back-over-empty-lines))
7758 (setq beg (point)))
7759 (save-match-data
7760 (save-excursion (outline-end-of-heading)
7761 (setq folded (outline-invisible-p)))
7762 (outline-end-of-subtree))
7763 (outline-next-heading)
7764 (setq ne-end (org-back-over-empty-lines))
7765 (setq end (point))
7766 (goto-char beg0)
7767 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7768 ;; include less whitespace
7769 (save-excursion
7770 (goto-char beg)
7771 (forward-line (- ne-beg ne-end))
7772 (setq beg (point))))
7773 ;; Find insertion point, with error handling
7774 (while (> cnt 0)
7775 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7776 (progn (goto-char beg0)
7777 (error "Cannot move past superior level or buffer limit")))
7778 (setq cnt (1- cnt)))
7779 (if (> arg 0)
7780 ;; Moving forward - still need to move over subtree
7781 (progn (org-end-of-subtree t t)
7782 (save-excursion
7783 (org-back-over-empty-lines)
7784 (or (bolp) (newline)))))
7785 (setq ne-ins (org-back-over-empty-lines))
7786 (move-marker ins-point (point))
7787 (setq txt (buffer-substring beg end))
7788 (org-save-markers-in-region beg end)
7789 (delete-region beg end)
7790 (org-remove-empty-overlays-at beg)
7791 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7792 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7793 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7794 (let ((bbb (point)))
7795 (insert-before-markers txt)
7796 (org-reinstall-markers-in-region bbb)
7797 (move-marker ins-point bbb))
7798 (or (bolp) (insert "\n"))
7799 (setq ins-end (point))
7800 (goto-char ins-point)
7801 (org-skip-whitespace)
7802 (when (and (< arg 0)
7803 (org-first-sibling-p)
7804 (> ne-ins ne-beg))
7805 ;; Move whitespace back to beginning
7806 (save-excursion
7807 (goto-char ins-end)
7808 (let ((kill-whole-line t))
7809 (kill-line (- ne-ins ne-beg)) (point)))
7810 (insert (make-string (- ne-ins ne-beg) ?\n)))
7811 (move-marker ins-point nil)
7812 (if folded
7813 (hide-subtree)
7814 (org-show-entry)
7815 (show-children)
7816 (org-cycle-hide-drawers 'children))
7817 (org-clean-visibility-after-subtree-move)
7818 ;; move back to the initial column we were at
7819 (move-to-column col)))
7821 (defvar org-subtree-clip ""
7822 "Clipboard for cut and paste of subtrees.
7823 This is actually only a copy of the kill, because we use the normal kill
7824 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7826 (defvar org-subtree-clip-folded nil
7827 "Was the last copied subtree folded?
7828 This is used to fold the tree back after pasting.")
7830 (defun org-cut-subtree (&optional n)
7831 "Cut the current subtree into the clipboard.
7832 With prefix arg N, cut this many sequential subtrees.
7833 This is a short-hand for marking the subtree and then cutting it."
7834 (interactive "p")
7835 (org-copy-subtree n 'cut))
7837 (defun org-copy-subtree (&optional n cut force-store-markers)
7838 "Cut the current subtree into the clipboard.
7839 With prefix arg N, cut this many sequential subtrees.
7840 This is a short-hand for marking the subtree and then copying it.
7841 If CUT is non-nil, actually cut the subtree.
7842 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7843 of some markers in the region, even if CUT is non-nil. This is
7844 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7845 (interactive "p")
7846 (let (beg end folded (beg0 (point)))
7847 (if (org-called-interactively-p 'any)
7848 (org-back-to-heading nil) ; take what looks like a subtree
7849 (org-back-to-heading t)) ; take what is really there
7850 (org-back-over-empty-lines)
7851 (setq beg (point))
7852 (skip-chars-forward " \t\r\n")
7853 (save-match-data
7854 (save-excursion (outline-end-of-heading)
7855 (setq folded (outline-invisible-p)))
7856 (condition-case nil
7857 (org-forward-heading-same-level (1- n) t)
7858 (error nil))
7859 (org-end-of-subtree t t))
7860 (org-back-over-empty-lines)
7861 (setq end (point))
7862 (goto-char beg0)
7863 (when (> end beg)
7864 (setq org-subtree-clip-folded folded)
7865 (when (or cut force-store-markers)
7866 (org-save-markers-in-region beg end))
7867 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7868 (setq org-subtree-clip (current-kill 0))
7869 (message "%s: Subtree(s) with %d characters"
7870 (if cut "Cut" "Copied")
7871 (length org-subtree-clip)))))
7873 (defun org-paste-subtree (&optional level tree for-yank)
7874 "Paste the clipboard as a subtree, with modification of headline level.
7875 The entire subtree is promoted or demoted in order to match a new headline
7876 level.
7878 If the cursor is at the beginning of a headline, the same level as
7879 that headline is used to paste the tree
7881 If not, the new level is derived from the *visible* headings
7882 before and after the insertion point, and taken to be the inferior headline
7883 level of the two. So if the previous visible heading is level 3 and the
7884 next is level 4 (or vice versa), level 4 will be used for insertion.
7885 This makes sure that the subtree remains an independent subtree and does
7886 not swallow low level entries.
7888 You can also force a different level, either by using a numeric prefix
7889 argument, or by inserting the heading marker by hand. For example, if the
7890 cursor is after \"*****\", then the tree will be shifted to level 5.
7892 If optional TREE is given, use this text instead of the kill ring.
7894 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7895 move back over whitespace before inserting, and move point to the end of
7896 the inserted text when done."
7897 (interactive "P")
7898 (setq tree (or tree (and kill-ring (current-kill 0))))
7899 (unless (org-kill-is-subtree-p tree)
7900 (error "%s"
7901 (substitute-command-keys
7902 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7903 (org-with-limited-levels
7904 (let* ((visp (not (outline-invisible-p)))
7905 (txt tree)
7906 (^re_ "\\(\\*+\\)[ \t]*")
7907 (old-level (if (string-match org-outline-regexp-bol txt)
7908 (- (match-end 0) (match-beginning 0) 1)
7909 -1))
7910 (force-level (cond (level (prefix-numeric-value level))
7911 ((and (looking-at "[ \t]*$")
7912 (string-match
7913 "^\\*+$" (buffer-substring
7914 (point-at-bol) (point))))
7915 (- (match-end 1) (match-beginning 1)))
7916 ((and (bolp)
7917 (looking-at org-outline-regexp))
7918 (- (match-end 0) (point) 1))))
7919 (previous-level (save-excursion
7920 (condition-case nil
7921 (progn
7922 (outline-previous-visible-heading 1)
7923 (if (looking-at ^re_)
7924 (- (match-end 0) (match-beginning 0) 1)
7926 (error 1))))
7927 (next-level (save-excursion
7928 (condition-case nil
7929 (progn
7930 (or (looking-at org-outline-regexp)
7931 (outline-next-visible-heading 1))
7932 (if (looking-at ^re_)
7933 (- (match-end 0) (match-beginning 0) 1)
7935 (error 1))))
7936 (new-level (or force-level (max previous-level next-level)))
7937 (shift (if (or (= old-level -1)
7938 (= new-level -1)
7939 (= old-level new-level))
7941 (- new-level old-level)))
7942 (delta (if (> shift 0) -1 1))
7943 (func (if (> shift 0) 'org-demote 'org-promote))
7944 (org-odd-levels-only nil)
7945 beg end newend)
7946 ;; Remove the forced level indicator
7947 (if force-level
7948 (delete-region (point-at-bol) (point)))
7949 ;; Paste
7950 (beginning-of-line (if (bolp) 1 2))
7951 (unless for-yank (org-back-over-empty-lines))
7952 (setq beg (point))
7953 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7954 (insert-before-markers txt)
7955 (unless (string-match "\n\\'" txt) (insert "\n"))
7956 (setq newend (point))
7957 (org-reinstall-markers-in-region beg)
7958 (setq end (point))
7959 (goto-char beg)
7960 (skip-chars-forward " \t\n\r")
7961 (setq beg (point))
7962 (if (and (outline-invisible-p) visp)
7963 (save-excursion (outline-show-heading)))
7964 ;; Shift if necessary
7965 (unless (= shift 0)
7966 (save-restriction
7967 (narrow-to-region beg end)
7968 (while (not (= shift 0))
7969 (org-map-region func (point-min) (point-max))
7970 (setq shift (+ delta shift)))
7971 (goto-char (point-min))
7972 (setq newend (point-max))))
7973 (when (or (org-called-interactively-p 'interactive) for-yank)
7974 (message "Clipboard pasted as level %d subtree" new-level))
7975 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7976 kill-ring
7977 (eq org-subtree-clip (current-kill 0))
7978 org-subtree-clip-folded)
7979 ;; The tree was folded before it was killed/copied
7980 (hide-subtree))
7981 (and for-yank (goto-char newend)))))
7983 (defun org-kill-is-subtree-p (&optional txt)
7984 "Check if the current kill is an outline subtree, or a set of trees.
7985 Returns nil if kill does not start with a headline, or if the first
7986 headline level is not the largest headline level in the tree.
7987 So this will actually accept several entries of equal levels as well,
7988 which is OK for `org-paste-subtree'.
7989 If optional TXT is given, check this string instead of the current kill."
7990 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7991 (re (org-get-limited-outline-regexp))
7992 (^re (concat "^" re))
7993 (start-level (and kill
7994 (string-match
7995 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7996 kill)
7997 (- (match-end 2) (match-beginning 2) 1)))
7998 (start (1+ (or (match-beginning 2) -1))))
7999 (if (not start-level)
8000 (progn
8001 nil) ;; does not even start with a heading
8002 (catch 'exit
8003 (while (setq start (string-match ^re kill (1+ start)))
8004 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8005 (throw 'exit nil)))
8006 t))))
8008 (defvar org-markers-to-move nil
8009 "Markers that should be moved with a cut-and-paste operation.
8010 Those markers are stored together with their positions relative to
8011 the start of the region.")
8013 (defun org-save-markers-in-region (beg end)
8014 "Check markers in region.
8015 If these markers are between BEG and END, record their position relative
8016 to BEG, so that after moving the block of text, we can put the markers back
8017 into place.
8018 This function gets called just before an entry or tree gets cut from the
8019 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8020 called immediately, to move the markers with the entries."
8021 (setq org-markers-to-move nil)
8022 (when (featurep 'org-clock)
8023 (org-clock-save-markers-for-cut-and-paste beg end))
8024 (when (featurep 'org-agenda)
8025 (org-agenda-save-markers-for-cut-and-paste beg end)))
8027 (defun org-check-and-save-marker (marker beg end)
8028 "Check if MARKER is between BEG and END.
8029 If yes, remember the marker and the distance to BEG."
8030 (when (and (marker-buffer marker)
8031 (equal (marker-buffer marker) (current-buffer)))
8032 (if (and (>= marker beg) (< marker end))
8033 (push (cons marker (- marker beg)) org-markers-to-move))))
8035 (defun org-reinstall-markers-in-region (beg)
8036 "Move all remembered markers to their position relative to BEG."
8037 (mapc (lambda (x)
8038 (move-marker (car x) (+ beg (cdr x))))
8039 org-markers-to-move)
8040 (setq org-markers-to-move nil))
8042 (defun org-narrow-to-subtree ()
8043 "Narrow buffer to the current subtree."
8044 (interactive)
8045 (save-excursion
8046 (save-match-data
8047 (org-with-limited-levels
8048 (narrow-to-region
8049 (progn (org-back-to-heading t) (point))
8050 (progn (org-end-of-subtree t t)
8051 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8052 (point)))))))
8054 (defun org-narrow-to-block ()
8055 "Narrow buffer to the current block."
8056 (interactive)
8057 (let* ((case-fold-search t)
8058 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8059 "^[ \t]*#\\+end_.*")))
8060 (if blockp
8061 (narrow-to-region (car blockp) (cdr blockp))
8062 (error "Not in a block"))))
8064 (eval-when-compile
8065 (defvar org-property-drawer-re))
8067 (defvar org-property-start-re) ;; defined below
8068 (defun org-clone-subtree-with-time-shift (n &optional shift)
8069 "Clone the task (subtree) at point N times.
8070 The clones will be inserted as siblings.
8072 In interactive use, the user will be prompted for the number of
8073 clones to be produced, and for a time SHIFT, which may be a
8074 repeater as used in time stamps, for example `+3d'.
8076 When a valid repeater is given and the entry contains any time
8077 stamps, the clones will become a sequence in time, with time
8078 stamps in the subtree shifted for each clone produced. If SHIFT
8079 is nil or the empty string, time stamps will be left alone. The
8080 ID property of the original subtree is removed.
8082 If the original subtree did contain time stamps with a repeater,
8083 the following will happen:
8084 - the repeater will be removed in each clone
8085 - an additional clone will be produced, with the current, unshifted
8086 date(s) in the entry.
8087 - the original entry will be placed *after* all the clones, with
8088 repeater intact.
8089 - the start days in the repeater in the original entry will be shifted
8090 to past the last clone.
8091 In this way you can spell out a number of instances of a repeating task,
8092 and still retain the repeater to cover future instances of the task."
8093 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8094 (let (beg end template task idprop
8095 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8096 (drawer-re org-drawer-regexp))
8097 (if (not (and (integerp n) (> n 0)))
8098 (error "Invalid number of replications %s" n))
8099 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8100 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8101 shift)))
8102 (error "Invalid shift specification %s" shift))
8103 (when doshift
8104 (setq shift-n (string-to-number (match-string 1 shift))
8105 shift-what (cdr (assoc (match-string 2 shift)
8106 '(("d" . day) ("w" . week)
8107 ("m" . month) ("y" . year))))))
8108 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8109 (setq nmin 1 nmax n)
8110 (org-back-to-heading t)
8111 (setq beg (point))
8112 (setq idprop (org-entry-get nil "ID"))
8113 (org-end-of-subtree t t)
8114 (or (bolp) (insert "\n"))
8115 (setq end (point))
8116 (setq template (buffer-substring beg end))
8117 (when (and doshift
8118 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8119 (delete-region beg end)
8120 (setq end beg)
8121 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8122 (goto-char end)
8123 (loop for n from nmin to nmax do
8124 ;; prepare clone
8125 (with-temp-buffer
8126 (insert template)
8127 (org-mode)
8128 (goto-char (point-min))
8129 (org-show-subtree)
8130 (and idprop (if org-clone-delete-id
8131 (org-entry-delete nil "ID")
8132 (org-id-get-create t)))
8133 (unless (= n 0)
8134 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8135 (kill-whole-line))
8136 (goto-char (point-min))
8137 (while (re-search-forward drawer-re nil t)
8138 (mapc (lambda (d)
8139 (org-remove-empty-drawer-at d (point))) org-drawers)))
8140 (goto-char (point-min))
8141 (when doshift
8142 (while (re-search-forward org-ts-regexp-both nil t)
8143 (org-timestamp-change (* n shift-n) shift-what))
8144 (unless (= n n-no-remove)
8145 (goto-char (point-min))
8146 (while (re-search-forward org-ts-regexp nil t)
8147 (save-excursion
8148 (goto-char (match-beginning 0))
8149 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8150 (delete-region (match-beginning 1) (match-end 1)))))))
8151 (setq task (buffer-string)))
8152 (insert task))
8153 (goto-char beg)))
8155 ;;; Outline Sorting
8157 (defun org-sort (with-case)
8158 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8159 Optional argument WITH-CASE means sort case-sensitively."
8160 (interactive "P")
8161 (cond
8162 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8163 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8165 (org-call-with-arg 'org-sort-entries with-case))))
8167 (defun org-sort-remove-invisible (s)
8168 (remove-text-properties 0 (length s) org-rm-props s)
8169 (while (string-match org-bracket-link-regexp s)
8170 (setq s (replace-match (if (match-end 2)
8171 (match-string 3 s)
8172 (match-string 1 s)) t t s)))
8175 (defvar org-priority-regexp) ; defined later in the file
8177 (defvar org-after-sorting-entries-or-items-hook nil
8178 "Hook that is run after a bunch of entries or items have been sorted.
8179 When children are sorted, the cursor is in the parent line when this
8180 hook gets called. When a region or a plain list is sorted, the cursor
8181 will be in the first entry of the sorted region/list.")
8183 (defun org-sort-entries
8184 (&optional with-case sorting-type getkey-func compare-func property)
8185 "Sort entries on a certain level of an outline tree.
8186 If there is an active region, the entries in the region are sorted.
8187 Else, if the cursor is before the first entry, sort the top-level items.
8188 Else, the children of the entry at point are sorted.
8190 Sorting can be alphabetically, numerically, by date/time as given by
8191 a time stamp, by a property or by priority.
8193 The command prompts for the sorting type unless it has been given to the
8194 function through the SORTING-TYPE argument, which needs to be a character,
8195 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8196 precise meaning of each character:
8198 n Numerically, by converting the beginning of the entry/item to a number.
8199 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8200 t By date/time, either the first active time stamp in the entry, or, if
8201 none exist, by the first inactive one.
8202 s By the scheduled date/time.
8203 d By deadline date/time.
8204 c By creation time, which is assumed to be the first inactive time stamp
8205 at the beginning of a line.
8206 p By priority according to the cookie.
8207 r By the value of a property.
8209 Capital letters will reverse the sort order.
8211 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8212 called with point at the beginning of the record. It must return either
8213 a string or a number that should serve as the sorting key for that record.
8215 Comparing entries ignores case by default. However, with an optional argument
8216 WITH-CASE, the sorting considers case as well."
8217 (interactive "P")
8218 (let ((case-func (if with-case 'identity 'downcase))
8219 start beg end stars re re2
8220 txt what tmp)
8221 ;; Find beginning and end of region to sort
8222 (cond
8223 ((org-region-active-p)
8224 ;; we will sort the region
8225 (setq end (region-end)
8226 what "region")
8227 (goto-char (region-beginning))
8228 (if (not (org-at-heading-p)) (outline-next-heading))
8229 (setq start (point)))
8230 ((or (org-at-heading-p)
8231 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8232 ;; we will sort the children of the current headline
8233 (org-back-to-heading)
8234 (setq start (point)
8235 end (progn (org-end-of-subtree t t)
8236 (or (bolp) (insert "\n"))
8237 (org-back-over-empty-lines)
8238 (point))
8239 what "children")
8240 (goto-char start)
8241 (show-subtree)
8242 (outline-next-heading))
8244 ;; we will sort the top-level entries in this file
8245 (goto-char (point-min))
8246 (or (org-at-heading-p) (outline-next-heading))
8247 (setq start (point))
8248 (goto-char (point-max))
8249 (beginning-of-line 1)
8250 (when (looking-at ".*?\\S-")
8251 ;; File ends in a non-white line
8252 (end-of-line 1)
8253 (insert "\n"))
8254 (setq end (point-max))
8255 (setq what "top-level")
8256 (goto-char start)
8257 (show-all)))
8259 (setq beg (point))
8260 (if (>= beg end) (error "Nothing to sort"))
8262 (looking-at "\\(\\*+\\)")
8263 (setq stars (match-string 1)
8264 re (concat "^" (regexp-quote stars) " +")
8265 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8266 txt (buffer-substring beg end))
8267 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8268 (if (and (not (equal stars "*")) (string-match re2 txt))
8269 (error "Region to sort contains a level above the first entry"))
8271 (unless sorting-type
8272 (message
8273 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8274 [t]ime [s]cheduled [d]eadline [c]reated
8275 A/N/T/S/D/C/P/O/F means reversed:"
8276 what)
8277 (setq sorting-type (read-char-exclusive))
8279 (and (= (downcase sorting-type) ?f)
8280 (setq getkey-func
8281 (org-icompleting-read "Sort using function: "
8282 obarray 'fboundp t nil nil))
8283 (setq getkey-func (intern getkey-func)))
8285 (and (= (downcase sorting-type) ?r)
8286 (setq property
8287 (org-icompleting-read "Property: "
8288 (mapcar 'list (org-buffer-property-keys t))
8289 nil t))))
8291 (message "Sorting entries...")
8293 (save-restriction
8294 (narrow-to-region start end)
8295 (let ((dcst (downcase sorting-type))
8296 (case-fold-search nil)
8297 (now (current-time)))
8298 (sort-subr
8299 (/= dcst sorting-type)
8300 ;; This function moves to the beginning character of the "record" to
8301 ;; be sorted.
8302 (lambda nil
8303 (if (re-search-forward re nil t)
8304 (goto-char (match-beginning 0))
8305 (goto-char (point-max))))
8306 ;; This function moves to the last character of the "record" being
8307 ;; sorted.
8308 (lambda nil
8309 (save-match-data
8310 (condition-case nil
8311 (outline-forward-same-level 1)
8312 (error
8313 (goto-char (point-max))))))
8314 ;; This function returns the value that gets sorted against.
8315 (lambda nil
8316 (cond
8317 ((= dcst ?n)
8318 (if (looking-at org-complex-heading-regexp)
8319 (string-to-number (match-string 4))
8320 nil))
8321 ((= dcst ?a)
8322 (if (looking-at org-complex-heading-regexp)
8323 (funcall case-func (match-string 4))
8324 nil))
8325 ((= dcst ?t)
8326 (let ((end (save-excursion (outline-next-heading) (point))))
8327 (if (or (re-search-forward org-ts-regexp end t)
8328 (re-search-forward org-ts-regexp-both end t))
8329 (org-time-string-to-seconds (match-string 0))
8330 (org-float-time now))))
8331 ((= dcst ?c)
8332 (let ((end (save-excursion (outline-next-heading) (point))))
8333 (if (re-search-forward
8334 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8335 end t)
8336 (org-time-string-to-seconds (match-string 0))
8337 (org-float-time now))))
8338 ((= dcst ?s)
8339 (let ((end (save-excursion (outline-next-heading) (point))))
8340 (if (re-search-forward org-scheduled-time-regexp end t)
8341 (org-time-string-to-seconds (match-string 1))
8342 (org-float-time now))))
8343 ((= dcst ?d)
8344 (let ((end (save-excursion (outline-next-heading) (point))))
8345 (if (re-search-forward org-deadline-time-regexp end t)
8346 (org-time-string-to-seconds (match-string 1))
8347 (org-float-time now))))
8348 ((= dcst ?p)
8349 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8350 (string-to-char (match-string 2))
8351 org-default-priority))
8352 ((= dcst ?r)
8353 (or (org-entry-get nil property) ""))
8354 ((= dcst ?o)
8355 (if (looking-at org-complex-heading-regexp)
8356 (- 9999 (length (member (match-string 2)
8357 org-todo-keywords-1)))))
8358 ((= dcst ?f)
8359 (if getkey-func
8360 (progn
8361 (setq tmp (funcall getkey-func))
8362 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8363 tmp)
8364 (error "Invalid key function `%s'" getkey-func)))
8365 (t (error "Invalid sorting type `%c'" sorting-type))))
8367 (cond
8368 ((= dcst ?a) 'string<)
8369 ((= dcst ?f) compare-func)
8370 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8371 (run-hooks 'org-after-sorting-entries-or-items-hook)
8372 (message "Sorting entries...done")))
8374 (defun org-do-sort (table what &optional with-case sorting-type)
8375 "Sort TABLE of WHAT according to SORTING-TYPE.
8376 The user will be prompted for the SORTING-TYPE if the call to this
8377 function does not specify it. WHAT is only for the prompt, to indicate
8378 what is being sorted. The sorting key will be extracted from
8379 the car of the elements of the table.
8380 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8381 (unless sorting-type
8382 (message
8383 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8384 what)
8385 (setq sorting-type (read-char-exclusive)))
8386 (let ((dcst (downcase sorting-type))
8387 extractfun comparefun)
8388 ;; Define the appropriate functions
8389 (cond
8390 ((= dcst ?n)
8391 (setq extractfun 'string-to-number
8392 comparefun (if (= dcst sorting-type) '< '>)))
8393 ((= dcst ?a)
8394 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8395 (lambda(x) (downcase (org-sort-remove-invisible x))))
8396 comparefun (if (= dcst sorting-type)
8397 'string<
8398 (lambda (a b) (and (not (string< a b))
8399 (not (string= a b)))))))
8400 ((= dcst ?t)
8401 (setq extractfun
8402 (lambda (x)
8403 (if (or (string-match org-ts-regexp x)
8404 (string-match org-ts-regexp-both x))
8405 (org-float-time
8406 (org-time-string-to-time (match-string 0 x)))
8408 comparefun (if (= dcst sorting-type) '< '>)))
8409 (t (error "Invalid sorting type `%c'" sorting-type)))
8411 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8412 table)
8413 (lambda (a b) (funcall comparefun (car a) (car b))))))
8416 ;;; The orgstruct minor mode
8418 ;; Define a minor mode which can be used in other modes in order to
8419 ;; integrate the org-mode structure editing commands.
8421 ;; This is really a hack, because the org-mode structure commands use
8422 ;; keys which normally belong to the major mode. Here is how it
8423 ;; works: The minor mode defines all the keys necessary to operate the
8424 ;; structure commands, but wraps the commands into a function which
8425 ;; tests if the cursor is currently at a headline or a plain list
8426 ;; item. If that is the case, the structure command is used,
8427 ;; temporarily setting many Org-mode variables like regular
8428 ;; expressions for filling etc. However, when any of those keys is
8429 ;; used at a different location, function uses `key-binding' to look
8430 ;; up if the key has an associated command in another currently active
8431 ;; keymap (minor modes, major mode, global), and executes that
8432 ;; command. There might be problems if any of the keys is otherwise
8433 ;; used as a prefix key.
8435 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8436 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8437 ;; addresses this by checking explicitly for both bindings.
8439 (defvar orgstruct-mode-map (make-sparse-keymap)
8440 "Keymap for the minor `orgstruct-mode'.")
8442 (defvar org-local-vars nil
8443 "List of local variables, for use by `orgstruct-mode'.")
8445 ;;;###autoload
8446 (define-minor-mode orgstruct-mode
8447 "Toggle the minor mode `orgstruct-mode'.
8448 This mode is for using Org-mode structure commands in other
8449 modes. The following keys behave as if Org-mode were active, if
8450 the cursor is on a headline, or on a plain list item (both as
8451 defined by Org-mode).
8453 M-up Move entry/item up
8454 M-down Move entry/item down
8455 M-left Promote
8456 M-right Demote
8457 M-S-up Move entry/item up
8458 M-S-down Move entry/item down
8459 M-S-left Promote subtree
8460 M-S-right Demote subtree
8461 M-q Fill paragraph and items like in Org-mode
8462 C-c ^ Sort entries
8463 C-c - Cycle list bullet
8464 TAB Cycle item visibility
8465 M-RET Insert new heading/item
8466 S-M-RET Insert new TODO heading / Checkbox item
8467 C-c C-c Set tags / toggle checkbox"
8468 nil " OrgStruct" nil
8469 (org-load-modules-maybe)
8470 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8472 ;;;###autoload
8473 (defun turn-on-orgstruct ()
8474 "Unconditionally turn on `orgstruct-mode'."
8475 (orgstruct-mode 1))
8477 (defvar org-fb-vars nil)
8478 (make-variable-buffer-local 'org-fb-vars)
8479 (defun orgstruct++-mode (&optional arg)
8480 "Toggle `orgstruct-mode', the enhanced version of it.
8481 In addition to setting orgstruct-mode, this also exports all
8482 indentation and autofilling variables from org-mode into the
8483 buffer. It will also recognize item context in multiline items."
8484 (interactive "P")
8485 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8486 (if (< arg 1)
8487 (progn (orgstruct-mode -1)
8488 (mapc (lambda(v)
8489 (org-set-local (car v)
8490 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8491 org-fb-vars))
8492 (orgstruct-mode 1)
8493 (setq org-fb-vars nil)
8494 (let (var val)
8495 (mapc
8496 (lambda (x)
8497 (when (string-match
8498 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8499 (symbol-name (car x)))
8500 (setq var (car x) val (nth 1 x))
8501 (push (list var `(quote ,(eval var))) org-fb-vars)
8502 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8503 org-local-vars)
8504 (org-set-local 'orgstruct-is-++ t))))
8506 (defvar orgstruct-is-++ nil
8507 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8508 (make-variable-buffer-local 'orgstruct-is-++)
8510 ;;;###autoload
8511 (defun turn-on-orgstruct++ ()
8512 "Unconditionally turn on `orgstruct++-mode'."
8513 (orgstruct++-mode 1))
8515 (defun orgstruct-error ()
8516 "Error when there is no default binding for a structure key."
8517 (interactive)
8518 (error "This key has no function outside structure elements"))
8520 (defun orgstruct-setup ()
8521 "Setup orgstruct keymaps."
8522 (let ((nfunc 0)
8523 (bindings
8524 (list
8525 '([(meta up)] org-metaup)
8526 '([(meta down)] org-metadown)
8527 '([(meta left)] org-metaleft)
8528 '([(meta right)] org-metaright)
8529 '([(meta shift up)] org-shiftmetaup)
8530 '([(meta shift down)] org-shiftmetadown)
8531 '([(meta shift left)] org-shiftmetaleft)
8532 '([(meta shift right)] org-shiftmetaright)
8533 '([?\e (up)] org-metaup)
8534 '([?\e (down)] org-metadown)
8535 '([?\e (left)] org-metaleft)
8536 '([?\e (right)] org-metaright)
8537 '([?\e (shift up)] org-shiftmetaup)
8538 '([?\e (shift down)] org-shiftmetadown)
8539 '([?\e (shift left)] org-shiftmetaleft)
8540 '([?\e (shift right)] org-shiftmetaright)
8541 '([(shift up)] org-shiftup)
8542 '([(shift down)] org-shiftdown)
8543 '([(shift left)] org-shiftleft)
8544 '([(shift right)] org-shiftright)
8545 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8546 '("\M-q" fill-paragraph)
8547 '("\C-c^" org-sort)
8548 '("\C-c-" org-cycle-list-bullet)))
8549 elt key fun cmd)
8550 (while (setq elt (pop bindings))
8551 (setq nfunc (1+ nfunc))
8552 (setq key (org-key (car elt))
8553 fun (nth 1 elt)
8554 cmd (orgstruct-make-binding fun nfunc key))
8555 (org-defkey orgstruct-mode-map key cmd))
8557 ;; Prevent an error for users who forgot to make autoloads
8558 (require 'org-element)
8560 ;; Special treatment needed for TAB and RET
8561 (org-defkey orgstruct-mode-map [(tab)]
8562 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8563 (org-defkey orgstruct-mode-map "\C-i"
8564 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8566 (org-defkey orgstruct-mode-map "\M-\C-m"
8567 (orgstruct-make-binding 'org-insert-heading 105
8568 "\M-\C-m" [(meta return)]))
8569 (org-defkey orgstruct-mode-map [(meta return)]
8570 (orgstruct-make-binding 'org-insert-heading 106
8571 [(meta return)] "\M-\C-m"))
8573 (org-defkey orgstruct-mode-map [(shift meta return)]
8574 (orgstruct-make-binding 'org-insert-todo-heading 107
8575 [(meta return)] "\M-\C-m"))
8577 (org-defkey orgstruct-mode-map "\e\C-m"
8578 (orgstruct-make-binding 'org-insert-heading 108
8579 "\e\C-m" [?\e (return)]))
8580 (org-defkey orgstruct-mode-map [?\e (return)]
8581 (orgstruct-make-binding 'org-insert-heading 109
8582 [?\e (return)] "\e\C-m"))
8583 (org-defkey orgstruct-mode-map [?\e (shift return)]
8584 (orgstruct-make-binding 'org-insert-todo-heading 110
8585 [?\e (return)] "\e\C-m"))
8587 (unless org-local-vars
8588 (setq org-local-vars (org-get-local-variables)))
8592 (defun orgstruct-make-binding (fun n &rest keys)
8593 "Create a function for binding in the structure minor mode.
8594 FUN is the command to call inside a table. N is used to create a unique
8595 command name. KEYS are keys that should be checked in for a command
8596 to execute outside of tables."
8597 (eval
8598 (list 'defun
8599 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8600 '(arg)
8601 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8602 "Outside of structure, run the binding of `"
8603 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8604 "'.")
8605 '(interactive "p")
8606 (list 'if
8607 `(org-context-p 'headline 'item
8608 (and orgstruct-is-++
8609 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8610 'item-body))
8611 (list 'org-run-like-in-org-mode (list 'quote fun))
8612 (list 'let '(orgstruct-mode)
8613 (list 'call-interactively
8614 (append '(or)
8615 (mapcar (lambda (k)
8616 (list 'key-binding k))
8617 keys)
8618 '('orgstruct-error))))))))
8620 (defun org-contextualize-keys (alist contexts)
8621 "Return valid elements in ALIST depending on CONTEXTS.
8623 `org-agenda-custom-commands' or `org-capture-templates' are the
8624 values used for ALIST, and `org-agenda-custom-commands-contexts'
8625 or `org-capture-templates-contexts' are the associated contexts
8626 definitions."
8627 (let ((contexts
8628 ;; normalize contexts
8629 (mapcar
8630 (lambda(c) (cond ((listp (cadr c))
8631 (list (car c) (car c) (cadr c)))
8632 ((string= "" (cadr c))
8633 (list (car c) (car c) (caddr c)))
8634 (t c))) contexts))
8635 (a alist) c r s)
8636 ;; loop over all commands or templates
8637 (while (setq c (pop a))
8638 (let (vrules repl)
8639 (cond
8640 ((not (assoc (car c) contexts))
8641 (push c r))
8642 ((and (assoc (car c) contexts)
8643 (setq vrules (org-contextualize-validate-key
8644 (car c) contexts)))
8645 (mapc (lambda (vr)
8646 (when (not (equal (car vr) (cadr vr)))
8647 (setq repl vr))) vrules)
8648 (if (not repl) (push c r)
8649 (push (cadr repl) s)
8650 (push
8651 (cons (car c)
8652 (cdr (or (assoc (cadr repl) alist)
8653 (error "Undefined key `%s' as contextual replacement for `%s'"
8654 (cadr repl) (car c)))))
8655 r))))))
8656 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8657 (delq
8659 (delete-dups
8660 (mapcar (lambda (x)
8661 (let ((tpl (car x)))
8662 (when (not (delq
8664 (mapcar (lambda(y)
8665 (equal y tpl)) s))) x)))
8666 (reverse r))))))
8668 (defun org-contextualize-validate-key (key contexts)
8669 "Check CONTEXTS for agenda or capture KEY."
8670 (let (r rr res)
8671 (while (setq r (pop contexts))
8672 (mapc
8673 (lambda (rr)
8674 (when
8675 (and (equal key (car r))
8676 (if (functionp rr) (funcall rr)
8677 (or (and (eq (car rr) 'in-file)
8678 (buffer-file-name)
8679 (string-match (cdr rr) (buffer-file-name)))
8680 (and (eq (car rr) 'in-mode)
8681 (string-match (cdr rr) (symbol-name major-mode)))
8682 (when (and (eq (car rr) 'not-in-file)
8683 (buffer-file-name))
8684 (not (string-match (cdr rr) (buffer-file-name))))
8685 (when (eq (car rr) 'not-in-mode)
8686 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8687 (push r res)))
8688 (car (last r))))
8689 (delete-dups (delq nil res))))
8691 (defun org-context-p (&rest contexts)
8692 "Check if local context is any of CONTEXTS.
8693 Possible values in the list of contexts are `table', `headline', and `item'."
8694 (let ((pos (point)))
8695 (goto-char (point-at-bol))
8696 (prog1 (or (and (memq 'table contexts)
8697 (looking-at "[ \t]*|"))
8698 (and (memq 'headline contexts)
8699 (looking-at org-outline-regexp))
8700 (and (memq 'item contexts)
8701 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8702 (and (memq 'item-body contexts)
8703 (org-in-item-p)))
8704 (goto-char pos))))
8706 (defun org-get-local-variables ()
8707 "Return a list of all local variables in an Org mode buffer."
8708 (let (varlist)
8709 (with-current-buffer (get-buffer-create "*Org tmp*")
8710 (erase-buffer)
8711 (org-mode)
8712 (setq varlist (buffer-local-variables)))
8713 (kill-buffer "*Org tmp*")
8714 (delq nil
8715 (mapcar
8716 (lambda (x)
8717 (setq x
8718 (if (symbolp x)
8719 (list x)
8720 (list (car x) (list 'quote (cdr x)))))
8721 (if (string-match
8722 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8723 (symbol-name (car x)))
8724 x nil))
8725 varlist))))
8727 (defun org-clone-local-variables (from-buffer &optional regexp)
8728 "Clone local variables from FROM-BUFFER.
8729 Optional argument REGEXP selects variables to clone."
8730 (mapc
8731 (lambda (pair)
8732 (and (symbolp (car pair))
8733 (or (null regexp)
8734 (string-match regexp (symbol-name (car pair))))
8735 (set (make-local-variable (car pair))
8736 (cdr pair))))
8737 (buffer-local-variables from-buffer)))
8739 ;;;###autoload
8740 (defun org-run-like-in-org-mode (cmd)
8741 "Run a command, pretending that the current buffer is in Org-mode.
8742 This will temporarily bind local variables that are typically bound in
8743 Org-mode to the values they have in Org-mode, and then interactively
8744 call CMD."
8745 (org-load-modules-maybe)
8746 (unless org-local-vars
8747 (setq org-local-vars (org-get-local-variables)))
8748 (eval (list 'let org-local-vars
8749 (list 'call-interactively (list 'quote cmd)))))
8751 ;;;; Archiving
8753 (defun org-get-category (&optional pos force-refresh)
8754 "Get the category applying to position POS."
8755 (save-match-data
8756 (if force-refresh (org-refresh-category-properties))
8757 (let ((pos (or pos (point))))
8758 (or (get-text-property pos 'org-category)
8759 (progn (org-refresh-category-properties)
8760 (get-text-property pos 'org-category))))))
8762 (defun org-refresh-category-properties ()
8763 "Refresh category text properties in the buffer."
8764 (let ((case-fold-search t)
8765 (inhibit-read-only t)
8766 (def-cat (cond
8767 ((null org-category)
8768 (if buffer-file-name
8769 (file-name-sans-extension
8770 (file-name-nondirectory buffer-file-name))
8771 "???"))
8772 ((symbolp org-category) (symbol-name org-category))
8773 (t org-category)))
8774 beg end cat pos optionp)
8775 (org-unmodified
8776 (save-excursion
8777 (save-restriction
8778 (widen)
8779 (goto-char (point-min))
8780 (put-text-property (point) (point-max) 'org-category def-cat)
8781 (while (re-search-forward
8782 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8783 (setq pos (match-end 0)
8784 optionp (equal (char-after (match-beginning 0)) ?#)
8785 cat (org-trim (match-string 2)))
8786 (if optionp
8787 (setq beg (point-at-bol) end (point-max))
8788 (org-back-to-heading t)
8789 (setq beg (point) end (org-end-of-subtree t t)))
8790 (put-text-property beg end 'org-category cat)
8791 (put-text-property beg end 'org-category-position beg)
8792 (goto-char pos)))))))
8795 ;;;; Link Stuff
8797 ;;; Link abbreviations
8799 (defun org-link-expand-abbrev (link)
8800 "Apply replacements as defined in `org-link-abbrev-alist'."
8801 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8802 (let* ((key (match-string 1 link))
8803 (as (or (assoc key org-link-abbrev-alist-local)
8804 (assoc key org-link-abbrev-alist)))
8805 (tag (and (match-end 2) (match-string 3 link)))
8806 rpl)
8807 (if (not as)
8808 link
8809 (setq rpl (cdr as))
8810 (cond
8811 ((symbolp rpl) (funcall rpl tag))
8812 ((string-match "%(\\([^)]+\\))" rpl)
8813 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8814 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8815 ((string-match "%h" rpl)
8816 (replace-match (url-hexify-string (or tag "")) t t rpl))
8817 (t (concat rpl tag)))))
8818 link))
8820 ;;; Storing and inserting links
8822 (defvar org-insert-link-history nil
8823 "Minibuffer history for links inserted with `org-insert-link'.")
8825 (defvar org-stored-links nil
8826 "Contains the links stored with `org-store-link'.")
8828 (defvar org-store-link-plist nil
8829 "Plist with info about the most recently link created with `org-store-link'.")
8831 (defvar org-link-protocols nil
8832 "Link protocols added to Org-mode using `org-add-link-type'.")
8834 (defvar org-store-link-functions nil
8835 "List of functions that are called to create and store a link.
8836 Each function will be called in turn until one returns a non-nil
8837 value. Each function should check if it is responsible for creating
8838 this link (for example by looking at the major mode).
8839 If not, it must exit and return nil.
8840 If yes, it should return a non-nil value after a calling
8841 `org-store-link-props' with a list of properties and values.
8842 Special properties are:
8844 :type The link prefix, like \"http\". This must be given.
8845 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8846 This is obligatory as well.
8847 :description Optional default description for the second pair
8848 of brackets in an Org-mode link. The user can still change
8849 this when inserting this link into an Org-mode buffer.
8851 In addition to these, any additional properties can be specified
8852 and then used in remember templates.")
8854 (defun org-add-link-type (type &optional follow export)
8855 "Add TYPE to the list of `org-link-types'.
8856 Re-compute all regular expressions depending on `org-link-types'
8858 FOLLOW and EXPORT are two functions.
8860 FOLLOW should take the link path as the single argument and do whatever
8861 is necessary to follow the link, for example find a file or display
8862 a mail message.
8864 EXPORT should format the link path for export to one of the export formats.
8865 It should be a function accepting three arguments:
8867 path the path of the link, the text after the prefix (like \"http:\")
8868 desc the description of the link, if any, or a description added by
8869 org-export-normalize-links if there is none
8870 format the export format, a symbol like `html' or `latex' or `ascii'..
8872 The function may use the FORMAT information to return different values
8873 depending on the format. The return value will be put literally into
8874 the exported file. If the return value is nil, this means Org should
8875 do what it normally does with links which do not have EXPORT defined.
8877 Org-mode has a built-in default for exporting links. If you are happy with
8878 this default, there is no need to define an export function for the link
8879 type. For a simple example of an export function, see `org-bbdb.el'."
8880 (add-to-list 'org-link-types type t)
8881 (org-make-link-regexps)
8882 (if (assoc type org-link-protocols)
8883 (setcdr (assoc type org-link-protocols) (list follow export))
8884 (push (list type follow export) org-link-protocols)))
8886 (defvar org-agenda-buffer-name)
8888 ;;;###autoload
8889 (defun org-store-link (arg)
8890 "\\<org-mode-map>Store an org-link to the current location.
8891 This link is added to `org-stored-links' and can later be inserted
8892 into an org-buffer with \\[org-insert-link].
8894 For some link types, a prefix arg is interpreted:
8895 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8896 For file links, arg negates `org-context-in-file-links'."
8897 (interactive "P")
8898 (org-load-modules-maybe)
8899 (setq org-store-link-plist nil) ; reset
8900 (org-with-limited-levels
8901 (let (link cpltxt desc description search txt custom-id agenda-link)
8902 (cond
8904 ((run-hook-with-args-until-success 'org-store-link-functions)
8905 (setq link (plist-get org-store-link-plist :link)
8906 desc (or (plist-get org-store-link-plist :description) link)))
8908 ((org-src-edit-buffer-p)
8909 (let (label gc)
8910 (while (or (not label)
8911 (save-excursion
8912 (save-restriction
8913 (widen)
8914 (goto-char (point-min))
8915 (re-search-forward
8916 (regexp-quote (format org-coderef-label-format label))
8917 nil t))))
8918 (when label (message "Label exists already") (sit-for 2))
8919 (setq label (read-string "Code line label: " label)))
8920 (end-of-line 1)
8921 (setq link (format org-coderef-label-format label))
8922 (setq gc (- 79 (length link)))
8923 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8924 (insert link)
8925 (setq link (concat "(" label ")") desc nil)))
8927 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8928 ;; We are in the agenda, link to referenced location
8929 (let ((m (or (get-text-property (point) 'org-hd-marker)
8930 (get-text-property (point) 'org-marker))))
8931 (when m
8932 (org-with-point-at m
8933 (setq agenda-link
8934 (if (org-called-interactively-p 'any)
8935 (call-interactively 'org-store-link)
8936 (org-store-link nil)))))))
8938 ((eq major-mode 'calendar-mode)
8939 (let ((cd (calendar-cursor-to-date)))
8940 (setq link
8941 (format-time-string
8942 (car org-time-stamp-formats)
8943 (apply 'encode-time
8944 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8945 nil nil nil))))
8946 (org-store-link-props :type "calendar" :date cd)))
8948 ((eq major-mode 'help-mode)
8949 (setq link (concat "help:" (save-excursion
8950 (goto-char (point-min))
8951 (looking-at "^[^ ]+")
8952 (match-string 0))))
8953 (org-store-link-props :type "help"))
8955 ((eq major-mode 'w3-mode)
8956 (setq cpltxt (if (and (buffer-name)
8957 (not (string-match "Untitled" (buffer-name))))
8958 (buffer-name)
8959 (url-view-url t))
8960 link (url-view-url t))
8961 (org-store-link-props :type "w3" :url (url-view-url t)))
8963 ((eq major-mode 'w3m-mode)
8964 (setq cpltxt (or w3m-current-title w3m-current-url)
8965 link w3m-current-url)
8966 (org-store-link-props :type "w3m" :url (url-view-url t)))
8968 ((setq search (run-hook-with-args-until-success
8969 'org-create-file-search-functions))
8970 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8971 "::" search))
8972 (setq cpltxt (or description link)))
8974 ((eq major-mode 'image-mode)
8975 (setq cpltxt (concat "file:"
8976 (abbreviate-file-name buffer-file-name))
8977 link cpltxt)
8978 (org-store-link-props :type "image" :file buffer-file-name))
8980 ((eq major-mode 'dired-mode)
8981 ;; link to the file in the current line
8982 (let ((file (dired-get-filename nil t)))
8983 (setq file (if file
8984 (abbreviate-file-name
8985 (expand-file-name (dired-get-filename nil t)))
8986 ;; otherwise, no file so use current directory.
8987 default-directory))
8988 (setq cpltxt (concat "file:" file)
8989 link cpltxt)))
8991 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8992 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8993 (cond
8994 ((org-in-regexp "<<\\(.*?\\)>>")
8995 (setq cpltxt
8996 (concat "file:"
8997 (abbreviate-file-name
8998 (buffer-file-name (buffer-base-buffer)))
8999 "::" (match-string 1))
9000 link cpltxt))
9001 ((and (featurep 'org-id)
9002 (or (eq org-link-to-org-use-id t)
9003 (and (org-called-interactively-p 'any)
9004 (or (eq org-link-to-org-use-id 'create-if-interactive)
9005 (and (eq org-link-to-org-use-id
9006 'create-if-interactive-and-no-custom-id)
9007 (not custom-id))))
9008 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9009 ;; We can make a link using the ID.
9010 (setq link (condition-case nil
9011 (prog1 (org-id-store-link)
9012 (setq desc (plist-get org-store-link-plist :description)))
9013 (error
9014 ;; probably before first headline, link to file only
9015 (concat "file:"
9016 (abbreviate-file-name
9017 (buffer-file-name (buffer-base-buffer))))))))
9019 ;; Just link to current headline
9020 (setq cpltxt (concat "file:"
9021 (abbreviate-file-name
9022 (buffer-file-name (buffer-base-buffer)))))
9023 ;; Add a context search string
9024 (when (org-xor org-context-in-file-links arg)
9025 (setq txt (cond
9026 ((org-at-heading-p) nil)
9027 ((org-region-active-p)
9028 (buffer-substring (region-beginning) (region-end)))))
9029 (when (or (null txt) (string-match "\\S-" txt))
9030 (setq cpltxt
9031 (concat cpltxt "::"
9032 (condition-case nil
9033 (org-make-org-heading-search-string txt)
9034 (error "")))
9035 desc (or (nth 4 (ignore-errors
9036 (org-heading-components))) "NONE"))))
9037 (if (string-match "::\\'" cpltxt)
9038 (setq cpltxt (substring cpltxt 0 -2)))
9039 (setq link cpltxt))))
9041 ((buffer-file-name (buffer-base-buffer))
9042 ;; Just link to this file here.
9043 (setq cpltxt (concat "file:"
9044 (abbreviate-file-name
9045 (buffer-file-name (buffer-base-buffer)))))
9046 ;; Add a context string
9047 (when (org-xor org-context-in-file-links arg)
9048 (setq txt (if (org-region-active-p)
9049 (buffer-substring (region-beginning) (region-end))
9050 (buffer-substring (point-at-bol) (point-at-eol))))
9051 ;; Only use search option if there is some text.
9052 (when (string-match "\\S-" txt)
9053 (setq cpltxt
9054 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9055 desc "NONE")))
9056 (setq link cpltxt))
9058 ((org-called-interactively-p 'interactive)
9059 (error "Cannot link to a buffer which is not visiting a file"))
9061 (t (setq link nil)))
9063 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9064 (setq link (or link cpltxt)
9065 desc (or desc cpltxt))
9066 (if (equal desc "NONE") (setq desc nil))
9068 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9069 (progn
9070 (setq org-stored-links
9071 (cons (list link desc) org-stored-links))
9072 (message "Stored: %s" (or desc link))
9073 (when custom-id
9074 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9075 "::#" custom-id))
9076 (setq org-stored-links
9077 (cons (list link desc) org-stored-links))))
9078 (or agenda-link (and link (org-make-link-string link desc)))))))
9080 (defun org-store-link-props (&rest plist)
9081 "Store link properties, extract names and addresses."
9082 (let (x adr)
9083 (when (setq x (plist-get plist :from))
9084 (setq adr (mail-extract-address-components x))
9085 (setq plist (plist-put plist :fromname (car adr)))
9086 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9087 (when (setq x (plist-get plist :to))
9088 (setq adr (mail-extract-address-components x))
9089 (setq plist (plist-put plist :toname (car adr)))
9090 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9091 (let ((from (plist-get plist :from))
9092 (to (plist-get plist :to)))
9093 (when (and from to org-from-is-user-regexp)
9094 (setq plist
9095 (plist-put plist :fromto
9096 (if (string-match org-from-is-user-regexp from)
9097 (concat "to %t")
9098 (concat "from %f"))))))
9099 (setq org-store-link-plist plist))
9101 (defun org-add-link-props (&rest plist)
9102 "Add these properties to the link property list."
9103 (let (key value)
9104 (while plist
9105 (setq key (pop plist) value (pop plist))
9106 (setq org-store-link-plist
9107 (plist-put org-store-link-plist key value)))))
9109 (defun org-email-link-description (&optional fmt)
9110 "Return the description part of an email link.
9111 This takes information from `org-store-link-plist' and formats it
9112 according to FMT (default from `org-email-link-description-format')."
9113 (setq fmt (or fmt org-email-link-description-format))
9114 (let* ((p org-store-link-plist)
9115 (to (plist-get p :toaddress))
9116 (from (plist-get p :fromaddress))
9117 (table
9118 (list
9119 (cons "%c" (plist-get p :fromto))
9120 (cons "%F" (plist-get p :from))
9121 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9122 (cons "%T" (plist-get p :to))
9123 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9124 (cons "%s" (plist-get p :subject))
9125 (cons "%d" (plist-get p :date))
9126 (cons "%m" (plist-get p :message-id)))))
9127 (when (string-match "%c" fmt)
9128 ;; Check if the user wrote this message
9129 (if (and org-from-is-user-regexp from to
9130 (save-match-data (string-match org-from-is-user-regexp from)))
9131 (setq fmt (replace-match "to %t" t t fmt))
9132 (setq fmt (replace-match "from %f" t t fmt))))
9133 (org-replace-escapes fmt table)))
9135 (defun org-make-org-heading-search-string (&optional string heading)
9136 "Make search string for STRING or current headline."
9137 (interactive)
9138 (let ((s (or string (org-get-heading)))
9139 (lines org-context-in-file-links))
9140 (unless (and string (not heading))
9141 ;; We are using a headline, clean up garbage in there.
9142 (if (string-match org-todo-regexp s)
9143 (setq s (replace-match "" t t s)))
9144 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9145 (setq s (replace-match "" t t s)))
9146 (setq s (org-trim s))
9147 (if (string-match (concat "^\\(" org-quote-string "\\|"
9148 org-comment-string "\\)") s)
9149 (setq s (replace-match "" t t s)))
9150 (while (string-match org-ts-regexp s)
9151 (setq s (replace-match "" t t s))))
9152 (or string (setq s (concat "*" s))) ; Add * for headlines
9153 (when (and string (integerp lines) (> lines 0))
9154 (let ((slines (org-split-string s "\n")))
9155 (when (< lines (length slines))
9156 (setq s (mapconcat
9157 'identity
9158 (reverse (nthcdr (- (length slines) lines)
9159 (reverse slines))) "\n")))))
9160 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9162 (defun org-make-link-string (link &optional description)
9163 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9164 (unless (string-match "\\S-" link)
9165 (error "Empty link"))
9166 (when (and description
9167 (stringp description)
9168 (not (string-match "\\S-" description)))
9169 (setq description nil))
9170 (when (stringp description)
9171 ;; Remove brackets from the description, they are fatal.
9172 (while (string-match "\\[" description)
9173 (setq description (replace-match "{" t t description)))
9174 (while (string-match "\\]" description)
9175 (setq description (replace-match "}" t t description))))
9176 (when (equal link description)
9177 ;; No description needed, it is identical
9178 (setq description nil))
9179 (when (and (not description)
9180 (not (string-match (org-image-file-name-regexp) link))
9181 (not (equal link (org-link-escape link))))
9182 (setq description (org-extract-attributes link)))
9183 (setq link
9184 (cond ((string-match (org-image-file-name-regexp) link) link)
9185 ((string-match org-link-types-re link)
9186 (concat (match-string 1 link)
9187 (org-link-escape (substring link (match-end 1)))))
9188 (t (org-link-escape link))))
9189 (concat "[[" link "]"
9190 (if description (concat "[" description "]") "")
9191 "]"))
9193 (defconst org-link-escape-chars
9194 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9195 "List of characters that should be escaped in link.
9196 This is the list that is used for internal purposes.")
9198 (defconst org-link-escape-chars-browser
9199 '(?\ )
9200 "List of escapes for characters that are problematic in links.
9201 This is the list that is used before handing over to the browser.")
9203 (defun org-link-escape (text &optional table merge)
9204 "Return percent escaped representation of TEXT.
9205 TEXT is a string with the text to escape.
9206 Optional argument TABLE is a list with characters that should be
9207 escaped. When nil, `org-link-escape-chars' is used.
9208 If optional argument MERGE is set, merge TABLE into
9209 `org-link-escape-chars'."
9210 (cond
9211 ((and table merge)
9212 (mapc (lambda (defchr)
9213 (unless (member defchr table)
9214 (setq table (cons defchr table)))) org-link-escape-chars))
9215 ((null table)
9216 (setq table org-link-escape-chars)))
9217 (mapconcat
9218 (lambda (char)
9219 (if (or (member char table)
9220 (and (or (< char 32) (= char 37) (> char 126))
9221 org-url-hexify-p))
9222 (mapconcat (lambda (sequence-element)
9223 (format "%%%.2X" sequence-element))
9224 (or (encode-coding-char char 'utf-8)
9225 (error "Unable to percent escape character: %s"
9226 (char-to-string char))) "")
9227 (char-to-string char))) text ""))
9229 (defun org-link-unescape (str)
9230 "Unhex hexified Unicode strings as returned from the JavaScript function
9231 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9232 (unless (and (null str) (string= "" str))
9233 (let ((pos 0) (case-fold-search t) unhexed)
9234 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9235 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9236 (setq str (replace-match unhexed t t str))
9237 (setq pos (+ pos (length unhexed))))))
9238 str)
9240 (defun org-link-unescape-compound (hex)
9241 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9242 Note: this function also decodes single byte encodings like
9243 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9244 (save-match-data
9245 (let* ((bytes (cdr (split-string hex "%")))
9246 (ret "")
9247 (eat 0)
9248 (sum 0))
9249 (while bytes
9250 (let* ((val (string-to-number (pop bytes) 16))
9251 (shift-xor
9252 (if (= 0 eat)
9253 (cond
9254 ((>= val 252) (cons 6 252))
9255 ((>= val 248) (cons 5 248))
9256 ((>= val 240) (cons 4 240))
9257 ((>= val 224) (cons 3 224))
9258 ((>= val 192) (cons 2 192))
9259 (t (cons 0 0)))
9260 (cons 6 128))))
9261 (if (>= val 192) (setq eat (car shift-xor)))
9262 (setq val (logxor val (cdr shift-xor)))
9263 (setq sum (+ (lsh sum (car shift-xor)) val))
9264 (if (> eat 0) (setq eat (- eat 1)))
9265 (cond
9266 ((= 0 eat) ;multi byte
9267 (setq ret (concat ret (org-char-to-string sum)))
9268 (setq sum 0))
9269 ((not bytes) ; single byte(s)
9270 (setq ret (org-link-unescape-single-byte-sequence hex))))
9271 )) ;; end (while bytes
9272 ret )))
9274 (defun org-link-unescape-single-byte-sequence (hex)
9275 "Unhexify hex-encoded single byte character sequences."
9276 (mapconcat (lambda (byte)
9277 (char-to-string (string-to-number byte 16)))
9278 (cdr (split-string hex "%")) ""))
9280 (defun org-xor (a b)
9281 "Exclusive or."
9282 (if a (not b) b))
9284 (defun org-fixup-message-id-for-http (s)
9285 "Replace special characters in a message id, so it can be used in an http query."
9286 (when (string-match "%" s)
9287 (setq s (mapconcat (lambda (c)
9288 (if (eq c ?%)
9289 "%25"
9290 (char-to-string c)))
9291 s "")))
9292 (while (string-match "<" s)
9293 (setq s (replace-match "%3C" t t s)))
9294 (while (string-match ">" s)
9295 (setq s (replace-match "%3E" t t s)))
9296 (while (string-match "@" s)
9297 (setq s (replace-match "%40" t t s)))
9300 (defun org-link-prettify (link)
9301 "Return a human-readable representation of LINK.
9302 The car of LINK must be a raw link the cdr of LINK must be either
9303 a link description or nil."
9304 (let ((desc (or (cadr link) "<no description>")))
9305 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9306 "<" (car link) ">")))
9308 ;;;###autoload
9309 (defun org-insert-link-global ()
9310 "Insert a link like Org-mode does.
9311 This command can be called in any mode to insert a link in Org-mode syntax."
9312 (interactive)
9313 (org-load-modules-maybe)
9314 (org-run-like-in-org-mode 'org-insert-link))
9316 (defun org-insert-all-links (&optional keep)
9317 "Insert all links in `org-stored-links'."
9318 (interactive "P")
9319 (let ((links (copy-sequence org-stored-links)) l)
9320 (while (setq l (if keep (pop links) (pop org-stored-links)))
9321 (insert "- ")
9322 (org-insert-link nil (car l) (cadr l))
9323 (insert "\n"))))
9325 (defun org-link-fontify-links-to-this-file ()
9326 "Fontify links to the current file in `org-stored-links'."
9327 (let ((f (buffer-file-name)) a b)
9328 (setq a (mapcar (lambda(l)
9329 (let ((ll (car l)))
9330 (when (and (string-match "^file:\\(.+\\)::" ll)
9331 (equal f (expand-file-name (match-string 1 ll))))
9332 ll)))
9333 org-stored-links))
9334 (when (featurep 'org-id)
9335 (setq b (mapcar (lambda(l)
9336 (let ((ll (car l)))
9337 (when (and (string-match "^id:\\(.+\\)$" ll)
9338 (equal f (expand-file-name
9339 (or (org-id-find-id-file
9340 (match-string 1 ll)) ""))))
9341 ll)))
9342 org-stored-links)))
9343 (mapcar (lambda(l)
9344 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9345 (delq nil (append a b)))))
9347 (defvar org-link-links-in-this-file nil)
9348 (defun org-insert-link (&optional complete-file link-location default-description)
9349 "Insert a link. At the prompt, enter the link.
9351 Completion can be used to insert any of the link protocol prefixes like
9352 http or ftp in use.
9354 The history can be used to select a link previously stored with
9355 `org-store-link'. When the empty string is entered (i.e. if you just
9356 press RET at the prompt), the link defaults to the most recently
9357 stored link. As SPC triggers completion in the minibuffer, you need to
9358 use M-SPC or C-q SPC to force the insertion of a space character.
9360 You will also be prompted for a description, and if one is given, it will
9361 be displayed in the buffer instead of the link.
9363 If there is already a link at point, this command will allow you to edit link
9364 and description parts.
9366 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9367 be selected using completion. The path to the file will be relative to the
9368 current directory if the file is in the current directory or a subdirectory.
9369 Otherwise, the link will be the absolute path as completed in the minibuffer
9370 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9371 option `org-link-file-path-type'.
9373 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9374 the current directory or below.
9376 With three \\[universal-argument] prefixes, negate the meaning of
9377 `org-keep-stored-link-after-insertion'.
9379 If `org-make-link-description-function' is non-nil, this function will be
9380 called with the link target, and the result will be the default
9381 link description.
9383 If the LINK-LOCATION parameter is non-nil, this value will be
9384 used as the link location instead of reading one interactively.
9386 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9387 be used as the default description."
9388 (interactive "P")
9389 (let* ((wcf (current-window-configuration))
9390 (region (if (org-region-active-p)
9391 (buffer-substring (region-beginning) (region-end))))
9392 (remove (and region (list (region-beginning) (region-end))))
9393 (desc region)
9394 tmphist ; byte-compile incorrectly complains about this
9395 (link link-location)
9396 (abbrevs org-link-abbrev-alist-local)
9397 entry file all-prefixes auto-desc)
9398 (cond
9399 (link-location) ; specified by arg, just use it.
9400 ((org-in-regexp org-bracket-link-regexp 1)
9401 ;; We do have a link at point, and we are going to edit it.
9402 (setq remove (list (match-beginning 0) (match-end 0)))
9403 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9404 (setq link (read-string "Link: "
9405 (org-link-unescape
9406 (org-match-string-no-properties 1)))))
9407 ((or (org-in-regexp org-angle-link-re)
9408 (org-in-regexp org-plain-link-re))
9409 ;; Convert to bracket link
9410 (setq remove (list (match-beginning 0) (match-end 0))
9411 link (read-string "Link: "
9412 (org-remove-angle-brackets (match-string 0)))))
9413 ((member complete-file '((4) (16)))
9414 ;; Completing read for file names.
9415 (setq link (org-file-complete-link complete-file)))
9417 ;; Read link, with completion for stored links.
9418 (org-link-fontify-links-to-this-file)
9419 (org-switch-to-buffer-other-window "*Org Links*")
9420 (with-current-buffer "*Org Links*"
9421 (erase-buffer)
9422 (insert "Insert a link.
9423 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9424 (when org-stored-links
9425 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9426 (insert (mapconcat 'org-link-prettify
9427 (reverse org-stored-links) "\n")))
9428 (goto-char (point-min)))
9429 (let ((cw (selected-window)))
9430 (select-window (get-buffer-window "*Org Links*" 'visible))
9431 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9432 (unless (pos-visible-in-window-p (point-max))
9433 (org-fit-window-to-buffer))
9434 (and (window-live-p cw) (select-window cw)))
9435 ;; Fake a link history, containing the stored links.
9436 (setq tmphist (append (mapcar 'car org-stored-links)
9437 org-insert-link-history))
9438 (setq all-prefixes (append (mapcar 'car abbrevs)
9439 (mapcar 'car org-link-abbrev-alist)
9440 org-link-types))
9441 (unwind-protect
9442 (progn
9443 (setq link
9444 (let ((org-completion-use-ido nil)
9445 (org-completion-use-iswitchb nil))
9446 (org-completing-read
9447 "Link: "
9448 (append
9449 (mapcar (lambda (x) (list (concat x ":")))
9450 all-prefixes)
9451 (mapcar 'car org-stored-links)
9452 (mapcar 'cadr org-stored-links))
9453 nil nil nil
9454 'tmphist
9455 (caar org-stored-links))))
9456 (if (not (string-match "\\S-" link))
9457 (error "No link selected"))
9458 (mapc (lambda(l)
9459 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9460 org-stored-links)
9461 (if (or (member link all-prefixes)
9462 (and (equal ":" (substring link -1))
9463 (member (substring link 0 -1) all-prefixes)
9464 (setq link (substring link 0 -1))))
9465 (setq link (org-link-try-special-completion link))))
9466 (set-window-configuration wcf)
9467 (kill-buffer "*Org Links*"))
9468 (setq entry (assoc link org-stored-links))
9469 (or entry (push link org-insert-link-history))
9470 (setq desc (or desc (nth 1 entry)))))
9472 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9473 (not org-keep-stored-link-after-insertion))
9474 (setq org-stored-links (delq (assoc link org-stored-links)
9475 org-stored-links)))
9477 (if (string-match org-plain-link-re link)
9478 ;; URL-like link, normalize the use of angular brackets.
9479 (setq link (org-remove-angle-brackets link)))
9481 ;; Check if we are linking to the current file with a search option
9482 ;; If yes, simplify the link by using only the search option.
9483 (when (and buffer-file-name
9484 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9485 (let* ((path (match-string 1 link))
9486 (case-fold-search nil)
9487 (search (match-string 2 link)))
9488 (save-match-data
9489 (if (equal (file-truename buffer-file-name) (file-truename path))
9490 ;; We are linking to this same file, with a search option
9491 (setq link search)))))
9493 ;; Check if we can/should use a relative path. If yes, simplify the link
9494 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9495 (let* ((type (match-string 1 link))
9496 (path (match-string 2 link))
9497 (origpath path)
9498 (case-fold-search nil))
9499 (cond
9500 ((or (eq org-link-file-path-type 'absolute)
9501 (equal complete-file '(16)))
9502 (setq path (abbreviate-file-name (expand-file-name path))))
9503 ((eq org-link-file-path-type 'noabbrev)
9504 (setq path (expand-file-name path)))
9505 ((eq org-link-file-path-type 'relative)
9506 (setq path (file-relative-name path)))
9508 (save-match-data
9509 (if (string-match (concat "^" (regexp-quote
9510 (expand-file-name
9511 (file-name-as-directory
9512 default-directory))))
9513 (expand-file-name path))
9514 ;; We are linking a file with relative path name.
9515 (setq path (substring (expand-file-name path)
9516 (match-end 0)))
9517 (setq path (abbreviate-file-name (expand-file-name path)))))))
9518 (setq link (concat type path))
9519 (if (equal desc origpath)
9520 (setq desc path))))
9522 (if org-make-link-description-function
9523 (setq desc (funcall org-make-link-description-function link desc))
9524 (if default-description (setq desc default-description)
9525 (setq desc (or (and auto-desc desc)
9526 (read-string "Description: " desc)))))
9528 (unless (string-match "\\S-" desc) (setq desc nil))
9529 (if remove (apply 'delete-region remove))
9530 (insert (org-make-link-string link desc))))
9532 (defun org-link-try-special-completion (type)
9533 "If there is completion support for link type TYPE, offer it."
9534 (let ((fun (intern (concat "org-" type "-complete-link"))))
9535 (if (functionp fun)
9536 (funcall fun)
9537 (read-string "Link (no completion support): " (concat type ":")))))
9539 (defun org-file-complete-link (&optional arg)
9540 "Create a file link using completion."
9541 (let (file link)
9542 (setq file (read-file-name "File: "))
9543 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9544 (pwd1 (file-name-as-directory (abbreviate-file-name
9545 (expand-file-name ".")))))
9546 (cond
9547 ((equal arg '(16))
9548 (setq link (concat
9549 "file:"
9550 (abbreviate-file-name (expand-file-name file)))))
9551 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9552 (setq link (concat "file:" (match-string 1 file))))
9553 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9554 (expand-file-name file))
9555 (setq link (concat
9556 "file:" (match-string 1 (expand-file-name file)))))
9557 (t (setq link (concat "file:" file)))))
9558 link))
9560 (defun org-completing-read (&rest args)
9561 "Completing-read with SPACE being a normal character."
9562 (let ((enable-recursive-minibuffers t)
9563 (minibuffer-local-completion-map
9564 (copy-keymap minibuffer-local-completion-map)))
9565 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9566 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9567 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9568 (apply 'org-icompleting-read args)))
9570 (defun org-completing-read-no-i (&rest args)
9571 (let (org-completion-use-ido org-completion-use-iswitchb)
9572 (apply 'org-completing-read args)))
9574 (defun org-iswitchb-completing-read (prompt choices &rest args)
9575 "Use iswitch as a completing-read replacement to choose from choices.
9576 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9577 from."
9578 (let* ((iswitchb-use-virtual-buffers nil)
9579 (iswitchb-make-buflist-hook
9580 (lambda ()
9581 (setq iswitchb-temp-buflist choices))))
9582 (iswitchb-read-buffer prompt)))
9584 (defun org-icompleting-read (&rest args)
9585 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9586 (org-without-partial-completion
9587 (if (and org-completion-use-ido
9588 (fboundp 'ido-completing-read)
9589 (boundp 'ido-mode) ido-mode
9590 (listp (second args)))
9591 (let ((ido-enter-matching-directory nil))
9592 (apply 'ido-completing-read (concat (car args))
9593 (if (consp (car (nth 1 args)))
9594 (mapcar 'car (nth 1 args))
9595 (nth 1 args))
9596 (cddr args)))
9597 (if (and org-completion-use-iswitchb
9598 (boundp 'iswitchb-mode) iswitchb-mode
9599 (listp (second args)))
9600 (apply 'org-iswitchb-completing-read (concat (car args))
9601 (if (consp (car (nth 1 args)))
9602 (mapcar 'car (nth 1 args))
9603 (nth 1 args))
9604 (cddr args))
9605 (apply 'completing-read args)))))
9607 (defun org-extract-attributes (s)
9608 "Extract the attributes cookie from a string and set as text property."
9609 (let (a attr (start 0) key value)
9610 (save-match-data
9611 (when (string-match "{{\\([^}]+\\)}}$" s)
9612 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9613 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9614 (setq key (match-string 1 a) value (match-string 2 a)
9615 start (match-end 0)
9616 attr (plist-put attr (intern key) value))))
9617 (org-add-props s nil 'org-attr attr))
9620 (defun org-extract-attributes-from-string (tag)
9621 (let (key value attr)
9622 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9623 (setq key (match-string 1 tag) value (match-string 2 tag)
9624 tag (replace-match "" t t tag)
9625 attr (plist-put attr (intern key) value)))
9626 (cons tag attr)))
9628 (defun org-attributes-to-string (plist)
9629 "Format a property list into an HTML attribute list."
9630 (let ((s "") key value)
9631 (while plist
9632 (setq key (pop plist) value (pop plist))
9633 (and value
9634 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9637 ;;; Opening/following a link
9639 (defvar org-link-search-failed nil)
9641 (defvar org-open-link-functions nil
9642 "Hook for functions finding a plain text link.
9643 These functions must take a single argument, the link content.
9644 They will be called for links that look like [[link text][description]]
9645 when LINK TEXT does not have a protocol like \"http:\" and does not look
9646 like a filename (e.g. \"./blue.png\").
9648 These functions will be called *before* Org attempts to resolve the
9649 link by doing text searches in the current buffer - so if you want a
9650 link \"[[target]]\" to still find \"<<target>>\", your function should
9651 handle this as a special case.
9653 When the function does handle the link, it must return a non-nil value.
9654 If it decides that it is not responsible for this link, it must return
9655 nil to indicate that that Org-mode can continue with other options
9656 like exact and fuzzy text search.")
9658 (defun org-next-link ()
9659 "Move forward to the next link.
9660 If the link is in hidden text, expose it."
9661 (interactive)
9662 (when (and org-link-search-failed (eq this-command last-command))
9663 (goto-char (point-min))
9664 (message "Link search wrapped back to beginning of buffer"))
9665 (setq org-link-search-failed nil)
9666 (let* ((pos (point))
9667 (ct (org-context))
9668 (a (assoc :link ct)))
9669 (if a (goto-char (nth 2 a)))
9670 (if (re-search-forward org-any-link-re nil t)
9671 (progn
9672 (goto-char (match-beginning 0))
9673 (if (outline-invisible-p) (org-show-context)))
9674 (goto-char pos)
9675 (setq org-link-search-failed t)
9676 (error "No further link found"))))
9678 (defun org-previous-link ()
9679 "Move backward to the previous link.
9680 If the link is in hidden text, expose it."
9681 (interactive)
9682 (when (and org-link-search-failed (eq this-command last-command))
9683 (goto-char (point-max))
9684 (message "Link search wrapped back to end of buffer"))
9685 (setq org-link-search-failed nil)
9686 (let* ((pos (point))
9687 (ct (org-context))
9688 (a (assoc :link ct)))
9689 (if a (goto-char (nth 1 a)))
9690 (if (re-search-backward org-any-link-re nil t)
9691 (progn
9692 (goto-char (match-beginning 0))
9693 (if (outline-invisible-p) (org-show-context)))
9694 (goto-char pos)
9695 (setq org-link-search-failed t)
9696 (error "No further link found"))))
9698 (defun org-translate-link (s)
9699 "Translate a link string if a translation function has been defined."
9700 (if (and org-link-translation-function
9701 (fboundp org-link-translation-function)
9702 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9703 (progn
9704 (setq s (funcall org-link-translation-function
9705 (match-string 1 s) (match-string 2 s)))
9706 (concat (car s) ":" (cdr s)))
9709 (defun org-translate-link-from-planner (type path)
9710 "Translate a link from Emacs Planner syntax so that Org can follow it.
9711 This is still an experimental function, your mileage may vary."
9712 (cond
9713 ((member type '("http" "https" "news" "ftp"))
9714 ;; standard Internet links are the same.
9715 nil)
9716 ((and (equal type "irc") (string-match "^//" path))
9717 ;; Planner has two / at the beginning of an irc link, we have 1.
9718 ;; We should have zero, actually....
9719 (setq path (substring path 1)))
9720 ((and (equal type "lisp") (string-match "^/" path))
9721 ;; Planner has a slash, we do not.
9722 (setq type "elisp" path (substring path 1)))
9723 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9724 ;; A typical message link. Planner has the id after the final slash,
9725 ;; we separate it with a hash mark
9726 (setq path (concat (match-string 1 path) "#"
9727 (org-remove-angle-brackets (match-string 2 path)))))
9729 (cons type path))
9731 (defun org-find-file-at-mouse (ev)
9732 "Open file link or URL at mouse."
9733 (interactive "e")
9734 (mouse-set-point ev)
9735 (org-open-at-point 'in-emacs))
9737 (defun org-open-at-mouse (ev)
9738 "Open file link or URL at mouse.
9739 See the docstring of `org-open-file' for details."
9740 (interactive "e")
9741 (mouse-set-point ev)
9742 (if (eq major-mode 'org-agenda-mode)
9743 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9744 (org-open-at-point))
9746 (defvar org-window-config-before-follow-link nil
9747 "The window configuration before following a link.
9748 This is saved in case the need arises to restore it.")
9750 (defvar org-open-link-marker (make-marker)
9751 "Marker pointing to the location where `org-open-at-point; was called.")
9753 ;;;###autoload
9754 (defun org-open-at-point-global ()
9755 "Follow a link like Org-mode does.
9756 This command can be called in any mode to follow a link that has
9757 Org-mode syntax."
9758 (interactive)
9759 (org-run-like-in-org-mode 'org-open-at-point))
9761 ;;;###autoload
9762 (defun org-open-link-from-string (s &optional arg reference-buffer)
9763 "Open a link in the string S, as if it was in Org-mode."
9764 (interactive "sLink: \nP")
9765 (let ((reference-buffer (or reference-buffer (current-buffer))))
9766 (with-temp-buffer
9767 (let ((org-inhibit-startup (not reference-buffer)))
9768 (org-mode)
9769 (insert s)
9770 (goto-char (point-min))
9771 (when reference-buffer
9772 (setq org-link-abbrev-alist-local
9773 (with-current-buffer reference-buffer
9774 org-link-abbrev-alist-local)))
9775 (org-open-at-point arg reference-buffer)))))
9777 (defvar org-open-at-point-functions nil
9778 "Hook that is run when following a link at point.
9780 Functions in this hook must return t if they identify and follow
9781 a link at point. If they don't find anything interesting at point,
9782 they must return nil.")
9784 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9785 (defun org-open-at-point (&optional arg reference-buffer)
9786 "Open link at or after point.
9787 If there is no link at point, this function will search forward up to
9788 the end of the current line.
9789 Normally, files will be opened by an appropriate application. If the
9790 optional prefix argument ARG is non-nil, Emacs will visit the file.
9791 With a double prefix argument, try to open outside of Emacs, in the
9792 application the system uses for this file type."
9793 (interactive "P")
9794 ;; if in a code block, then open the block's results
9795 (unless (call-interactively #'org-babel-open-src-block-result)
9796 (org-load-modules-maybe)
9797 (move-marker org-open-link-marker (point))
9798 (setq org-window-config-before-follow-link (current-window-configuration))
9799 (org-remove-occur-highlights nil nil t)
9800 (cond
9801 ((and (org-at-heading-p)
9802 (not (org-at-timestamp-p t))
9803 (not (org-in-regexp
9804 (concat org-plain-link-re "\\|"
9805 org-bracket-link-regexp "\\|"
9806 org-angle-link-re "\\|"
9807 "[ \t]:[^ \t\n]+:[ \t]*$")))
9808 (not (get-text-property (point) 'org-linked-text)))
9809 (or (org-offer-links-in-entry arg)
9810 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9811 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9812 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9813 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9814 (not (org-in-regexp org-bracket-link-regexp)))
9815 (org-footnote-action))
9817 (let (type path link line search (pos (point)))
9818 (catch 'match
9819 (save-excursion
9820 (skip-chars-forward "^]\n\r")
9821 (when (org-in-regexp org-bracket-link-regexp 1)
9822 (setq link (org-extract-attributes
9823 (org-link-unescape (org-match-string-no-properties 1))))
9824 (while (string-match " *\n *" link)
9825 (setq link (replace-match " " t t link)))
9826 (setq link (org-link-expand-abbrev link))
9827 (cond
9828 ((or (file-name-absolute-p link)
9829 (string-match "^\\.\\.?/" link))
9830 (setq type "file" path link))
9831 ((string-match org-link-re-with-space3 link)
9832 (setq type (match-string 1 link) path (match-string 2 link)))
9833 ((string-match "^help:+\\(.+\\)" link)
9834 (setq type "help" path (match-string 1 link)))
9835 (t (setq type "thisfile" path link)))
9836 (throw 'match t)))
9838 (when (get-text-property (point) 'org-linked-text)
9839 (setq type "thisfile"
9840 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9841 (1+ (point)) (point))
9842 path (buffer-substring
9843 (or (previous-single-property-change pos 'org-linked-text)
9844 (point-min))
9845 (or (next-single-property-change pos 'org-linked-text)
9846 (point-max))))
9847 (throw 'match t))
9849 (save-excursion
9850 (when (or (org-in-regexp org-angle-link-re)
9851 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9852 (save-match-data (not (looking-back "\\[\\[")))))
9853 (setq type (match-string 1)
9854 path (org-link-unescape (match-string 2)))
9855 (throw 'match t)))
9856 (save-excursion
9857 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9858 (setq type "tags"
9859 path (match-string 1))
9860 (while (string-match ":" path)
9861 (setq path (replace-match "+" t t path)))
9862 (throw 'match t)))
9863 (when (org-in-regexp "<\\([^><\n]+\\)>")
9864 (setq type "tree-match"
9865 path (match-string 1))
9866 (throw 'match t)))
9867 (unless path
9868 (error "No link found"))
9870 ;; switch back to reference buffer
9871 ;; needed when if called in a temporary buffer through
9872 ;; org-open-link-from-string
9873 (with-current-buffer (or reference-buffer (current-buffer))
9875 ;; Remove any trailing spaces in path
9876 (if (string-match " +\\'" path)
9877 (setq path (replace-match "" t t path)))
9878 (if (and org-link-translation-function
9879 (fboundp org-link-translation-function))
9880 ;; Check if we need to translate the link
9881 (let ((tmp (funcall org-link-translation-function type path)))
9882 (setq type (car tmp) path (cdr tmp))))
9884 (cond
9886 ((assoc type org-link-protocols)
9887 (funcall (nth 1 (assoc type org-link-protocols)) path))
9889 ((equal type "help")
9890 (let ((f-or-v (intern path)))
9891 (cond ((fboundp f-or-v)
9892 (describe-function f-or-v))
9893 ((boundp f-or-v)
9894 (describe-variable f-or-v))
9895 (t (error "Not a known function or variable")))))
9897 ((equal type "mailto")
9898 (let ((cmd (car org-link-mailto-program))
9899 (args (cdr org-link-mailto-program)) args1
9900 (address path) (subject "") a)
9901 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9902 (setq address (match-string 1 path)
9903 subject (org-link-escape (match-string 2 path))))
9904 (while args
9905 (cond
9906 ((not (stringp (car args))) (push (pop args) args1))
9907 (t (setq a (pop args))
9908 (if (string-match "%a" a)
9909 (setq a (replace-match address t t a)))
9910 (if (string-match "%s" a)
9911 (setq a (replace-match subject t t a)))
9912 (push a args1))))
9913 (apply cmd (nreverse args1))))
9915 ((member type '("http" "https" "ftp" "news"))
9916 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9917 (org-link-escape
9918 path org-link-escape-chars-browser)
9919 path))))
9921 ((string= type "doi")
9922 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9923 (org-link-escape
9924 path org-link-escape-chars-browser)
9925 path))))
9927 ((member type '("message"))
9928 (browse-url (concat type ":" path)))
9930 ((string= type "tags")
9931 (org-tags-view arg path))
9933 ((string= type "tree-match")
9934 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9936 ((string= type "file")
9937 (if (string-match "::\\([0-9]+\\)\\'" path)
9938 (setq line (string-to-number (match-string 1 path))
9939 path (substring path 0 (match-beginning 0)))
9940 (if (string-match "::\\(.+\\)\\'" path)
9941 (setq search (match-string 1 path)
9942 path (substring path 0 (match-beginning 0)))))
9943 (if (string-match "[*?{]" (file-name-nondirectory path))
9944 (dired path)
9945 (org-open-file path arg line search)))
9947 ((string= type "shell")
9948 (let ((buf (generate-new-buffer "*Org Shell Output"))
9949 (cmd path))
9950 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9951 (string-match org-confirm-shell-link-not-regexp cmd))
9952 (not org-confirm-shell-link-function)
9953 (funcall org-confirm-shell-link-function
9954 (format "Execute \"%s\" in shell? "
9955 (org-add-props cmd nil
9956 'face 'org-warning))))
9957 (progn
9958 (message "Executing %s" cmd)
9959 (shell-command cmd buf)
9960 (if (featurep 'midnight)
9961 (setq clean-buffer-list-kill-buffer-names
9962 (cons buf clean-buffer-list-kill-buffer-names))))
9963 (error "Abort"))))
9965 ((string= type "elisp")
9966 (let ((cmd path))
9967 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9968 (string-match org-confirm-elisp-link-not-regexp cmd))
9969 (not org-confirm-elisp-link-function)
9970 (funcall org-confirm-elisp-link-function
9971 (format "Execute \"%s\" as elisp? "
9972 (org-add-props cmd nil
9973 'face 'org-warning))))
9974 (message "%s => %s" cmd
9975 (if (equal (string-to-char cmd) ?\()
9976 (eval (read cmd))
9977 (call-interactively (read cmd))))
9978 (error "Abort"))))
9980 ((and (string= type "thisfile")
9981 (run-hook-with-args-until-success
9982 'org-open-link-functions path)))
9984 ((string= type "thisfile")
9985 (if arg
9986 (switch-to-buffer-other-window
9987 (org-get-buffer-for-internal-link (current-buffer)))
9988 (org-mark-ring-push))
9989 (let ((cmd `(org-link-search
9990 ,path
9991 ,(cond ((equal arg '(4)) ''occur)
9992 ((equal arg '(16)) ''org-occur))
9993 ,pos)))
9994 (condition-case nil (let ((org-link-search-inhibit-query t))
9995 (eval cmd))
9996 (error (progn (widen) (eval cmd))))))
9998 (t (browse-url-at-point)))))))
9999 (move-marker org-open-link-marker nil)
10000 (run-hook-with-args 'org-follow-link-hook)))
10002 (defun org-offer-links-in-entry (&optional nth zero)
10003 "Offer links in the current entry and follow the selected link.
10004 If there is only one link, follow it immediately as well.
10005 If NTH is an integer, immediately pick the NTH link found.
10006 If ZERO is a string, check also this string for a link, and if
10007 there is one, offer it as link number zero."
10008 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10009 "\\(" org-angle-link-re "\\)\\|"
10010 "\\(" org-plain-link-re "\\)"))
10011 (cnt ?0)
10012 (in-emacs (if (integerp nth) nil nth))
10013 have-zero end links link c)
10014 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10015 (push (match-string 0 zero) links)
10016 (setq cnt (1- cnt) have-zero t))
10017 (save-excursion
10018 (org-back-to-heading t)
10019 (setq end (save-excursion (outline-next-heading) (point)))
10020 (while (re-search-forward re end t)
10021 (push (match-string 0) links))
10022 (setq links (org-uniquify (reverse links))))
10024 (cond
10025 ((null links)
10026 (message "No links"))
10027 ((equal (length links) 1)
10028 (setq link (list (car links))))
10029 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10030 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10031 (t ; we have to select a link
10032 (save-excursion
10033 (save-window-excursion
10034 (delete-other-windows)
10035 (with-output-to-temp-buffer "*Select Link*"
10036 (mapc (lambda (l)
10037 (if (not (string-match org-bracket-link-regexp l))
10038 (princ (format "[%c] %s\n" (incf cnt)
10039 (org-remove-angle-brackets l)))
10040 (if (match-end 3)
10041 (princ (format "[%c] %s (%s)\n" (incf cnt)
10042 (match-string 3 l) (match-string 1 l)))
10043 (princ (format "[%c] %s\n" (incf cnt)
10044 (match-string 1 l))))))
10045 links))
10046 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10047 (message "Select link to open, RET to open all:")
10048 (setq c (read-char-exclusive))
10049 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10050 (when (equal c ?q) (error "Abort"))
10051 (if (equal c ?\C-m)
10052 (setq link links)
10053 (setq nth (- c ?0))
10054 (if have-zero (setq nth (1+ nth)))
10055 (unless (and (integerp nth) (>= (length links) nth))
10056 (error "Invalid link selection"))
10057 (setq link (list (nth (1- nth) links))))))
10058 (if link
10059 (let ((buf (current-buffer)))
10060 (dolist (l link)
10061 (org-open-link-from-string l in-emacs buf))
10063 nil)))
10065 ;; Add special file links that specify the way of opening
10067 (org-add-link-type "file+sys" 'org-open-file-with-system)
10068 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10069 (defun org-open-file-with-system (path)
10070 "Open file at PATH using the system way of opening it."
10071 (org-open-file path 'system))
10072 (defun org-open-file-with-emacs (path)
10073 "Open file at PATH in Emacs."
10074 (org-open-file path 'emacs))
10075 (defun org-remove-file-link-modifiers ()
10076 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10077 (goto-char (point-min))
10078 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10079 (org-if-unprotected
10080 (replace-match "file:" t t))))
10081 (eval-after-load "org-exp"
10082 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10083 'org-remove-file-link-modifiers))
10085 ;;;; Time estimates
10087 (defun org-get-effort (&optional pom)
10088 "Get the effort estimate for the current entry."
10089 (org-entry-get pom org-effort-property))
10091 ;;; File search
10093 (defvar org-create-file-search-functions nil
10094 "List of functions to construct the right search string for a file link.
10095 These functions are called in turn with point at the location to
10096 which the link should point.
10098 A function in the hook should first test if it would like to
10099 handle this file type, for example by checking the `major-mode'
10100 or the file extension. If it decides not to handle this file, it
10101 should just return nil to give other functions a chance. If it
10102 does handle the file, it must return the search string to be used
10103 when following the link. The search string will be part of the
10104 file link, given after a double colon, and `org-open-at-point'
10105 will automatically search for it. If special measures must be
10106 taken to make the search successful, another function should be
10107 added to the companion hook `org-execute-file-search-functions',
10108 which see.
10110 A function in this hook may also use `setq' to set the variable
10111 `description' to provide a suggestion for the descriptive text to
10112 be used for this link when it gets inserted into an Org-mode
10113 buffer with \\[org-insert-link].")
10115 (defvar org-execute-file-search-functions nil
10116 "List of functions to execute a file search triggered by a link.
10118 Functions added to this hook must accept a single argument, the
10119 search string that was part of the file link, the part after the
10120 double colon. The function must first check if it would like to
10121 handle this search, for example by checking the `major-mode' or
10122 the file extension. If it decides not to handle this search, it
10123 should just return nil to give other functions a chance. If it
10124 does handle the search, it must return a non-nil value to keep
10125 other functions from trying.
10127 Each function can access the current prefix argument through the
10128 variable `current-prefix-argument'. Note that a single prefix is
10129 used to force opening a link in Emacs, so it may be good to only
10130 use a numeric or double prefix to guide the search function.
10132 In case this is needed, a function in this hook can also restore
10133 the window configuration before `org-open-at-point' was called using:
10135 (set-window-configuration org-window-config-before-follow-link)")
10137 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10138 (defun org-link-search (s &optional type avoid-pos stealth)
10139 "Search for a link search option.
10140 If S is surrounded by forward slashes, it is interpreted as a
10141 regular expression. In org-mode files, this will create an `org-occur'
10142 sparse tree. In ordinary files, `occur' will be used to list matches.
10143 If the current buffer is in `dired-mode', grep will be used to search
10144 in all files. If AVOID-POS is given, ignore matches near that position.
10146 When optional argument STEALTH is non-nil, do not modify
10147 visibility around point, thus ignoring
10148 `org-show-hierarchy-above', `org-show-following-heading' and
10149 `org-show-siblings' variables."
10150 (let ((case-fold-search t)
10151 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10152 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10153 (append '(("") (" ") ("\t") ("\n"))
10154 org-emphasis-alist)
10155 "\\|") "\\)"))
10156 (pos (point))
10157 (pre nil) (post nil)
10158 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10159 (cond
10160 ;; First check if there are any special search functions
10161 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10162 ;; Now try the builtin stuff
10163 ((and (equal (string-to-char s0) ?#)
10164 (> (length s0) 1)
10165 (save-excursion
10166 (goto-char (point-min))
10167 (and
10168 (re-search-forward
10169 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10170 (setq type 'dedicated
10171 pos (match-beginning 0))))
10172 ;; There is an exact target for this
10173 (goto-char pos)
10174 (org-back-to-heading t)))
10175 ((save-excursion
10176 (goto-char (point-min))
10177 (and
10178 (re-search-forward
10179 (concat "<<" (regexp-quote s0) ">>") nil t)
10180 (setq type 'dedicated
10181 pos (match-beginning 0))))
10182 ;; There is an exact target for this
10183 (goto-char pos))
10184 ((save-excursion
10185 (goto-char (point-min))
10186 (and
10187 (re-search-forward
10188 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10189 (setq type 'dedicated pos (match-beginning 0))))
10190 ;; Found an invisible target.
10191 (goto-char pos))
10192 ((save-excursion
10193 (goto-char (point-min))
10194 (and
10195 (re-search-forward
10196 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10197 (setq type 'dedicated pos (match-beginning 0))))
10198 ;; Found an element with a matching #+name affiliated keyword.
10199 (goto-char pos))
10200 ((and (string-match "^(\\(.*\\))$" s0)
10201 (save-excursion
10202 (goto-char (point-min))
10203 (and
10204 (re-search-forward
10205 (concat "[^[]" (regexp-quote
10206 (format org-coderef-label-format
10207 (match-string 1 s0))))
10208 nil t)
10209 (setq type 'dedicated
10210 pos (1+ (match-beginning 0))))))
10211 ;; There is a coderef target for this
10212 (goto-char pos))
10213 ((string-match "^/\\(.*\\)/$" s)
10214 ;; A regular expression
10215 (cond
10216 ((derived-mode-p 'org-mode)
10217 (org-occur (match-string 1 s)))
10218 ;;((eq major-mode 'dired-mode)
10219 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10220 (t (org-do-occur (match-string 1 s)))))
10221 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10222 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10223 (goto-char (point-min))
10224 (cond
10225 ((let (case-fold-search)
10226 (re-search-forward (format org-complex-heading-regexp-format
10227 (regexp-quote s))
10228 nil t))
10229 ;; OK, found a match
10230 (setq type 'dedicated)
10231 (goto-char (match-beginning 0)))
10232 ((and (not org-link-search-inhibit-query)
10233 (eq org-link-search-must-match-exact-headline 'query-to-create)
10234 (y-or-n-p "No match - create this as a new heading? "))
10235 (goto-char (point-max))
10236 (or (bolp) (newline))
10237 (insert "* " s "\n")
10238 (beginning-of-line 0))
10240 (goto-char pos)
10241 (error "No match"))))
10243 ;; A normal search string
10244 (when (equal (string-to-char s) ?*)
10245 ;; Anchor on headlines, post may include tags.
10246 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10247 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10248 s (substring s 1)))
10249 (remove-text-properties
10250 0 (length s)
10251 '(face nil mouse-face nil keymap nil fontified nil) s)
10252 ;; Make a series of regular expressions to find a match
10253 (setq words (org-split-string s "[ \n\r\t]+")
10255 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10256 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10257 "\\)" markers)
10258 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10259 re2a (concat "[ \t\r\n]" re2a_)
10260 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10261 re4 (concat "[^a-zA-Z_]" re4_)
10263 re1 (concat pre re2 post)
10264 re3 (concat pre (if pre re4_ re4) post)
10265 re5 (concat pre ".*" re4)
10266 re2 (concat pre re2)
10267 re2a (concat pre (if pre re2a_ re2a))
10268 re4 (concat pre (if pre re4_ re4))
10269 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10270 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10271 re5 "\\)"
10273 (cond
10274 ((eq type 'org-occur) (org-occur reall))
10275 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10276 (t (goto-char (point-min))
10277 (setq type 'fuzzy)
10278 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10279 (org-search-not-self 1 re1 nil t)
10280 (org-search-not-self 1 re2 nil t)
10281 (org-search-not-self 1 re2a nil t)
10282 (org-search-not-self 1 re3 nil t)
10283 (org-search-not-self 1 re4 nil t)
10284 (org-search-not-self 1 re5 nil t)
10286 (goto-char (match-beginning 1))
10287 (goto-char pos)
10288 (error "No match"))))))
10289 (and (derived-mode-p 'org-mode)
10290 (not stealth)
10291 (org-show-context 'link-search))
10292 type))
10294 (defun org-search-not-self (group &rest args)
10295 "Execute `re-search-forward', but only accept matches that do not
10296 enclose the position of `org-open-link-marker'."
10297 (let ((m org-open-link-marker))
10298 (catch 'exit
10299 (while (apply 're-search-forward args)
10300 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10301 (goto-char (match-end group))
10302 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10303 (> (match-beginning 0) (marker-position m))
10304 (< (match-end 0) (marker-position m)))
10305 (save-match-data
10306 (or (not (org-in-regexp
10307 org-bracket-link-analytic-regexp 1))
10308 (not (match-end 4)) ; no description
10309 (and (<= (match-beginning 4) (point))
10310 (>= (match-end 4) (point))))))
10311 (throw 'exit (point))))))))
10313 (defun org-get-buffer-for-internal-link (buffer)
10314 "Return a buffer to be used for displaying the link target of internal links."
10315 (cond
10316 ((not org-display-internal-link-with-indirect-buffer)
10317 buffer)
10318 ((string-match "(Clone)$" (buffer-name buffer))
10319 (message "Buffer is already a clone, not making another one")
10320 ;; we also do not modify visibility in this case
10321 buffer)
10322 (t ; make a new indirect buffer for displaying the link
10323 (let* ((bn (buffer-name buffer))
10324 (ibn (concat bn "(Clone)"))
10325 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10326 (with-current-buffer ib (org-overview))
10327 ib))))
10329 (defun org-do-occur (regexp &optional cleanup)
10330 "Call the Emacs command `occur'.
10331 If CLEANUP is non-nil, remove the printout of the regular expression
10332 in the *Occur* buffer. This is useful if the regex is long and not useful
10333 to read."
10334 (occur regexp)
10335 (when cleanup
10336 (let ((cwin (selected-window)) win beg end)
10337 (when (setq win (get-buffer-window "*Occur*"))
10338 (select-window win))
10339 (goto-char (point-min))
10340 (when (re-search-forward "match[a-z]+" nil t)
10341 (setq beg (match-end 0))
10342 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10343 (setq end (1- (match-beginning 0)))))
10344 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10345 (goto-char (point-min))
10346 (select-window cwin))))
10348 ;;; The mark ring for links jumps
10350 (defvar org-mark-ring nil
10351 "Mark ring for positions before jumps in Org-mode.")
10352 (defvar org-mark-ring-last-goto nil
10353 "Last position in the mark ring used to go back.")
10354 ;; Fill and close the ring
10355 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10356 (loop for i from 1 to org-mark-ring-length do
10357 (push (make-marker) org-mark-ring))
10358 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10359 org-mark-ring)
10361 (defun org-mark-ring-push (&optional pos buffer)
10362 "Put the current position or POS into the mark ring and rotate it."
10363 (interactive)
10364 (setq pos (or pos (point)))
10365 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10366 (move-marker (car org-mark-ring)
10367 (or pos (point))
10368 (or buffer (current-buffer)))
10369 (message "%s"
10370 (substitute-command-keys
10371 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10373 (defun org-mark-ring-goto (&optional n)
10374 "Jump to the previous position in the mark ring.
10375 With prefix arg N, jump back that many stored positions. When
10376 called several times in succession, walk through the entire ring.
10377 Org-mode commands jumping to a different position in the current file,
10378 or to another Org-mode file, automatically push the old position
10379 onto the ring."
10380 (interactive "p")
10381 (let (p m)
10382 (if (eq last-command this-command)
10383 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10384 (setq p org-mark-ring))
10385 (setq org-mark-ring-last-goto p)
10386 (setq m (car p))
10387 (org-pop-to-buffer-same-window (marker-buffer m))
10388 (goto-char m)
10389 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10391 (defun org-remove-angle-brackets (s)
10392 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10393 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10395 (defun org-add-angle-brackets (s)
10396 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10397 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10399 (defun org-remove-double-quotes (s)
10400 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10401 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10404 ;;; Following specific links
10406 (defun org-follow-timestamp-link ()
10407 (cond
10408 ((org-at-date-range-p t)
10409 (let ((org-agenda-start-on-weekday)
10410 (t1 (match-string 1))
10411 (t2 (match-string 2)))
10412 (setq t1 (time-to-days (org-time-string-to-time t1))
10413 t2 (time-to-days (org-time-string-to-time t2)))
10414 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10415 ((org-at-timestamp-p t)
10416 (org-agenda-list nil (time-to-days (org-time-string-to-time
10417 (substring (match-string 1) 0 10)))
10419 (t (error "This should not happen"))))
10422 ;;; Following file links
10423 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10424 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10425 (declare-function mailcap-mime-info
10426 "mailcap" (string &optional request no-decode))
10427 (defvar org-wait nil)
10428 (defun org-open-file (path &optional in-emacs line search)
10429 "Open the file at PATH.
10430 First, this expands any special file name abbreviations. Then the
10431 configuration variable `org-file-apps' is checked if it contains an
10432 entry for this file type, and if yes, the corresponding command is launched.
10434 If no application is found, Emacs simply visits the file.
10436 With optional prefix argument IN-EMACS, Emacs will visit the file.
10437 With a double \\[universal-argument] \\[universal-argument] \
10438 prefix arg, Org tries to avoid opening in Emacs
10439 and to use an external application to visit the file.
10441 Optional LINE specifies a line to go to, optional SEARCH a string
10442 to search for. If LINE or SEARCH is given, the file will be
10443 opened in Emacs, unless an entry from org-file-apps that makes
10444 use of groups in a regexp matches.
10446 If you want to change the way frames are used when following a
10447 link, please customize `org-link-frame-setup'.
10449 If the file does not exist, an error is thrown."
10450 (let* ((file (if (equal path "")
10451 buffer-file-name
10452 (substitute-in-file-name (expand-file-name path))))
10453 (file-apps (append org-file-apps (org-default-apps)))
10454 (apps (org-remove-if
10455 'org-file-apps-entry-match-against-dlink-p file-apps))
10456 (apps-dlink (org-remove-if-not
10457 'org-file-apps-entry-match-against-dlink-p file-apps))
10458 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10459 (dirp (if remp nil (file-directory-p file)))
10460 (file (if (and dirp org-open-directory-means-index-dot-org)
10461 (concat (file-name-as-directory file) "index.org")
10462 file))
10463 (a-m-a-p (assq 'auto-mode apps))
10464 (dfile (downcase file))
10465 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10466 (link (cond ((and (eq line nil)
10467 (eq search nil))
10468 file)
10469 (line
10470 (concat file "::" (number-to-string line)))
10471 (search
10472 (concat file "::" search))))
10473 (dlink (downcase link))
10474 (old-buffer (current-buffer))
10475 (old-pos (point))
10476 (old-mode major-mode)
10477 ext cmd link-match-data)
10478 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10479 (setq ext (match-string 1 dfile))
10480 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10481 (setq ext (match-string 1 dfile))))
10482 (cond
10483 ((member in-emacs '((16) system))
10484 (setq cmd (cdr (assoc 'system apps))))
10485 (in-emacs (setq cmd 'emacs))
10487 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10488 (and dirp (cdr (assoc 'directory apps)))
10489 ; first, try matching against apps-dlink
10490 ; if we get a match here, store the match data for later
10491 (let ((match (assoc-default dlink apps-dlink
10492 'string-match)))
10493 (if match
10494 (progn (setq link-match-data (match-data))
10495 match)
10496 (progn (setq in-emacs (or in-emacs line search))
10497 nil))) ; if we have no match in apps-dlink,
10498 ; always open the file in emacs if line or search
10499 ; is given (for backwards compatibility)
10500 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10501 'string-match)
10502 (cdr (assoc ext apps))
10503 (cdr (assoc t apps))))))
10504 (when (eq cmd 'system)
10505 (setq cmd (cdr (assoc 'system apps))))
10506 (when (eq cmd 'default)
10507 (setq cmd (cdr (assoc t apps))))
10508 (when (eq cmd 'mailcap)
10509 (require 'mailcap)
10510 (mailcap-parse-mailcaps)
10511 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10512 (command (mailcap-mime-info mime-type)))
10513 (if (stringp command)
10514 (setq cmd command)
10515 (setq cmd 'emacs))))
10516 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10517 (not (file-exists-p file))
10518 (not org-open-non-existing-files))
10519 (error "No such file: %s" file))
10520 (cond
10521 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10522 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10523 (while (string-match "['\"]%s['\"]" cmd)
10524 (setq cmd (replace-match "%s" t t cmd)))
10525 (while (string-match "%s" cmd)
10526 (setq cmd (replace-match
10527 (save-match-data
10528 (shell-quote-argument
10529 (convert-standard-filename file)))
10530 t t cmd)))
10532 ;; Replace "%1", "%2" etc. in command with group matches from regex
10533 (save-match-data
10534 (let ((match-index 1)
10535 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10536 (set-match-data link-match-data)
10537 (while (<= match-index number-of-groups)
10538 (let ((regex (concat "%" (number-to-string match-index)))
10539 (replace-with (match-string match-index dlink)))
10540 (while (string-match regex cmd)
10541 (setq cmd (replace-match replace-with t t cmd))))
10542 (setq match-index (+ match-index 1)))))
10544 (save-window-excursion
10545 (start-process-shell-command cmd nil cmd)
10546 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10548 ((or (stringp cmd)
10549 (eq cmd 'emacs))
10550 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10551 (widen)
10552 (if line (org-goto-line line)
10553 (if search (org-link-search search))))
10554 ((consp cmd)
10555 (let ((file (convert-standard-filename file)))
10556 (save-match-data
10557 (set-match-data link-match-data)
10558 (eval cmd))))
10559 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10560 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10561 (or (not (equal old-buffer (current-buffer)))
10562 (not (equal old-pos (point))))
10563 (org-mark-ring-push old-pos old-buffer))))
10565 (defun org-file-apps-entry-match-against-dlink-p (entry)
10566 "This function returns non-nil if `entry' uses a regular
10567 expression which should be matched against the whole link by
10568 org-open-file.
10570 It assumes that is the case when the entry uses a regular
10571 expression which has at least one grouping construct and the
10572 action is either a lisp form or a command string containing
10573 '%1', i.e. using at least one subexpression match as a
10574 parameter."
10575 (let ((selector (car entry))
10576 (action (cdr entry)))
10577 (if (stringp selector)
10578 (and (> (regexp-opt-depth selector) 0)
10579 (or (and (stringp action)
10580 (string-match "%[0-9]" action))
10581 (consp action)))
10582 nil)))
10584 (defun org-default-apps ()
10585 "Return the default applications for this operating system."
10586 (cond
10587 ((eq system-type 'darwin)
10588 org-file-apps-defaults-macosx)
10589 ((eq system-type 'windows-nt)
10590 org-file-apps-defaults-windowsnt)
10591 (t org-file-apps-defaults-gnu)))
10593 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10594 "Convert extensions to regular expressions in the cars of LIST.
10595 Also, weed out any non-string entries, because the return value is used
10596 only for regexp matching.
10597 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10598 point to the symbol `emacs', indicating that the file should
10599 be opened in Emacs."
10600 (append
10601 (delq nil
10602 (mapcar (lambda (x)
10603 (if (not (stringp (car x)))
10605 (if (string-match "\\W" (car x))
10607 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10608 list))
10609 (if add-auto-mode
10610 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10612 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10613 (defun org-file-remote-p (file)
10614 "Test whether FILE specifies a location on a remote system.
10615 Return non-nil if the location is indeed remote.
10617 For example, the filename \"/user@host:/foo\" specifies a location
10618 on the system \"/user@host:\"."
10619 (cond ((fboundp 'file-remote-p)
10620 (file-remote-p file))
10621 ((fboundp 'tramp-handle-file-remote-p)
10622 (tramp-handle-file-remote-p file))
10623 ((and (boundp 'ange-ftp-name-format)
10624 (string-match (car ange-ftp-name-format) file))
10625 t)))
10628 ;;;; Refiling
10630 (defun org-get-org-file ()
10631 "Read a filename, with default directory `org-directory'."
10632 (let ((default (or org-default-notes-file remember-data-file)))
10633 (read-file-name (format "File name [%s]: " default)
10634 (file-name-as-directory org-directory)
10635 default)))
10637 (defun org-notes-order-reversed-p ()
10638 "Check if the current file should receive notes in reversed order."
10639 (cond
10640 ((not org-reverse-note-order) nil)
10641 ((eq t org-reverse-note-order) t)
10642 ((not (listp org-reverse-note-order)) nil)
10643 (t (catch 'exit
10644 (let ((all org-reverse-note-order)
10645 entry)
10646 (while (setq entry (pop all))
10647 (if (string-match (car entry) buffer-file-name)
10648 (throw 'exit (cdr entry))))
10649 nil)))))
10651 (defvar org-refile-target-table nil
10652 "The list of refile targets, created by `org-refile'.")
10654 (defvar org-agenda-new-buffers nil
10655 "Buffers created to visit agenda files.")
10657 (defvar org-refile-cache nil
10658 "Cache for refile targets.")
10660 (defvar org-refile-markers nil
10661 "All the markers used for caching refile locations.")
10663 (defun org-refile-marker (pos)
10664 "Get a new refile marker, but only if caching is in use."
10665 (if (not org-refile-use-cache)
10667 (let ((m (make-marker)))
10668 (move-marker m pos)
10669 (push m org-refile-markers)
10670 m)))
10672 (defun org-refile-cache-clear ()
10673 "Clear the refile cache and disable all the markers."
10674 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10675 (setq org-refile-markers nil)
10676 (setq org-refile-cache nil)
10677 (message "Refile cache has been cleared"))
10679 (defun org-refile-cache-check-set (set)
10680 "Check if all the markers in the cache still have live buffers."
10681 (let (marker)
10682 (catch 'exit
10683 (while (and set (setq marker (nth 3 (pop set))))
10684 ;; if org-refile-use-outline-path is 'file, marker may be nil
10685 (when (and marker (null (marker-buffer marker)))
10686 (message "not found") (sit-for 3)
10687 (throw 'exit nil)))
10688 t)))
10690 (defun org-refile-cache-put (set &rest identifiers)
10691 "Push the refile targets SET into the cache, under IDENTIFIERS."
10692 (let* ((key (sha1 (prin1-to-string identifiers)))
10693 (entry (assoc key org-refile-cache)))
10694 (if entry
10695 (setcdr entry set)
10696 (push (cons key set) org-refile-cache))))
10698 (defun org-refile-cache-get (&rest identifiers)
10699 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10700 (cond
10701 ((not org-refile-cache) nil)
10702 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10704 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10705 org-refile-cache))))
10706 (and set (org-refile-cache-check-set set) set)))))
10708 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10709 "Produce a table with refile targets."
10710 (let ((case-fold-search nil)
10711 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10712 (entries (or org-refile-targets '((nil . (:level . 1)))))
10713 targets tgs txt re files f desc descre fast-path-p level pos0)
10714 (message "Getting targets...")
10715 (with-current-buffer (or default-buffer (current-buffer))
10716 (while (setq entry (pop entries))
10717 (setq files (car entry) desc (cdr entry))
10718 (setq fast-path-p nil)
10719 (cond
10720 ((null files) (setq files (list (current-buffer))))
10721 ((eq files 'org-agenda-files)
10722 (setq files (org-agenda-files 'unrestricted)))
10723 ((and (symbolp files) (fboundp files))
10724 (setq files (funcall files)))
10725 ((and (symbolp files) (boundp files))
10726 (setq files (symbol-value files))))
10727 (if (stringp files) (setq files (list files)))
10728 (cond
10729 ((eq (car desc) :tag)
10730 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10731 ((eq (car desc) :todo)
10732 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10733 ((eq (car desc) :regexp)
10734 (setq descre (cdr desc)))
10735 ((eq (car desc) :level)
10736 (setq descre (concat "^\\*\\{" (number-to-string
10737 (if org-odd-levels-only
10738 (1- (* 2 (cdr desc)))
10739 (cdr desc)))
10740 "\\}[ \t]")))
10741 ((eq (car desc) :maxlevel)
10742 (setq fast-path-p t)
10743 (setq descre (concat "^\\*\\{1," (number-to-string
10744 (if org-odd-levels-only
10745 (1- (* 2 (cdr desc)))
10746 (cdr desc)))
10747 "\\}[ \t]")))
10748 (t (error "Bad refiling target description %s" desc)))
10749 (while (setq f (pop files))
10750 (with-current-buffer
10751 (if (bufferp f) f (org-get-agenda-file-buffer f))
10753 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10754 (progn
10755 (if (bufferp f) (setq f (buffer-file-name
10756 (buffer-base-buffer f))))
10757 (setq f (and f (expand-file-name f)))
10758 (if (eq org-refile-use-outline-path 'file)
10759 (push (list (file-name-nondirectory f) f nil nil) tgs))
10760 (save-excursion
10761 (save-restriction
10762 (widen)
10763 (goto-char (point-min))
10764 (while (re-search-forward descre nil t)
10765 (goto-char (setq pos0 (point-at-bol)))
10766 (catch 'next
10767 (when org-refile-target-verify-function
10768 (save-match-data
10769 (or (funcall org-refile-target-verify-function)
10770 (throw 'next t))))
10771 (when (and (looking-at org-complex-heading-regexp)
10772 (not (member (match-string 4) excluded-entries))
10773 (match-string 4))
10774 (setq level (org-reduced-level
10775 (- (match-end 1) (match-beginning 1)))
10776 txt (org-link-display-format (match-string 4))
10777 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10778 re (format org-complex-heading-regexp-format
10779 (regexp-quote (match-string 4))))
10780 (when org-refile-use-outline-path
10781 (setq txt (mapconcat
10782 'org-protect-slash
10783 (append
10784 (if (eq org-refile-use-outline-path
10785 'file)
10786 (list (file-name-nondirectory
10787 (buffer-file-name
10788 (buffer-base-buffer))))
10789 (if (eq org-refile-use-outline-path
10790 'full-file-path)
10791 (list (buffer-file-name
10792 (buffer-base-buffer)))))
10793 (org-get-outline-path fast-path-p
10794 level txt)
10795 (list txt))
10796 "/")))
10797 (push (list txt f re (org-refile-marker (point)))
10798 tgs)))
10799 (when (= (point) pos0)
10800 ;; verification function has not moved point
10801 (goto-char (point-at-eol))))))))
10802 (when org-refile-use-cache
10803 (org-refile-cache-put tgs (buffer-file-name) descre))
10804 (setq targets (append tgs targets))
10805 ))))
10806 (message "Getting targets...done")
10807 (nreverse targets)))
10809 (defun org-protect-slash (s)
10810 (while (string-match "/" s)
10811 (setq s (replace-match "\\" t t s)))
10814 (defvar org-olpa (make-vector 20 nil))
10816 (defun org-get-outline-path (&optional fastp level heading)
10817 "Return the outline path to the current entry, as a list.
10819 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10820 routine which makes outline path derivations for an entire file,
10821 avoiding backtracing. Refile target collection makes use of that."
10822 (if fastp
10823 (progn
10824 (if (> level 19)
10825 (error "Outline path failure, more than 19 levels"))
10826 (loop for i from level upto 19 do
10827 (aset org-olpa i nil))
10828 (prog1
10829 (delq nil (append org-olpa nil))
10830 (aset org-olpa level heading)))
10831 (let (rtn case-fold-search)
10832 (save-excursion
10833 (save-restriction
10834 (widen)
10835 (while (org-up-heading-safe)
10836 (when (looking-at org-complex-heading-regexp)
10837 (push (org-match-string-no-properties 4) rtn)))
10838 rtn)))))
10840 (defun org-format-outline-path (path &optional width prefix)
10841 "Format the outline path PATH for display.
10842 Width is the maximum number of characters that is available.
10843 Prefix is a prefix to be included in the returned string,
10844 such as the file name."
10845 (setq width (or width 79))
10846 (if prefix (setq width (- width (length prefix))))
10847 (if (not path)
10848 (or prefix "")
10849 (let* ((nsteps (length path))
10850 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10851 (maxwidth (if (<= total-width width)
10852 10000 ;; everything fits
10853 ;; we need to shorten the level headings
10854 (/ (- width nsteps) nsteps)))
10855 (org-odd-levels-only nil)
10856 (n 0)
10857 (total (1+ (length prefix))))
10858 (setq maxwidth (max maxwidth 10))
10859 (concat prefix
10860 (mapconcat
10861 (lambda (h)
10862 (setq n (1+ n))
10863 (if (and (= n nsteps) (< maxwidth 10000))
10864 (setq maxwidth (- total-width total)))
10865 (if (< (length h) maxwidth)
10866 (progn (setq total (+ total (length h) 1)) h)
10867 (setq h (substring h 0 (- maxwidth 2))
10868 total (+ total maxwidth 1))
10869 (if (string-match "[ \t]+\\'" h)
10870 (setq h (substring h 0 (match-beginning 0))))
10871 (setq h (concat h "..")))
10872 (org-add-props h nil 'face
10873 (nth (% (1- n) org-n-level-faces)
10874 org-level-faces))
10876 path "/")))))
10878 (defun org-display-outline-path (&optional file current)
10879 "Display the current outline path in the echo area."
10880 (interactive "P")
10881 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10882 (case-fold-search nil)
10883 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10884 (if current (setq path (append path
10885 (save-excursion
10886 (org-back-to-heading t)
10887 (if (looking-at org-complex-heading-regexp)
10888 (list (match-string 4)))))))
10889 (message "%s"
10890 (org-format-outline-path
10891 path
10892 (1- (frame-width))
10893 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10895 (defvar org-refile-history nil
10896 "History for refiling operations.")
10898 (defvar org-after-refile-insert-hook nil
10899 "Hook run after `org-refile' has inserted its stuff at the new location.
10900 Note that this is still *before* the stuff will be removed from
10901 the *old* location.")
10903 (defvar org-capture-last-stored-marker)
10904 (defun org-refile (&optional goto default-buffer rfloc)
10905 "Move the entry or entries at point to another heading.
10906 The list of target headings is compiled using the information in
10907 `org-refile-targets', which see.
10909 At the target location, the entry is filed as a subitem of the target
10910 heading. Depending on `org-reverse-note-order', the new subitem will
10911 either be the first or the last subitem.
10913 If there is an active region, all entries in that region will be moved.
10914 However, the region must fulfill the requirement that the first heading
10915 is the first one sets the top-level of the moved text - at most siblings
10916 below it are allowed.
10918 With prefix arg GOTO, the command will only visit the target location
10919 and not actually move anything.
10921 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10922 go to the location where the last refiling operation has put the subtree.
10923 With a prefix argument of `2', refile to the running clock.
10925 RFLOC can be a refile location obtained in a different way.
10927 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10929 If you are using target caching (see `org-refile-use-cache'),
10930 you have to clear the target cache in order to find new targets.
10931 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10932 prefix argument (`C-u C-u C-u C-c C-w')."
10934 (interactive "P")
10935 (if (member goto '(0 (64)))
10936 (org-refile-cache-clear)
10937 (let* ((cbuf (current-buffer))
10938 (regionp (org-region-active-p))
10939 (region-start (and regionp (region-beginning)))
10940 (region-end (and regionp (region-end)))
10941 (region-length (and regionp (- region-end region-start)))
10942 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10943 pos it nbuf file re level reversed)
10944 (setq last-command nil)
10945 (when regionp
10946 (goto-char region-start)
10947 (or (bolp) (goto-char (point-at-bol)))
10948 (setq region-start (point))
10949 (unless (or (org-kill-is-subtree-p
10950 (buffer-substring region-start region-end))
10951 (prog1 org-refile-active-region-within-subtree
10952 (org-toggle-heading)))
10953 (error "The region is not a (sequence of) subtree(s)")))
10954 (if (equal goto '(16))
10955 (org-refile-goto-last-stored)
10956 (when (or
10957 (and (equal goto 2)
10958 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10959 (prog1
10960 (setq it (list (or org-clock-heading "running clock")
10961 (buffer-file-name
10962 (marker-buffer org-clock-hd-marker))
10964 (marker-position org-clock-hd-marker)))
10965 (setq goto nil)))
10966 (setq it (or rfloc
10967 (let (heading-text)
10968 (save-excursion
10969 (unless goto
10970 (org-back-to-heading t)
10971 (setq heading-text
10972 (nth 4 (org-heading-components))))
10973 (org-refile-get-location
10974 (cond (goto "Goto")
10975 (regionp "Refile region to")
10976 (t (concat "Refile subtree \""
10977 heading-text "\" to")))
10978 default-buffer
10979 (and (not (equal '(4) goto))
10980 org-refile-allow-creating-parent-nodes)
10981 goto))))))
10982 (setq file (nth 1 it)
10983 re (nth 2 it)
10984 pos (nth 3 it))
10985 (if (and (not goto)
10987 (equal (buffer-file-name) file)
10988 (if regionp
10989 (and (>= pos region-start)
10990 (<= pos region-end))
10991 (and (>= pos (point))
10992 (< pos (save-excursion
10993 (org-end-of-subtree t t))))))
10994 (error "Cannot refile to position inside the tree or region"))
10996 (setq nbuf (or (find-buffer-visiting file)
10997 (find-file-noselect file)))
10998 (if goto
10999 (progn
11000 (org-pop-to-buffer-same-window nbuf)
11001 (goto-char pos)
11002 (org-show-context 'org-goto))
11003 (if regionp
11004 (progn
11005 (org-kill-new (buffer-substring region-start region-end))
11006 (org-save-markers-in-region region-start region-end))
11007 (org-copy-subtree 1 nil t))
11008 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11009 (find-file-noselect file)))
11010 (setq reversed (org-notes-order-reversed-p))
11011 (save-excursion
11012 (save-restriction
11013 (widen)
11014 (if pos
11015 (progn
11016 (goto-char pos)
11017 (looking-at org-outline-regexp)
11018 (setq level (org-get-valid-level (funcall outline-level) 1))
11019 (goto-char
11020 (if reversed
11021 (or (outline-next-heading) (point-max))
11022 (or (save-excursion (org-get-next-sibling))
11023 (org-end-of-subtree t t)
11024 (point-max)))))
11025 (setq level 1)
11026 (if (not reversed)
11027 (goto-char (point-max))
11028 (goto-char (point-min))
11029 (or (outline-next-heading) (goto-char (point-max)))))
11030 (if (not (bolp)) (newline))
11031 (org-paste-subtree level)
11032 (when org-log-refile
11033 (org-add-log-setup 'refile nil nil 'findpos
11034 org-log-refile)
11035 (unless (eq org-log-refile 'note)
11036 (save-excursion (org-add-log-note))))
11037 (and org-auto-align-tags
11038 (let ((org-loop-over-headlines-in-active-region nil))
11039 (org-set-tags nil t)))
11040 (bookmark-set "org-refile-last-stored")
11041 ;; If we are refiling for capture, make sure that the
11042 ;; last-capture pointers point here
11043 (when (org-bound-and-true-p org-refile-for-capture)
11044 (bookmark-set "org-capture-last-stored-marker")
11045 (move-marker org-capture-last-stored-marker (point)))
11046 (if (fboundp 'deactivate-mark) (deactivate-mark))
11047 (run-hooks 'org-after-refile-insert-hook))))
11048 (if regionp
11049 (delete-region (point) (+ (point) region-length))
11050 (org-cut-subtree))
11051 (when (featurep 'org-inlinetask)
11052 (org-inlinetask-remove-END-maybe))
11053 (setq org-markers-to-move nil)
11054 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11056 (defun org-refile-goto-last-stored ()
11057 "Go to the location where the last refile was stored."
11058 (interactive)
11059 (bookmark-jump "org-refile-last-stored")
11060 (message "This is the location of the last refile"))
11062 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11063 no-exclude)
11064 "Prompt the user for a refile location, using PROMPT.
11065 PROMPT should not be suffixed with a colon and a space, because
11066 this function appends the default value from
11067 `org-refile-history' automatically, if that is not empty.
11068 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11069 this is used for the GOTO interface."
11070 (let ((org-refile-targets org-refile-targets)
11071 (org-refile-use-outline-path org-refile-use-outline-path)
11072 excluded-entries)
11073 (when (and (derived-mode-p 'org-mode)
11074 (not org-refile-use-cache)
11075 (not no-exclude))
11076 (org-map-tree
11077 (lambda()
11078 (setq excluded-entries
11079 (append excluded-entries (list (org-get-heading t t)))))))
11080 (setq org-refile-target-table
11081 (org-refile-get-targets default-buffer excluded-entries)))
11082 (unless org-refile-target-table
11083 (error "No refile targets"))
11084 (let* ((prompt (concat prompt
11085 (and (car org-refile-history)
11086 (concat " (default " (car org-refile-history) ")"))
11087 ": "))
11088 (cbuf (current-buffer))
11089 (partial-completion-mode nil)
11090 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11091 (cfunc (if (and org-refile-use-outline-path
11092 org-outline-path-complete-in-steps)
11093 'org-olpath-completing-read
11094 'org-icompleting-read))
11095 (extra (if org-refile-use-outline-path "/" ""))
11096 (filename (and cfn (expand-file-name cfn)))
11097 (tbl (mapcar
11098 (lambda (x)
11099 (if (and (not (member org-refile-use-outline-path
11100 '(file full-file-path)))
11101 (not (equal filename (nth 1 x))))
11102 (cons (concat (car x) extra " ("
11103 (file-name-nondirectory (nth 1 x)) ")")
11104 (cdr x))
11105 (cons (concat (car x) extra) (cdr x))))
11106 org-refile-target-table))
11107 (completion-ignore-case t)
11108 pa answ parent-target child parent old-hist)
11109 (setq old-hist org-refile-history)
11110 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11111 nil 'org-refile-history (car org-refile-history)))
11112 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11113 (org-refile-check-position pa)
11114 (if pa
11115 (progn
11116 (when (or (not org-refile-history)
11117 (not (eq old-hist org-refile-history))
11118 (not (equal (car pa) (car org-refile-history))))
11119 (setq org-refile-history
11120 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11121 org-refile-history
11122 (cdr org-refile-history))))
11123 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11124 (pop org-refile-history)))
11126 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11127 (progn
11128 (setq parent (match-string 1 answ)
11129 child (match-string 2 answ))
11130 (setq parent-target (or (assoc parent tbl)
11131 (assoc (concat parent "/") tbl)))
11132 (when (and parent-target
11133 (or (eq new-nodes t)
11134 (and (eq new-nodes 'confirm)
11135 (y-or-n-p (format "Create new node \"%s\"? "
11136 child)))))
11137 (org-refile-new-child parent-target child)))
11138 (error "Invalid target location")))))
11140 (declare-function org-string-nw-p "org-macs.el" (s))
11141 (defun org-refile-check-position (refile-pointer)
11142 "Check if the refile pointer matches the readline to which it points."
11143 (let* ((file (nth 1 refile-pointer))
11144 (re (nth 2 refile-pointer))
11145 (pos (nth 3 refile-pointer))
11146 buffer)
11147 (when (org-string-nw-p re)
11148 (setq buffer (if (markerp pos)
11149 (marker-buffer pos)
11150 (or (find-buffer-visiting file)
11151 (find-file-noselect file))))
11152 (with-current-buffer buffer
11153 (save-excursion
11154 (save-restriction
11155 (widen)
11156 (goto-char pos)
11157 (beginning-of-line 1)
11158 (unless (org-looking-at-p re)
11159 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11161 (defun org-refile-new-child (parent-target child)
11162 "Use refile target PARENT-TARGET to add new CHILD below it."
11163 (unless parent-target
11164 (error "Cannot find parent for new node"))
11165 (let ((file (nth 1 parent-target))
11166 (pos (nth 3 parent-target))
11167 level)
11168 (with-current-buffer (or (find-buffer-visiting file)
11169 (find-file-noselect file))
11170 (save-excursion
11171 (save-restriction
11172 (widen)
11173 (if pos
11174 (goto-char pos)
11175 (goto-char (point-max))
11176 (if (not (bolp)) (newline)))
11177 (when (looking-at org-outline-regexp)
11178 (setq level (funcall outline-level))
11179 (org-end-of-subtree t t))
11180 (org-back-over-empty-lines)
11181 (insert "\n" (make-string
11182 (if pos (org-get-valid-level level 1) 1) ?*)
11183 " " child "\n")
11184 (beginning-of-line 0)
11185 (list (concat (car parent-target) "/" child) file "" (point)))))))
11187 (defun org-olpath-completing-read (prompt collection &rest args)
11188 "Read an outline path like a file name."
11189 (let ((thetable collection)
11190 (org-completion-use-ido nil) ; does not work with ido.
11191 (org-completion-use-iswitchb nil)) ; or iswitchb
11192 (apply
11193 'org-icompleting-read prompt
11194 (lambda (string predicate &optional flag)
11195 (let (rtn r f (l (length string)))
11196 (cond
11197 ((eq flag nil)
11198 ;; try completion
11199 (try-completion string thetable))
11200 ((eq flag t)
11201 ;; all-completions
11202 (setq rtn (all-completions string thetable predicate))
11203 (mapcar
11204 (lambda (x)
11205 (setq r (substring x l))
11206 (if (string-match " ([^)]*)$" x)
11207 (setq f (match-string 0 x))
11208 (setq f ""))
11209 (if (string-match "/" r)
11210 (concat string (substring r 0 (match-end 0)) f)
11212 rtn))
11213 ((eq flag 'lambda)
11214 ;; exact match?
11215 (assoc string thetable)))))
11216 args)))
11218 ;;;; Dynamic blocks
11220 (defun org-find-dblock (name)
11221 "Find the first dynamic block with name NAME in the buffer.
11222 If not found, stay at current position and return nil."
11223 (let ((case-fold-search t) pos)
11224 (save-excursion
11225 (goto-char (point-min))
11226 (setq pos (and (re-search-forward
11227 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11228 (match-beginning 0))))
11229 (if pos (goto-char pos))
11230 pos))
11232 (defconst org-dblock-start-re
11233 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11234 "Matches the start line of a dynamic block, with parameters.")
11236 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11237 "Matches the end of a dynamic block.")
11239 (defun org-create-dblock (plist)
11240 "Create a dynamic block section, with parameters taken from PLIST.
11241 PLIST must contain a :name entry which is used as name of the block."
11242 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11243 (end-of-line 1)
11244 (newline))
11245 (let ((col (current-column))
11246 (name (plist-get plist :name)))
11247 (insert "#+BEGIN: " name)
11248 (while plist
11249 (if (eq (car plist) :name)
11250 (setq plist (cddr plist))
11251 (insert " " (prin1-to-string (pop plist)))))
11252 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11253 (beginning-of-line -2)))
11255 (defun org-prepare-dblock ()
11256 "Prepare dynamic block for refresh.
11257 This empties the block, puts the cursor at the insert position and returns
11258 the property list including an extra property :name with the block name."
11259 (unless (looking-at org-dblock-start-re)
11260 (error "Not at a dynamic block"))
11261 (let* ((begdel (1+ (match-end 0)))
11262 (name (org-no-properties (match-string 1)))
11263 (params (append (list :name name)
11264 (read (concat "(" (match-string 3) ")")))))
11265 (save-excursion
11266 (beginning-of-line 1)
11267 (skip-chars-forward " \t")
11268 (setq params (plist-put params :indentation-column (current-column))))
11269 (unless (re-search-forward org-dblock-end-re nil t)
11270 (error "Dynamic block not terminated"))
11271 (setq params
11272 (append params
11273 (list :content (buffer-substring
11274 begdel (match-beginning 0)))))
11275 (delete-region begdel (match-beginning 0))
11276 (goto-char begdel)
11277 (open-line 1)
11278 params))
11280 (defun org-map-dblocks (&optional command)
11281 "Apply COMMAND to all dynamic blocks in the current buffer.
11282 If COMMAND is not given, use `org-update-dblock'."
11283 (let ((cmd (or command 'org-update-dblock)))
11284 (save-excursion
11285 (goto-char (point-min))
11286 (while (re-search-forward org-dblock-start-re nil t)
11287 (goto-char (match-beginning 0))
11288 (save-excursion
11289 (condition-case nil
11290 (funcall cmd)
11291 (error (message "Error during update of dynamic block"))))
11292 (unless (re-search-forward org-dblock-end-re nil t)
11293 (error "Dynamic block not terminated"))))))
11295 (defun org-dblock-update (&optional arg)
11296 "User command for updating dynamic blocks.
11297 Update the dynamic block at point. With prefix ARG, update all dynamic
11298 blocks in the buffer."
11299 (interactive "P")
11300 (if arg
11301 (org-update-all-dblocks)
11302 (or (looking-at org-dblock-start-re)
11303 (org-beginning-of-dblock))
11304 (org-update-dblock)))
11306 (defun org-update-dblock ()
11307 "Update the dynamic block at point.
11308 This means to empty the block, parse for parameters and then call
11309 the correct writing function."
11310 (interactive)
11311 (save-window-excursion
11312 (let* ((pos (point))
11313 (line (org-current-line))
11314 (params (org-prepare-dblock))
11315 (name (plist-get params :name))
11316 (indent (plist-get params :indentation-column))
11317 (cmd (intern (concat "org-dblock-write:" name))))
11318 (message "Updating dynamic block `%s' at line %d..." name line)
11319 (funcall cmd params)
11320 (message "Updating dynamic block `%s' at line %d...done" name line)
11321 (goto-char pos)
11322 (when (and indent (> indent 0))
11323 (setq indent (make-string indent ?\ ))
11324 (save-excursion
11325 (org-beginning-of-dblock)
11326 (forward-line 1)
11327 (while (not (looking-at org-dblock-end-re))
11328 (insert indent)
11329 (beginning-of-line 2))
11330 (when (looking-at org-dblock-end-re)
11331 (and (looking-at "[ \t]+")
11332 (replace-match ""))
11333 (insert indent)))))))
11335 (defun org-beginning-of-dblock ()
11336 "Find the beginning of the dynamic block at point.
11337 Error if there is no such block at point."
11338 (let ((pos (point))
11339 beg)
11340 (end-of-line 1)
11341 (if (and (re-search-backward org-dblock-start-re nil t)
11342 (setq beg (match-beginning 0))
11343 (re-search-forward org-dblock-end-re nil t)
11344 (> (match-end 0) pos))
11345 (goto-char beg)
11346 (goto-char pos)
11347 (error "Not in a dynamic block"))))
11349 ;;;###autoload
11350 (defun org-update-all-dblocks ()
11351 "Update all dynamic blocks in the buffer.
11352 This function can be used in a hook."
11353 (interactive)
11354 (when (derived-mode-p 'org-mode)
11355 (org-map-dblocks 'org-update-dblock)))
11358 ;;;; Completion
11360 (defconst org-additional-option-like-keywords
11361 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11362 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11363 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11364 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11365 "BEGIN:" "END:"
11366 "ORGTBL" "TBLFM:" "TBLNAME:"
11367 "BEGIN_EXAMPLE" "END_EXAMPLE"
11368 "BEGIN_VERBATIM" "END_VERBATIM"
11369 "BEGIN_QUOTE" "END_QUOTE"
11370 "BEGIN_VERSE" "END_VERSE"
11371 "BEGIN_CENTER" "END_CENTER"
11372 "BEGIN_SRC" "END_SRC"
11373 "BEGIN_RESULT" "END_RESULT"
11374 "BEGIN_lstlisting" "END_lstlisting"
11375 "NAME:" "RESULTS:"
11376 "HEADER:" "HEADERS:"
11377 "COLUMNS:" "PROPERTY:"
11378 "CAPTION:" "LABEL:"
11379 "SETUPFILE:"
11380 "INCLUDE:"
11381 "BIND:"
11382 "MACRO:"))
11384 (defconst org-options-keywords
11385 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11386 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11387 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11388 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11389 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11390 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11391 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11393 (defconst org-additional-option-like-keywords-for-flyspell
11394 (delete-dups
11395 (split-string
11396 (mapconcat (lambda(k)
11397 (replace-regexp-in-string
11398 "_\\|:" " "
11399 (concat k " " (downcase k) " " (upcase k))))
11400 (append org-options-keywords org-additional-option-like-keywords)
11401 " ")
11402 " +" t)))
11404 (defcustom org-structure-template-alist
11406 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11407 "<src lang=\"?\">\n\n</src>")
11408 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11409 "<example>\n?\n</example>")
11410 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11411 "<quote>\n?\n</quote>")
11412 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11413 "<verse>\n?\n</verse>")
11414 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11415 "<center>\n?\n</center>")
11416 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11417 "<literal style=\"latex\">\n?\n</literal>")
11418 ("L" "#+LaTeX: "
11419 "<literal style=\"latex\">?</literal>")
11420 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11421 "<literal style=\"html\">\n?\n</literal>")
11422 ("H" "#+HTML: "
11423 "<literal style=\"html\">?</literal>")
11424 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11425 ("A" "#+ASCII: ")
11426 ("i" "#+INDEX: ?"
11427 "#+INDEX: ?")
11428 ("I" "#+INCLUDE: %file ?"
11429 "<include file=%file markup=\"?\">")
11431 "Structure completion elements.
11432 This is a list of abbreviation keys and values. The value gets inserted
11433 if you type `<' followed by the key and then press the completion key,
11434 usually `M-TAB'. %file will be replaced by a file name after prompting
11435 for the file using completion. The cursor will be placed at the position
11436 of the `?` in the template.
11437 There are two templates for each key, the first uses the original Org syntax,
11438 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11439 the default when the /org-mtags.el/ module has been loaded. See also the
11440 variable `org-mtags-prefer-muse-templates'."
11441 :group 'org-completion
11442 :type '(repeat
11443 (string :tag "Key")
11444 (string :tag "Template")
11445 (string :tag "Muse Template")))
11447 (defun org-try-structure-completion ()
11448 "Try to complete a structure template before point.
11449 This looks for strings like \"<e\" on an otherwise empty line and
11450 expands them."
11451 (let ((l (buffer-substring (point-at-bol) (point)))
11453 (when (and (looking-at "[ \t]*$")
11454 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11455 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11456 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11457 (match-beginning 1)) a)
11458 t)))
11460 (defun org-complete-expand-structure-template (start cell)
11461 "Expand a structure template."
11462 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11463 (rpl (nth (if musep 2 1) cell))
11464 (ind ""))
11465 (delete-region start (point))
11466 (when (string-match "\\`#\\+" rpl)
11467 (cond
11468 ((bolp))
11469 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11470 (setq ind (buffer-substring (point-at-bol) (point))))
11471 (t (newline))))
11472 (setq start (point))
11473 (if (string-match "%file" rpl)
11474 (setq rpl (replace-match
11475 (concat
11476 "\""
11477 (save-match-data
11478 (abbreviate-file-name (read-file-name "Include file: ")))
11479 "\"")
11480 t t rpl)))
11481 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11482 (concat "\n" ind)))
11483 (insert rpl)
11484 (if (re-search-backward "\\?" start t) (delete-char 1))))
11486 ;;;; TODO, DEADLINE, Comments
11488 (defun org-toggle-comment ()
11489 "Change the COMMENT state of an entry."
11490 (interactive)
11491 (save-excursion
11492 (org-back-to-heading)
11493 (let (case-fold-search)
11494 (cond
11495 ((looking-at (format org-heading-keyword-regexp-format
11496 org-comment-string))
11497 (goto-char (match-end 1))
11498 (looking-at (concat " +" org-comment-string))
11499 (replace-match "" t t)
11500 (when (eolp) (insert " ")))
11501 ((looking-at org-outline-regexp)
11502 (goto-char (match-end 0))
11503 (insert org-comment-string " "))))))
11505 (defvar org-last-todo-state-is-todo nil
11506 "This is non-nil when the last TODO state change led to a TODO state.
11507 If the last change removed the TODO tag or switched to DONE, then
11508 this is nil.")
11510 (defvar org-setting-tags nil) ; dynamically skipped
11512 (defvar org-todo-setup-filter-hook nil
11513 "Hook for functions that pre-filter todo specs.
11514 Each function takes a todo spec and returns either nil or the spec
11515 transformed into canonical form." )
11517 (defvar org-todo-get-default-hook nil
11518 "Hook for functions that get a default item for todo.
11519 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11520 nil or a string to be used for the todo mark." )
11522 (defvar org-agenda-headline-snapshot-before-repeat)
11524 (defun org-current-effective-time ()
11525 "Return current time adjusted for `org-extend-today-until' variable."
11526 (let* ((ct (org-current-time))
11527 (dct (decode-time ct))
11528 (ct1
11529 (if (and org-use-effective-time
11530 (< (nth 2 dct) org-extend-today-until))
11531 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11532 ct)))
11533 ct1))
11535 (defun org-todo-yesterday (&optional arg)
11536 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11537 (interactive "P")
11538 (if (eq major-mode 'org-agenda-mode)
11539 (apply 'org-agenda-todo-yesterday arg)
11540 (let* ((hour (third (decode-time
11541 (org-current-time))))
11542 (org-extend-today-until (1+ hour)))
11543 (org-todo arg))))
11545 (defun org-todo (&optional arg)
11546 "Change the TODO state of an item.
11547 The state of an item is given by a keyword at the start of the heading,
11548 like
11549 *** TODO Write paper
11550 *** DONE Call mom
11552 The different keywords are specified in the variable `org-todo-keywords'.
11553 By default the available states are \"TODO\" and \"DONE\".
11554 So for this example: when the item starts with TODO, it is changed to DONE.
11555 When it starts with DONE, the DONE is removed. And when neither TODO nor
11556 DONE are present, add TODO at the beginning of the heading.
11558 With \\[universal-argument] prefix arg, use completion to determine the new \
11559 state.
11560 With numeric prefix arg, switch to that state.
11561 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11562 keywords (nextset).
11563 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11564 With a numeric prefix arg of 0, inhibit note taking for the change.
11566 For calling through lisp, arg is also interpreted in the following way:
11567 'none -> empty state
11568 \"\"(empty string) -> switch to empty state
11569 'done -> switch to DONE
11570 'nextset -> switch to the next set of keywords
11571 'previousset -> switch to the previous set of keywords
11572 \"WAITING\" -> switch to the specified keyword, but only if it
11573 really is a member of `org-todo-keywords'."
11574 (interactive "P")
11575 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11576 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11577 'region-start-level 'region))
11578 org-loop-over-headlines-in-active-region)
11579 (org-map-entries
11580 `(org-todo ,arg)
11581 org-loop-over-headlines-in-active-region
11582 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11583 (if (equal arg '(16)) (setq arg 'nextset))
11584 (let ((org-blocker-hook org-blocker-hook)
11585 (case-fold-search nil))
11586 (when (equal arg '(64))
11587 (setq arg nil org-blocker-hook nil))
11588 (when (and org-blocker-hook
11589 (or org-inhibit-blocking
11590 (org-entry-get nil "NOBLOCKING")))
11591 (setq org-blocker-hook nil))
11592 (save-excursion
11593 (catch 'exit
11594 (org-back-to-heading t)
11595 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11596 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11597 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11598 (let* ((match-data (match-data))
11599 (startpos (point-at-bol))
11600 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11601 (org-log-done org-log-done)
11602 (org-log-repeat org-log-repeat)
11603 (org-todo-log-states org-todo-log-states)
11604 (org-inhibit-logging
11605 (if (equal arg 0)
11606 (progn (setq arg nil) 'note) org-inhibit-logging))
11607 (this (match-string 1))
11608 (hl-pos (match-beginning 0))
11609 (head (org-get-todo-sequence-head this))
11610 (ass (assoc head org-todo-kwd-alist))
11611 (interpret (nth 1 ass))
11612 (done-word (nth 3 ass))
11613 (final-done-word (nth 4 ass))
11614 (org-last-state (or this ""))
11615 (completion-ignore-case t)
11616 (member (member this org-todo-keywords-1))
11617 (tail (cdr member))
11618 (org-state (cond
11619 ((and org-todo-key-trigger
11620 (or (and (equal arg '(4))
11621 (eq org-use-fast-todo-selection 'prefix))
11622 (and (not arg) org-use-fast-todo-selection
11623 (not (eq org-use-fast-todo-selection
11624 'prefix)))))
11625 ;; Use fast selection
11626 (org-fast-todo-selection))
11627 ((and (equal arg '(4))
11628 (or (not org-use-fast-todo-selection)
11629 (not org-todo-key-trigger)))
11630 ;; Read a state with completion
11631 (org-icompleting-read
11632 "State: " (mapcar (lambda(x) (list x))
11633 org-todo-keywords-1)
11634 nil t))
11635 ((eq arg 'right)
11636 (if this
11637 (if tail (car tail) nil)
11638 (car org-todo-keywords-1)))
11639 ((eq arg 'left)
11640 (if (equal member org-todo-keywords-1)
11642 (if this
11643 (nth (- (length org-todo-keywords-1)
11644 (length tail) 2)
11645 org-todo-keywords-1)
11646 (org-last org-todo-keywords-1))))
11647 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11648 (setq arg nil))) ; hack to fall back to cycling
11649 (arg
11650 ;; user or caller requests a specific state
11651 (cond
11652 ((equal arg "") nil)
11653 ((eq arg 'none) nil)
11654 ((eq arg 'done) (or done-word (car org-done-keywords)))
11655 ((eq arg 'nextset)
11656 (or (car (cdr (member head org-todo-heads)))
11657 (car org-todo-heads)))
11658 ((eq arg 'previousset)
11659 (let ((org-todo-heads (reverse org-todo-heads)))
11660 (or (car (cdr (member head org-todo-heads)))
11661 (car org-todo-heads))))
11662 ((car (member arg org-todo-keywords-1)))
11663 ((stringp arg)
11664 (error "State `%s' not valid in this file" arg))
11665 ((nth (1- (prefix-numeric-value arg))
11666 org-todo-keywords-1))))
11667 ((null member) (or head (car org-todo-keywords-1)))
11668 ((equal this final-done-word) nil) ;; -> make empty
11669 ((null tail) nil) ;; -> first entry
11670 ((memq interpret '(type priority))
11671 (if (eq this-command last-command)
11672 (car tail)
11673 (if (> (length tail) 0)
11674 (or done-word (car org-done-keywords))
11675 nil)))
11677 (car tail))))
11678 (org-state (or
11679 (run-hook-with-args-until-success
11680 'org-todo-get-default-hook org-state org-last-state)
11681 org-state))
11682 (next (if org-state (concat " " org-state " ") " "))
11683 (change-plist (list :type 'todo-state-change :from this :to org-state
11684 :position startpos))
11685 dolog now-done-p)
11686 (when org-blocker-hook
11687 (setq org-last-todo-state-is-todo
11688 (not (member this org-done-keywords)))
11689 (unless (save-excursion
11690 (save-match-data
11691 (org-with-wide-buffer
11692 (run-hook-with-args-until-failure
11693 'org-blocker-hook change-plist))))
11694 (if (org-called-interactively-p 'interactive)
11695 (error "TODO state change from %s to %s blocked" this org-state)
11696 ;; fail silently
11697 (message "TODO state change from %s to %s blocked" this org-state)
11698 (throw 'exit nil))))
11699 (store-match-data match-data)
11700 (replace-match next t t)
11701 (unless (pos-visible-in-window-p hl-pos)
11702 (message "TODO state changed to %s" (org-trim next)))
11703 (unless head
11704 (setq head (org-get-todo-sequence-head org-state)
11705 ass (assoc head org-todo-kwd-alist)
11706 interpret (nth 1 ass)
11707 done-word (nth 3 ass)
11708 final-done-word (nth 4 ass)))
11709 (when (memq arg '(nextset previousset))
11710 (message "Keyword-Set %d/%d: %s"
11711 (- (length org-todo-sets) -1
11712 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11713 (length org-todo-sets)
11714 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11715 (setq org-last-todo-state-is-todo
11716 (not (member org-state org-done-keywords)))
11717 (setq now-done-p (and (member org-state org-done-keywords)
11718 (not (member this org-done-keywords))))
11719 (and logging (org-local-logging logging))
11720 (when (and (or org-todo-log-states org-log-done)
11721 (not (eq org-inhibit-logging t))
11722 (not (memq arg '(nextset previousset))))
11723 ;; we need to look at recording a time and note
11724 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11725 (nth 2 (assoc this org-todo-log-states))))
11726 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11727 (setq dolog 'time))
11728 (when (and org-state
11729 (member org-state org-not-done-keywords)
11730 (not (member this org-not-done-keywords)))
11731 ;; This is now a todo state and was not one before
11732 ;; If there was a CLOSED time stamp, get rid of it.
11733 (org-add-planning-info nil nil 'closed))
11734 (when (and now-done-p org-log-done)
11735 ;; It is now done, and it was not done before
11736 (org-add-planning-info 'closed (org-current-effective-time))
11737 (if (and (not dolog) (eq 'note org-log-done))
11738 (org-add-log-setup 'done org-state this 'findpos 'note)))
11739 (when (and org-state dolog)
11740 ;; This is a non-nil state, and we need to log it
11741 (org-add-log-setup 'state org-state this 'findpos dolog)))
11742 ;; Fixup tag positioning
11743 (org-todo-trigger-tag-changes org-state)
11744 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11745 (when org-provide-todo-statistics
11746 (org-update-parent-todo-statistics))
11747 (run-hooks 'org-after-todo-state-change-hook)
11748 (if (and arg (not (member org-state org-done-keywords)))
11749 (setq head (org-get-todo-sequence-head org-state)))
11750 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11751 ;; Do we need to trigger a repeat?
11752 (when now-done-p
11753 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11754 ;; This is for the agenda, take a snapshot of the headline.
11755 (save-match-data
11756 (setq org-agenda-headline-snapshot-before-repeat
11757 (org-get-heading))))
11758 (org-auto-repeat-maybe org-state))
11759 ;; Fixup cursor location if close to the keyword
11760 (if (and (outline-on-heading-p)
11761 (not (bolp))
11762 (save-excursion (beginning-of-line 1)
11763 (looking-at org-todo-line-regexp))
11764 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11765 (progn
11766 (goto-char (or (match-end 2) (match-end 1)))
11767 (and (looking-at " ") (just-one-space))))
11768 (when org-trigger-hook
11769 (save-excursion
11770 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11772 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11773 "Block turning an entry into a TODO, using the hierarchy.
11774 This checks whether the current task should be blocked from state
11775 changes. Such blocking occurs when:
11777 1. The task has children which are not all in a completed state.
11779 2. A task has a parent with the property :ORDERED:, and there
11780 are siblings prior to the current task with incomplete
11781 status.
11783 3. The parent of the task is blocked because it has siblings that should
11784 be done first, or is child of a block grandparent TODO entry."
11786 (if (not org-enforce-todo-dependencies)
11787 t ; if locally turned off don't block
11788 (catch 'dont-block
11789 ;; If this is not a todo state change, or if this entry is already DONE,
11790 ;; do not block
11791 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11792 (member (plist-get change-plist :from)
11793 (cons 'done org-done-keywords))
11794 (member (plist-get change-plist :to)
11795 (cons 'todo org-not-done-keywords))
11796 (not (plist-get change-plist :to)))
11797 (throw 'dont-block t))
11798 ;; If this task has children, and any are undone, it's blocked
11799 (save-excursion
11800 (org-back-to-heading t)
11801 (let ((this-level (funcall outline-level)))
11802 (outline-next-heading)
11803 (let ((child-level (funcall outline-level)))
11804 (while (and (not (eobp))
11805 (> child-level this-level))
11806 ;; this todo has children, check whether they are all
11807 ;; completed
11808 (if (and (not (org-entry-is-done-p))
11809 (org-entry-is-todo-p))
11810 (throw 'dont-block nil))
11811 (outline-next-heading)
11812 (setq child-level (funcall outline-level))))))
11813 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11814 ;; any previous siblings are undone, it's blocked
11815 (save-excursion
11816 (org-back-to-heading t)
11817 (let* ((pos (point))
11818 (parent-pos (and (org-up-heading-safe) (point))))
11819 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11820 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11821 (forward-line 1)
11822 (re-search-forward org-not-done-heading-regexp pos t))
11823 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11824 ;; Search further up the hierarchy, to see if an ancestor is blocked
11825 (while t
11826 (goto-char parent-pos)
11827 (if (not (looking-at org-not-done-heading-regexp))
11828 (throw 'dont-block t)) ; do not block, parent is not a TODO
11829 (setq pos (point))
11830 (setq parent-pos (and (org-up-heading-safe) (point)))
11831 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11832 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11833 (forward-line 1)
11834 (re-search-forward org-not-done-heading-regexp pos t))
11835 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11837 (defcustom org-track-ordered-property-with-tag nil
11838 "Should the ORDERED property also be shown as a tag?
11839 The ORDERED property decides if an entry should require subtasks to be
11840 completed in sequence. Since a property is not very visible, setting
11841 this option means that toggling the ORDERED property with the command
11842 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11843 not relevant for the behavior, but it makes things more visible.
11845 Note that toggling the tag with tags commands will not change the property
11846 and therefore not influence behavior!
11848 This can be t, meaning the tag ORDERED should be used, It can also be a
11849 string to select a different tag for this task."
11850 :group 'org-todo
11851 :type '(choice
11852 (const :tag "No tracking" nil)
11853 (const :tag "Track with ORDERED tag" t)
11854 (string :tag "Use other tag")))
11856 (defun org-toggle-ordered-property ()
11857 "Toggle the ORDERED property of the current entry.
11858 For better visibility, you can track the value of this property with a tag.
11859 See variable `org-track-ordered-property-with-tag'."
11860 (interactive)
11861 (let* ((t1 org-track-ordered-property-with-tag)
11862 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11863 (save-excursion
11864 (org-back-to-heading)
11865 (if (org-entry-get nil "ORDERED")
11866 (progn
11867 (org-delete-property "ORDERED")
11868 (and tag (org-toggle-tag tag 'off))
11869 (message "Subtasks can be completed in arbitrary order"))
11870 (org-entry-put nil "ORDERED" "t")
11871 (and tag (org-toggle-tag tag 'on))
11872 (message "Subtasks must be completed in sequence")))))
11874 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11875 (defun org-block-todo-from-checkboxes (change-plist)
11876 "Block turning an entry into a TODO, using checkboxes.
11877 This checks whether the current task should be blocked from state
11878 changes because there are unchecked boxes in this entry."
11879 (if (not org-enforce-todo-checkbox-dependencies)
11880 t ; if locally turned off don't block
11881 (catch 'dont-block
11882 ;; If this is not a todo state change, or if this entry is already DONE,
11883 ;; do not block
11884 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11885 (member (plist-get change-plist :from)
11886 (cons 'done org-done-keywords))
11887 (member (plist-get change-plist :to)
11888 (cons 'todo org-not-done-keywords))
11889 (not (plist-get change-plist :to)))
11890 (throw 'dont-block t))
11891 ;; If this task has checkboxes that are not checked, it's blocked
11892 (save-excursion
11893 (org-back-to-heading t)
11894 (let ((beg (point)) end)
11895 (outline-next-heading)
11896 (setq end (point))
11897 (goto-char beg)
11898 (if (org-list-search-forward
11899 (concat (org-item-beginning-re)
11900 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11901 "\\[[- ]\\]")
11902 end t)
11903 (progn
11904 (if (boundp 'org-blocked-by-checkboxes)
11905 (setq org-blocked-by-checkboxes t))
11906 (throw 'dont-block nil)))))
11907 t))) ; do not block
11909 (defun org-entry-blocked-p ()
11910 "Is the current entry blocked?"
11911 (if (org-entry-get nil "NOBLOCKING")
11912 nil ;; Never block this entry
11913 (not
11914 (run-hook-with-args-until-failure
11915 'org-blocker-hook
11916 (list :type 'todo-state-change
11917 :position (point)
11918 :from 'todo
11919 :to 'done)))))
11921 (defun org-update-statistics-cookies (all)
11922 "Update the statistics cookie, either from TODO or from checkboxes.
11923 This should be called with the cursor in a line with a statistics cookie."
11924 (interactive "P")
11925 (if all
11926 (progn
11927 (org-update-checkbox-count 'all)
11928 (org-map-entries 'org-update-parent-todo-statistics))
11929 (if (not (org-at-heading-p))
11930 (org-update-checkbox-count)
11931 (let ((pos (move-marker (make-marker) (point)))
11932 end l1 l2)
11933 (ignore-errors (org-back-to-heading t))
11934 (if (not (org-at-heading-p))
11935 (org-update-checkbox-count)
11936 (setq l1 (org-outline-level))
11937 (setq end (save-excursion
11938 (outline-next-heading)
11939 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11940 (point)))
11941 (if (and (save-excursion
11942 (re-search-forward
11943 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11944 (not (save-excursion (re-search-forward
11945 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11946 (org-update-checkbox-count)
11947 (if (and l2 (> l2 l1))
11948 (progn
11949 (goto-char end)
11950 (org-update-parent-todo-statistics))
11951 (goto-char pos)
11952 (beginning-of-line 1)
11953 (while (re-search-forward
11954 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11955 (point-at-eol) t)
11956 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11957 (goto-char pos)
11958 (move-marker pos nil)))))
11960 (defvar org-entry-property-inherited-from) ;; defined below
11961 (defun org-update-parent-todo-statistics ()
11962 "Update any statistics cookie in the parent of the current headline.
11963 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11964 the entire subtree and this will travel up the hierarchy and update
11965 statistics everywhere."
11966 (let* ((prop (save-excursion (org-up-heading-safe)
11967 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11968 (recursive (or (not org-hierarchical-todo-statistics)
11969 (and prop (string-match "\\<recursive\\>" prop))))
11970 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11972 (first t)
11973 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11974 level ltoggle l1 new ndel
11975 (cnt-all 0) (cnt-done 0) is-percent kwd
11976 checkbox-beg ov ovs ove cookie-present)
11977 (catch 'exit
11978 (save-excursion
11979 (beginning-of-line 1)
11980 (setq ltoggle (funcall outline-level))
11981 ;; Three situations are to consider:
11983 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11984 ;; to the top-level ancestor on the headline;
11986 ;; 2. If parent has "recursive" property, repeat up to the
11987 ;; headline setting that property, taking inheritance into
11988 ;; account;
11990 ;; 3. Else, move up to direct parent and proceed only once.
11991 (while (and (setq level (org-up-heading-safe))
11992 (or recursive first)
11993 (>= (point) lim))
11994 (setq first nil cookie-present nil)
11995 (unless (and level
11996 (not (string-match
11997 "\\<checkbox\\>"
11998 (downcase (or (org-entry-get nil "COOKIE_DATA")
11999 "")))))
12000 (throw 'exit nil))
12001 (while (re-search-forward box-re (point-at-eol) t)
12002 (setq cnt-all 0 cnt-done 0 cookie-present t)
12003 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12004 (save-match-data
12005 (unless (outline-next-heading) (throw 'exit nil))
12006 (while (and (looking-at org-complex-heading-regexp)
12007 (> (setq l1 (length (match-string 1))) level))
12008 (setq kwd (and (or recursive (= l1 ltoggle))
12009 (match-string 2)))
12010 (if (or (eq org-provide-todo-statistics 'all-headlines)
12011 (and (listp org-provide-todo-statistics)
12012 (or (member kwd org-provide-todo-statistics)
12013 (member kwd org-done-keywords))))
12014 (setq cnt-all (1+ cnt-all))
12015 (if (eq org-provide-todo-statistics t)
12016 (and kwd (setq cnt-all (1+ cnt-all)))))
12017 (and (member kwd org-done-keywords)
12018 (setq cnt-done (1+ cnt-done)))
12019 (outline-next-heading)))
12020 (setq new
12021 (if is-percent
12022 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12023 (format "[%d/%d]" cnt-done cnt-all))
12024 ndel (- (match-end 0) checkbox-beg))
12025 ;; handle overlays when updating cookie from column view
12026 (when (setq ov (car (overlays-at checkbox-beg)))
12027 (setq ovs (overlay-start ov) ove (overlay-end ov))
12028 (delete-overlay ov))
12029 (goto-char checkbox-beg)
12030 (insert new)
12031 (delete-region (point) (+ (point) ndel))
12032 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12033 (when ov (move-overlay ov ovs ove)))
12034 (when cookie-present
12035 (run-hook-with-args 'org-after-todo-statistics-hook
12036 cnt-done (- cnt-all cnt-done))))))
12037 (run-hooks 'org-todo-statistics-hook)))
12039 (defvar org-after-todo-statistics-hook nil
12040 "Hook that is called after a TODO statistics cookie has been updated.
12041 Each function is called with two arguments: the number of not-done entries
12042 and the number of done entries.
12044 For example, the following function, when added to this hook, will switch
12045 an entry to DONE when all children are done, and back to TODO when new
12046 entries are set to a TODO status. Note that this hook is only called
12047 when there is a statistics cookie in the headline!
12049 (defun org-summary-todo (n-done n-not-done)
12050 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12051 (let (org-log-done org-log-states) ; turn off logging
12052 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12055 (defvar org-todo-statistics-hook nil
12056 "Hook that is run whenever Org thinks TODO statistics should be updated.
12057 This hook runs even if there is no statistics cookie present, in which case
12058 `org-after-todo-statistics-hook' would not run.")
12060 (defun org-todo-trigger-tag-changes (state)
12061 "Apply the changes defined in `org-todo-state-tags-triggers'."
12062 (let ((l org-todo-state-tags-triggers)
12063 changes)
12064 (when (or (not state) (equal state ""))
12065 (setq changes (append changes (cdr (assoc "" l)))))
12066 (when (and (stringp state) (> (length state) 0))
12067 (setq changes (append changes (cdr (assoc state l)))))
12068 (when (member state org-not-done-keywords)
12069 (setq changes (append changes (cdr (assoc 'todo l)))))
12070 (when (member state org-done-keywords)
12071 (setq changes (append changes (cdr (assoc 'done l)))))
12072 (dolist (c changes)
12073 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12075 (defun org-local-logging (value)
12076 "Get logging settings from a property VALUE."
12077 (let* (words w a)
12078 ;; directly set the variables, they are already local.
12079 (setq org-log-done nil
12080 org-log-repeat nil
12081 org-todo-log-states nil)
12082 (setq words (org-split-string value))
12083 (while (setq w (pop words))
12084 (cond
12085 ((setq a (assoc w org-startup-options))
12086 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12087 (set (nth 1 a) (nth 2 a))))
12088 ((setq a (org-extract-log-state-settings w))
12089 (and (member (car a) org-todo-keywords-1)
12090 (push a org-todo-log-states)))))))
12092 (defun org-get-todo-sequence-head (kwd)
12093 "Return the head of the TODO sequence to which KWD belongs.
12094 If KWD is not set, check if there is a text property remembering the
12095 right sequence."
12096 (let (p)
12097 (cond
12098 ((not kwd)
12099 (or (get-text-property (point-at-bol) 'org-todo-head)
12100 (progn
12101 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12102 nil (point-at-eol)))
12103 (get-text-property p 'org-todo-head))))
12104 ((not (member kwd org-todo-keywords-1))
12105 (car org-todo-keywords-1))
12106 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12108 (defun org-fast-todo-selection ()
12109 "Fast TODO keyword selection with single keys.
12110 Returns the new TODO keyword, or nil if no state change should occur."
12111 (let* ((fulltable org-todo-key-alist)
12112 (done-keywords org-done-keywords) ;; needed for the faces.
12113 (maxlen (apply 'max (mapcar
12114 (lambda (x)
12115 (if (stringp (car x)) (string-width (car x)) 0))
12116 fulltable)))
12117 (expert nil)
12118 (fwidth (+ maxlen 3 1 3))
12119 (ncol (/ (- (window-width) 4) fwidth))
12120 tg cnt e c tbl
12121 groups ingroup)
12122 (save-excursion
12123 (save-window-excursion
12124 (if expert
12125 (set-buffer (get-buffer-create " *Org todo*"))
12126 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12127 (erase-buffer)
12128 (org-set-local 'org-done-keywords done-keywords)
12129 (setq tbl fulltable cnt 0)
12130 (while (setq e (pop tbl))
12131 (cond
12132 ((equal e '(:startgroup))
12133 (push '() groups) (setq ingroup t)
12134 (when (not (= cnt 0))
12135 (setq cnt 0)
12136 (insert "\n"))
12137 (insert "{ "))
12138 ((equal e '(:endgroup))
12139 (setq ingroup nil cnt 0)
12140 (insert "}\n"))
12141 ((equal e '(:newline))
12142 (when (not (= cnt 0))
12143 (setq cnt 0)
12144 (insert "\n")
12145 (setq e (car tbl))
12146 (while (equal (car tbl) '(:newline))
12147 (insert "\n")
12148 (setq tbl (cdr tbl)))))
12150 (setq tg (car e) c (cdr e))
12151 (if ingroup (push tg (car groups)))
12152 (setq tg (org-add-props tg nil 'face
12153 (org-get-todo-face tg)))
12154 (if (and (= cnt 0) (not ingroup)) (insert " "))
12155 (insert "[" c "] " tg (make-string
12156 (- fwidth 4 (length tg)) ?\ ))
12157 (when (= (setq cnt (1+ cnt)) ncol)
12158 (insert "\n")
12159 (if ingroup (insert " "))
12160 (setq cnt 0)))))
12161 (insert "\n")
12162 (goto-char (point-min))
12163 (if (not expert) (org-fit-window-to-buffer))
12164 (message "[a-z..]:Set [SPC]:clear")
12165 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12166 (cond
12167 ((or (= c ?\C-g)
12168 (and (= c ?q) (not (rassoc c fulltable))))
12169 (setq quit-flag t))
12170 ((= c ?\ ) nil)
12171 ((setq e (rassoc c fulltable) tg (car e))
12173 (t (setq quit-flag t)))))))
12175 (defun org-entry-is-todo-p ()
12176 (member (org-get-todo-state) org-not-done-keywords))
12178 (defun org-entry-is-done-p ()
12179 (member (org-get-todo-state) org-done-keywords))
12181 (defun org-get-todo-state ()
12182 (save-excursion
12183 (org-back-to-heading t)
12184 (and (looking-at org-todo-line-regexp)
12185 (match-end 2)
12186 (match-string 2))))
12188 (defun org-at-date-range-p (&optional inactive-ok)
12189 "Is the cursor inside a date range?"
12190 (interactive)
12191 (save-excursion
12192 (catch 'exit
12193 (let ((pos (point)))
12194 (skip-chars-backward "^[<\r\n")
12195 (skip-chars-backward "<[")
12196 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12197 (>= (match-end 0) pos)
12198 (throw 'exit t))
12199 (skip-chars-backward "^<[\r\n")
12200 (skip-chars-backward "<[")
12201 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12202 (>= (match-end 0) pos)
12203 (throw 'exit t)))
12204 nil)))
12206 (defun org-get-repeat (&optional tagline)
12207 "Check if there is a deadline/schedule with repeater in this entry."
12208 (save-match-data
12209 (save-excursion
12210 (org-back-to-heading t)
12211 (and (re-search-forward (if tagline
12212 (concat tagline "\\s-*" org-repeat-re)
12213 org-repeat-re)
12214 (org-entry-end-position) t)
12215 (match-string-no-properties 1)))))
12217 (defvar org-last-changed-timestamp)
12218 (defvar org-last-inserted-timestamp)
12219 (defvar org-log-post-message)
12220 (defvar org-log-note-purpose)
12221 (defvar org-log-note-how)
12222 (defvar org-log-note-extra)
12223 (defun org-auto-repeat-maybe (done-word)
12224 "Check if the current headline contains a repeated deadline/schedule.
12225 If yes, set TODO state back to what it was and change the base date
12226 of repeating deadline/scheduled time stamps to new date.
12227 This function is run automatically after each state change to a DONE state."
12228 ;; last-state is dynamically scoped into this function
12229 (let* ((repeat (org-get-repeat))
12230 (aa (assoc org-last-state org-todo-kwd-alist))
12231 (interpret (nth 1 aa))
12232 (head (nth 2 aa))
12233 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12234 (msg "Entry repeats: ")
12235 (org-log-done nil)
12236 (org-todo-log-states nil)
12237 re type n what ts time to-state)
12238 (when repeat
12239 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12240 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12241 org-todo-repeat-to-state))
12242 (unless (and to-state (member to-state org-todo-keywords-1))
12243 (setq to-state (if (eq interpret 'type) org-last-state head)))
12244 (org-todo to-state)
12245 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12246 (org-entry-put nil "LAST_REPEAT" (format-time-string
12247 (org-time-stamp-format t t))))
12248 (when org-log-repeat
12249 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12250 (memq 'org-add-log-note post-command-hook))
12251 ;; OK, we are already setup for some record
12252 (if (eq org-log-repeat 'note)
12253 ;; make sure we take a note, not only a time stamp
12254 (setq org-log-note-how 'note))
12255 ;; Set up for taking a record
12256 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12257 org-last-state
12258 'findpos org-log-repeat)))
12259 (org-back-to-heading t)
12260 (org-add-planning-info nil nil 'closed)
12261 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12262 org-deadline-time-regexp "\\)\\|\\("
12263 org-ts-regexp "\\)"))
12264 (while (re-search-forward
12265 re (save-excursion (outline-next-heading) (point)) t)
12266 (setq type (if (match-end 1) org-scheduled-string
12267 (if (match-end 3) org-deadline-string "Plain:"))
12268 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12269 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12270 (setq n (string-to-number (match-string 2 ts))
12271 what (match-string 3 ts))
12272 (if (equal what "w") (setq n (* n 7) what "d"))
12273 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12274 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12275 ;; Preparation, see if we need to modify the start date for the change
12276 (when (match-end 1)
12277 (setq time (save-match-data (org-time-string-to-time ts)))
12278 (cond
12279 ((equal (match-string 1 ts) ".")
12280 ;; Shift starting date to today
12281 (org-timestamp-change
12282 (- (org-today) (time-to-days time))
12283 'day))
12284 ((equal (match-string 1 ts) "+")
12285 (let ((nshiftmax 10) (nshift 0))
12286 (while (or (= nshift 0)
12287 (<= (time-to-days time)
12288 (time-to-days (current-time))))
12289 (when (= (incf nshift) nshiftmax)
12290 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12291 (error "Abort")))
12292 (org-timestamp-change n (cdr (assoc what whata)))
12293 (org-at-timestamp-p t)
12294 (setq ts (match-string 1))
12295 (setq time (save-match-data (org-time-string-to-time ts)))))
12296 (org-timestamp-change (- n) (cdr (assoc what whata)))
12297 ;; rematch, so that we have everything in place for the real shift
12298 (org-at-timestamp-p t)
12299 (setq ts (match-string 1))
12300 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12301 (org-timestamp-change n (cdr (assoc what whata)))
12302 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12303 (setq org-log-post-message msg)
12304 (message "%s" msg))))
12306 (defun org-show-todo-tree (arg)
12307 "Make a compact tree which shows all headlines marked with TODO.
12308 The tree will show the lines where the regexp matches, and all higher
12309 headlines above the match.
12310 With a \\[universal-argument] prefix, prompt for a regexp to match.
12311 With a numeric prefix N, construct a sparse tree for the Nth element
12312 of `org-todo-keywords-1'."
12313 (interactive "P")
12314 (let ((case-fold-search nil)
12315 (kwd-re
12316 (cond ((null arg) org-not-done-regexp)
12317 ((equal arg '(4))
12318 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12319 (mapcar 'list org-todo-keywords-1))))
12320 (concat "\\("
12321 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12322 "\\)\\>")))
12323 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12324 (regexp-quote (nth (1- (prefix-numeric-value arg))
12325 org-todo-keywords-1)))
12326 (t (error "Invalid prefix argument: %s" arg)))))
12327 (message "%d TODO entries found"
12328 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12330 (defun org-deadline (&optional remove time)
12331 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12332 With argument REMOVE, remove any deadline from the item.
12333 With argument TIME, set the deadline at the corresponding date. TIME
12334 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12335 (interactive "P")
12336 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12337 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12338 'region-start-level 'region))
12339 org-loop-over-headlines-in-active-region)
12340 (org-map-entries
12341 `(org-deadline ',remove ,time)
12342 org-loop-over-headlines-in-active-region
12343 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12344 (let* ((old-date (org-entry-get nil "DEADLINE"))
12345 (repeater (and old-date
12346 (string-match
12347 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12348 old-date)
12349 (match-string 1 old-date))))
12350 (if remove
12351 (progn
12352 (when (and old-date org-log-redeadline)
12353 (org-add-log-setup 'deldeadline nil old-date 'findpos
12354 org-log-redeadline))
12355 (org-remove-timestamp-with-keyword org-deadline-string)
12356 (message "Item no longer has a deadline."))
12357 (org-add-planning-info 'deadline time 'closed)
12358 (when (and old-date org-log-redeadline
12359 (not (equal old-date
12360 (substring org-last-inserted-timestamp 1 -1))))
12361 (org-add-log-setup 'redeadline nil old-date 'findpos
12362 org-log-redeadline))
12363 (when repeater
12364 (save-excursion
12365 (org-back-to-heading t)
12366 (when (re-search-forward (concat org-deadline-string " "
12367 org-last-inserted-timestamp)
12368 (save-excursion
12369 (outline-next-heading) (point)) t)
12370 (goto-char (1- (match-end 0)))
12371 (insert " " repeater)
12372 (setq org-last-inserted-timestamp
12373 (concat (substring org-last-inserted-timestamp 0 -1)
12374 " " repeater
12375 (substring org-last-inserted-timestamp -1))))))
12376 (message "Deadline on %s" org-last-inserted-timestamp)))))
12378 (defun org-schedule (&optional remove time)
12379 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12380 With argument REMOVE, remove any scheduling date from the item.
12381 With argument TIME, scheduled at the corresponding date. TIME can
12382 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12383 (interactive "P")
12384 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12385 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12386 'region-start-level 'region))
12387 org-loop-over-headlines-in-active-region)
12388 (org-map-entries
12389 `(org-schedule ',remove ,time)
12390 org-loop-over-headlines-in-active-region
12391 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12392 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12393 (repeater (and old-date
12394 (string-match
12395 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12396 old-date)
12397 (match-string 1 old-date))))
12398 (if remove
12399 (progn
12400 (when (and old-date org-log-reschedule)
12401 (org-add-log-setup 'delschedule nil old-date 'findpos
12402 org-log-reschedule))
12403 (org-remove-timestamp-with-keyword org-scheduled-string)
12404 (message "Item is no longer scheduled."))
12405 (org-add-planning-info 'scheduled time 'closed)
12406 (when (and old-date org-log-reschedule
12407 (not (equal old-date
12408 (substring org-last-inserted-timestamp 1 -1))))
12409 (org-add-log-setup 'reschedule nil old-date 'findpos
12410 org-log-reschedule))
12411 (when repeater
12412 (save-excursion
12413 (org-back-to-heading t)
12414 (when (re-search-forward (concat org-scheduled-string " "
12415 org-last-inserted-timestamp)
12416 (save-excursion
12417 (outline-next-heading) (point)) t)
12418 (goto-char (1- (match-end 0)))
12419 (insert " " repeater)
12420 (setq org-last-inserted-timestamp
12421 (concat (substring org-last-inserted-timestamp 0 -1)
12422 " " repeater
12423 (substring org-last-inserted-timestamp -1))))))
12424 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12426 (defun org-get-scheduled-time (pom &optional inherit)
12427 "Get the scheduled time as a time tuple, of a format suitable
12428 for calling org-schedule with, or if there is no scheduling,
12429 returns nil."
12430 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12431 (when time
12432 (apply 'encode-time (org-parse-time-string time)))))
12434 (defun org-get-deadline-time (pom &optional inherit)
12435 "Get the deadline as a time tuple, of a format suitable for
12436 calling org-deadline with, or if there is no scheduling, returns
12437 nil."
12438 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12439 (when time
12440 (apply 'encode-time (org-parse-time-string time)))))
12442 (defun org-remove-timestamp-with-keyword (keyword)
12443 "Remove all time stamps with KEYWORD in the current entry."
12444 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12445 beg)
12446 (save-excursion
12447 (org-back-to-heading t)
12448 (setq beg (point))
12449 (outline-next-heading)
12450 (while (re-search-backward re beg t)
12451 (replace-match "")
12452 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12453 (equal (char-before) ?\ ))
12454 (backward-delete-char 1)
12455 (if (string-match "^[ \t]*$" (buffer-substring
12456 (point-at-bol) (point-at-eol)))
12457 (delete-region (point-at-bol)
12458 (min (point-max) (1+ (point-at-eol))))))))))
12460 (defun org-add-planning-info (what &optional time &rest remove)
12461 "Insert new timestamp with keyword in the line directly after the headline.
12462 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12463 If non is given, the user is prompted for a date.
12464 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12465 be removed."
12466 (interactive)
12467 (let (org-time-was-given org-end-time-was-given ts
12468 end default-time default-input)
12470 (catch 'exit
12471 (when (and (memq what '(scheduled deadline))
12472 (or (not time)
12473 (and (stringp time)
12474 (string-match "^[-+]+[0-9]" time))))
12475 ;; Try to get a default date/time from existing timestamp
12476 (save-excursion
12477 (org-back-to-heading t)
12478 (setq end (save-excursion (outline-next-heading) (point)))
12479 (when (re-search-forward (if (eq what 'scheduled)
12480 org-scheduled-time-regexp
12481 org-deadline-time-regexp)
12482 end t)
12483 (setq ts (match-string 1)
12484 default-time
12485 (apply 'encode-time (org-parse-time-string ts))
12486 default-input (and ts (org-get-compact-tod ts))))))
12487 (when what
12488 (setq time
12489 (if (stringp time)
12490 ;; This is a string (relative or absolute), set proper date
12491 (apply 'encode-time
12492 (org-read-date-analyze
12493 time default-time (decode-time default-time)))
12494 ;; If necessary, get the time from the user
12495 (or time (org-read-date nil 'to-time nil nil
12496 default-time default-input)))))
12498 (when (and org-insert-labeled-timestamps-at-point
12499 (member what '(scheduled deadline)))
12500 (insert
12501 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12502 (org-insert-time-stamp time org-time-was-given
12503 nil nil nil (list org-end-time-was-given))
12504 (setq what nil))
12505 (save-excursion
12506 (save-restriction
12507 (let (col list elt ts buffer-invisibility-spec)
12508 (org-back-to-heading t)
12509 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12510 (goto-char (match-end 1))
12511 (setq col (current-column))
12512 (goto-char (match-end 0))
12513 (if (eobp) (insert "\n") (forward-char 1))
12514 (when (and (not what)
12515 (not (looking-at
12516 (concat "[ \t]*"
12517 org-keyword-time-not-clock-regexp))))
12518 ;; Nothing to add, nothing to remove...... :-)
12519 (throw 'exit nil))
12520 (if (and (not (looking-at org-outline-regexp))
12521 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12522 "[^\r\n]*"))
12523 (not (equal (match-string 1) org-clock-string)))
12524 (narrow-to-region (match-beginning 0) (match-end 0))
12525 (insert-before-markers "\n")
12526 (backward-char 1)
12527 (narrow-to-region (point) (point))
12528 (and org-adapt-indentation (org-indent-to-column col)))
12529 ;; Check if we have to remove something.
12530 (setq list (cons what remove))
12531 (while list
12532 (setq elt (pop list))
12533 (when (or (and (eq elt 'scheduled)
12534 (re-search-forward org-scheduled-time-regexp nil t))
12535 (and (eq elt 'deadline)
12536 (re-search-forward org-deadline-time-regexp nil t))
12537 (and (eq elt 'closed)
12538 (re-search-forward org-closed-time-regexp nil t)))
12539 (replace-match "")
12540 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12541 (and (looking-at "[ \t]+") (replace-match ""))
12542 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12543 (when what
12544 (insert
12545 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12546 (cond ((eq what 'scheduled) org-scheduled-string)
12547 ((eq what 'deadline) org-deadline-string)
12548 ((eq what 'closed) org-closed-string))
12549 " ")
12550 (setq ts (org-insert-time-stamp
12551 time
12552 (or org-time-was-given
12553 (and (eq what 'closed) org-log-done-with-time))
12554 (eq what 'closed)
12555 nil nil (list org-end-time-was-given)))
12556 (insert
12557 (if (not (or (bolp) (eq (char-before) ?\ )
12558 (memq (char-after) '(32 10))
12559 (eobp))) " " ""))
12560 (end-of-line 1))
12561 (goto-char (point-min))
12562 (widen)
12563 (if (and (looking-at "[ \t]*\n")
12564 (equal (char-before) ?\n))
12565 (delete-region (1- (point)) (point-at-eol)))
12566 ts))))))
12568 (defvar org-log-note-marker (make-marker))
12569 (defvar org-log-note-purpose nil)
12570 (defvar org-log-note-state nil)
12571 (defvar org-log-note-previous-state nil)
12572 (defvar org-log-note-how nil)
12573 (defvar org-log-note-extra nil)
12574 (defvar org-log-note-window-configuration nil)
12575 (defvar org-log-note-return-to (make-marker))
12576 (defvar org-log-note-effective-time nil
12577 "Remembered current time so that dynamically scoped
12578 `org-extend-today-until' affects tha timestamps in state change
12579 log")
12581 (defvar org-log-post-message nil
12582 "Message to be displayed after a log note has been stored.
12583 The auto-repeater uses this.")
12585 (defun org-add-note ()
12586 "Add a note to the current entry.
12587 This is done in the same way as adding a state change note."
12588 (interactive)
12589 (org-add-log-setup 'note nil nil 'findpos nil))
12591 (defvar org-property-end-re)
12592 (defun org-add-log-setup (&optional purpose state prev-state
12593 findpos how extra)
12594 "Set up the post command hook to take a note.
12595 If this is about to TODO state change, the new state is expected in STATE.
12596 When FINDPOS is non-nil, find the correct position for the note in
12597 the current entry. If not, assume that it can be inserted at point.
12598 HOW is an indicator what kind of note should be created.
12599 EXTRA is additional text that will be inserted into the notes buffer."
12600 (let* ((org-log-into-drawer (org-log-into-drawer))
12601 (drawer (cond ((stringp org-log-into-drawer)
12602 org-log-into-drawer)
12603 (org-log-into-drawer "LOGBOOK"))))
12604 (save-restriction
12605 (save-excursion
12606 (when findpos
12607 (org-back-to-heading t)
12608 (narrow-to-region (point) (save-excursion
12609 (outline-next-heading) (point)))
12610 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12611 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12612 "[^\r\n]*\\)?"))
12613 (goto-char (match-end 0))
12614 (cond
12615 (drawer
12616 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12617 nil t)
12618 (progn
12619 (goto-char (match-end 0))
12620 (or org-log-states-order-reversed
12621 (and (re-search-forward org-property-end-re nil t)
12622 (goto-char (1- (match-beginning 0))))))
12623 (insert "\n:" drawer ":\n:END:")
12624 (beginning-of-line 0)
12625 (org-indent-line)
12626 (beginning-of-line 2)
12627 (org-indent-line)
12628 (end-of-line 0)))
12629 ((and org-log-state-notes-insert-after-drawers
12630 (save-excursion
12631 (forward-line) (looking-at org-drawer-regexp)))
12632 (forward-line)
12633 (while (looking-at org-drawer-regexp)
12634 (goto-char (match-end 0))
12635 (re-search-forward org-property-end-re (point-max) t)
12636 (forward-line))
12637 (forward-line -1)))
12638 (unless org-log-states-order-reversed
12639 (and (= (char-after) ?\n) (forward-char 1))
12640 (org-skip-over-state-notes)
12641 (skip-chars-backward " \t\n\r")))
12642 (move-marker org-log-note-marker (point))
12643 (setq org-log-note-purpose purpose
12644 org-log-note-state state
12645 org-log-note-previous-state prev-state
12646 org-log-note-how how
12647 org-log-note-extra extra
12648 org-log-note-effective-time (org-current-effective-time))
12649 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12651 (defun org-skip-over-state-notes ()
12652 "Skip past the list of State notes in an entry."
12653 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12654 (when (ignore-errors (goto-char (org-in-item-p)))
12655 (let* ((struct (org-list-struct))
12656 (prevs (org-list-prevs-alist struct)))
12657 (while (looking-at "[ \t]*- State")
12658 (goto-char (or (org-list-get-next-item (point) struct prevs)
12659 (org-list-get-item-end (point) struct)))))))
12661 (defun org-add-log-note (&optional purpose)
12662 "Pop up a window for taking a note, and add this note later at point."
12663 (remove-hook 'post-command-hook 'org-add-log-note)
12664 (setq org-log-note-window-configuration (current-window-configuration))
12665 (delete-other-windows)
12666 (move-marker org-log-note-return-to (point))
12667 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12668 (goto-char org-log-note-marker)
12669 (org-switch-to-buffer-other-window "*Org Note*")
12670 (erase-buffer)
12671 (if (memq org-log-note-how '(time state))
12672 (let (current-prefix-arg) (org-store-log-note))
12673 (let ((org-inhibit-startup t)) (org-mode))
12674 (insert (format "# Insert note for %s.
12675 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12676 (cond
12677 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12678 ((eq org-log-note-purpose 'done) "closed todo item")
12679 ((eq org-log-note-purpose 'state)
12680 (format "state change from \"%s\" to \"%s\""
12681 (or org-log-note-previous-state "")
12682 (or org-log-note-state "")))
12683 ((eq org-log-note-purpose 'reschedule)
12684 "rescheduling")
12685 ((eq org-log-note-purpose 'delschedule)
12686 "no longer scheduled")
12687 ((eq org-log-note-purpose 'redeadline)
12688 "changing deadline")
12689 ((eq org-log-note-purpose 'deldeadline)
12690 "removing deadline")
12691 ((eq org-log-note-purpose 'refile)
12692 "refiling")
12693 ((eq org-log-note-purpose 'note)
12694 "this entry")
12695 (t (error "This should not happen")))))
12696 (if org-log-note-extra (insert org-log-note-extra))
12697 (org-set-local 'org-finish-function 'org-store-log-note)
12698 (run-hooks 'org-log-buffer-setup-hook)))
12700 (defvar org-note-abort nil) ; dynamically scoped
12701 (defun org-store-log-note ()
12702 "Finish taking a log note, and insert it to where it belongs."
12703 (let ((txt (buffer-string))
12704 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12705 lines ind bul)
12706 (kill-buffer (current-buffer))
12707 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12708 (setq txt (replace-match "" t t txt)))
12709 (if (string-match "\\s-+\\'" txt)
12710 (setq txt (replace-match "" t t txt)))
12711 (setq lines (org-split-string txt "\n"))
12712 (when (and note (string-match "\\S-" note))
12713 (setq note
12714 (org-replace-escapes
12715 note
12716 (list (cons "%u" (user-login-name))
12717 (cons "%U" user-full-name)
12718 (cons "%t" (format-time-string
12719 (org-time-stamp-format 'long 'inactive)
12720 org-log-note-effective-time))
12721 (cons "%T" (format-time-string
12722 (org-time-stamp-format 'long nil)
12723 org-log-note-effective-time))
12724 (cons "%d" (format-time-string
12725 (org-time-stamp-format nil 'inactive)
12726 org-log-note-effective-time))
12727 (cons "%D" (format-time-string
12728 (org-time-stamp-format nil nil)
12729 org-log-note-effective-time))
12730 (cons "%s" (if org-log-note-state
12731 (concat "\"" org-log-note-state "\"")
12732 ""))
12733 (cons "%S" (if org-log-note-previous-state
12734 (concat "\"" org-log-note-previous-state "\"")
12735 "\"\"")))))
12736 (if lines (setq note (concat note " \\\\")))
12737 (push note lines))
12738 (when (or current-prefix-arg org-note-abort)
12739 (when org-log-into-drawer
12740 (org-remove-empty-drawer-at
12741 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12742 org-log-note-marker))
12743 (setq lines nil))
12744 (when lines
12745 (with-current-buffer (marker-buffer org-log-note-marker)
12746 (save-excursion
12747 (goto-char org-log-note-marker)
12748 (move-marker org-log-note-marker nil)
12749 (end-of-line 1)
12750 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12751 (setq ind (save-excursion
12752 (if (ignore-errors (goto-char (org-in-item-p)))
12753 (let ((struct (org-list-struct)))
12754 (org-list-get-ind
12755 (org-list-get-top-point struct) struct))
12756 (skip-chars-backward " \r\t\n")
12757 (cond
12758 ((and (org-at-heading-p)
12759 org-adapt-indentation)
12760 (1+ (org-current-level)))
12761 ((org-at-heading-p) 0)
12762 (t (org-get-indentation))))))
12763 (setq bul (org-list-bullet-string "-"))
12764 (org-indent-line-to ind)
12765 (insert bul (pop lines))
12766 (let ((ind-body (+ (length bul) ind)))
12767 (while lines
12768 (insert "\n")
12769 (org-indent-line-to ind-body)
12770 (insert (pop lines))))
12771 (message "Note stored")
12772 (org-back-to-heading t)
12773 (org-cycle-hide-drawers 'children)))))
12774 (set-window-configuration org-log-note-window-configuration)
12775 (with-current-buffer (marker-buffer org-log-note-return-to)
12776 (goto-char org-log-note-return-to))
12777 (move-marker org-log-note-return-to nil)
12778 (and org-log-post-message (message "%s" org-log-post-message)))
12780 (defun org-remove-empty-drawer-at (drawer pos)
12781 "Remove an empty drawer DRAWER at position POS.
12782 POS may also be a marker."
12783 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12784 (save-excursion
12785 (save-restriction
12786 (widen)
12787 (goto-char pos)
12788 (if (org-in-regexp
12789 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12790 (replace-match ""))))))
12792 (defvar org-ts-type nil)
12793 (defun org-sparse-tree (&optional arg type)
12794 "Create a sparse tree, prompt for the details.
12795 This command can create sparse trees. You first need to select the type
12796 of match used to create the tree:
12798 t Show all TODO entries.
12799 T Show entries with a specific TODO keyword.
12800 m Show entries selected by a tags/property match.
12801 p Enter a property name and its value (both with completion on existing
12802 names/values) and show entries with that property.
12803 r Show entries matching a regular expression (`/' can be used as well).
12804 b Show deadlines and scheduled items before a date.
12805 a Show deadlines and scheduled items after a date.
12806 d Show deadlines due within `org-deadline-warning-days'.
12807 D Show deadlines and scheduled items between a date range."
12808 (interactive "P")
12809 (let (ans kwd value ts-type)
12810 (setq type (or type org-sparse-tree-default-date-type))
12811 (setq org-ts-type type)
12812 (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"
12813 (cond ((eq type 'all) "all timestamps")
12814 ((eq type 'scheduled) "only scheduled")
12815 ((eq type 'deadline) "only deadline")
12816 ((eq type 'active) "only active timestamps")
12817 ((eq type 'inactive) "only inactive timestamps")
12818 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12819 (t "scheduled/deadline")))
12820 (setq ans (read-char-exclusive))
12821 (cond
12822 ((equal ans ?c)
12823 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12824 ((equal ans ?d)
12825 (call-interactively 'org-check-deadlines))
12826 ((equal ans ?b)
12827 (call-interactively 'org-check-before-date))
12828 ((equal ans ?a)
12829 (call-interactively 'org-check-after-date))
12830 ((equal ans ?D)
12831 (call-interactively 'org-check-dates-range))
12832 ((equal ans ?t)
12833 (org-show-todo-tree nil))
12834 ((equal ans ?T)
12835 (org-show-todo-tree '(4)))
12836 ((member ans '(?T ?m))
12837 (call-interactively 'org-match-sparse-tree))
12838 ((member ans '(?p ?P))
12839 (setq kwd (org-icompleting-read "Property: "
12840 (mapcar 'list (org-buffer-property-keys))))
12841 (setq value (org-icompleting-read "Value: "
12842 (mapcar 'list (org-property-values kwd))))
12843 (unless (string-match "\\`{.*}\\'" value)
12844 (setq value (concat "\"" value "\"")))
12845 (org-match-sparse-tree arg (concat kwd "=" value)))
12846 ((member ans '(?r ?R ?/))
12847 (call-interactively 'org-occur))
12848 (t (error "No such sparse tree command \"%c\"" ans)))))
12850 (defvar org-occur-highlights nil
12851 "List of overlays used for occur matches.")
12852 (make-variable-buffer-local 'org-occur-highlights)
12853 (defvar org-occur-parameters nil
12854 "Parameters of the active org-occur calls.
12855 This is a list, each call to org-occur pushes as cons cell,
12856 containing the regular expression and the callback, onto the list.
12857 The list can contain several entries if `org-occur' has been called
12858 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12859 will only contain one set of parameters. When the highlights are
12860 removed (for example with `C-c C-c', or with the next edit (depending
12861 on `org-remove-highlights-with-change'), this variable is emptied
12862 as well.")
12863 (make-variable-buffer-local 'org-occur-parameters)
12865 (defun org-occur (regexp &optional keep-previous callback)
12866 "Make a compact tree which shows all matches of REGEXP.
12867 The tree will show the lines where the regexp matches, and all higher
12868 headlines above the match. It will also show the heading after the match,
12869 to make sure editing the matching entry is easy.
12870 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12871 call to `org-occur' will be kept, to allow stacking of calls to this
12872 command.
12873 If CALLBACK is non-nil, it is a function which is called to confirm
12874 that the match should indeed be shown."
12875 (interactive "sRegexp: \nP")
12876 (when (equal regexp "")
12877 (error "Regexp cannot be empty"))
12878 (unless keep-previous
12879 (org-remove-occur-highlights nil nil t))
12880 (push (cons regexp callback) org-occur-parameters)
12881 (let ((cnt 0))
12882 (save-excursion
12883 (goto-char (point-min))
12884 (if (or (not keep-previous) ; do not want to keep
12885 (not org-occur-highlights)) ; no previous matches
12886 ;; hide everything
12887 (org-overview))
12888 (while (re-search-forward regexp nil t)
12889 (when (or (not callback)
12890 (save-match-data (funcall callback)))
12891 (setq cnt (1+ cnt))
12892 (when org-highlight-sparse-tree-matches
12893 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12894 (org-show-context 'occur-tree))))
12895 (when org-remove-highlights-with-change
12896 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12897 nil 'local))
12898 (unless org-sparse-tree-open-archived-trees
12899 (org-hide-archived-subtrees (point-min) (point-max)))
12900 (run-hooks 'org-occur-hook)
12901 (if (org-called-interactively-p 'interactive)
12902 (message "%d match(es) for regexp %s" cnt regexp))
12903 cnt))
12905 (defun org-occur-next-match (&optional n reset)
12906 "Function for `next-error-function' to find sparse tree matches.
12907 N is the number of matches to move, when negative move backwards.
12908 RESET is entirely ignored - this function always goes back to the
12909 starting point when no match is found."
12910 (let* ((limit (if (< n 0) (point-min) (point-max)))
12911 (search-func (if (< n 0)
12912 'previous-single-char-property-change
12913 'next-single-char-property-change))
12914 (n (abs n))
12915 (pos (point))
12917 (catch 'exit
12918 (while (setq p1 (funcall search-func (point) 'org-type))
12919 (when (equal p1 limit)
12920 (goto-char pos)
12921 (error "No more matches"))
12922 (when (equal (get-char-property p1 'org-type) 'org-occur)
12923 (setq n (1- n))
12924 (when (= n 0)
12925 (goto-char p1)
12926 (throw 'exit (point))))
12927 (goto-char p1))
12928 (goto-char p1)
12929 (error "No more matches"))))
12931 (defun org-show-context (&optional key)
12932 "Make sure point and context are visible.
12933 How much context is shown depends upon the variables
12934 `org-show-hierarchy-above', `org-show-following-heading',
12935 `org-show-entry-below' and `org-show-siblings'."
12936 (let ((heading-p (org-at-heading-p t))
12937 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12938 (following-p (org-get-alist-option org-show-following-heading key))
12939 (entry-p (org-get-alist-option org-show-entry-below key))
12940 (siblings-p (org-get-alist-option org-show-siblings key)))
12941 (catch 'exit
12942 ;; Show heading or entry text
12943 (if (and heading-p (not entry-p))
12944 (org-flag-heading nil) ; only show the heading
12945 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12946 (org-show-hidden-entry))) ; show entire entry
12947 (when following-p
12948 ;; Show next sibling, or heading below text
12949 (save-excursion
12950 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12951 (org-flag-heading nil))))
12952 (when siblings-p (org-show-siblings))
12953 (when hierarchy-p
12954 ;; show all higher headings, possibly with siblings
12955 (save-excursion
12956 (while (and (condition-case nil
12957 (progn (org-up-heading-all 1) t)
12958 (error nil))
12959 (not (bobp)))
12960 (org-flag-heading nil)
12961 (when siblings-p (org-show-siblings))))))))
12963 (defvar org-reveal-start-hook nil
12964 "Hook run before revealing a location.")
12966 (defun org-reveal (&optional siblings)
12967 "Show current entry, hierarchy above it, and the following headline.
12968 This can be used to show a consistent set of context around locations
12969 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12970 not t for the search context.
12972 With optional argument SIBLINGS, on each level of the hierarchy all
12973 siblings are shown. This repairs the tree structure to what it would
12974 look like when opened with hierarchical calls to `org-cycle'.
12975 With double optional argument \\[universal-argument] \\[universal-argument], \
12976 go to the parent and show the
12977 entire tree."
12978 (interactive "P")
12979 (run-hooks 'org-reveal-start-hook)
12980 (let ((org-show-hierarchy-above t)
12981 (org-show-following-heading t)
12982 (org-show-siblings (if siblings t org-show-siblings)))
12983 (org-show-context nil))
12984 (when (equal siblings '(16))
12985 (save-excursion
12986 (when (org-up-heading-safe)
12987 (org-show-subtree)
12988 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12990 (defun org-highlight-new-match (beg end)
12991 "Highlight from BEG to END and mark the highlight is an occur headline."
12992 (let ((ov (make-overlay beg end)))
12993 (overlay-put ov 'face 'secondary-selection)
12994 (overlay-put ov 'org-type 'org-occur)
12995 (push ov org-occur-highlights)))
12997 (defun org-remove-occur-highlights (&optional beg end noremove)
12998 "Remove the occur highlights from the buffer.
12999 BEG and END are ignored. If NOREMOVE is nil, remove this function
13000 from the `before-change-functions' in the current buffer."
13001 (interactive)
13002 (unless org-inhibit-highlight-removal
13003 (mapc 'delete-overlay org-occur-highlights)
13004 (setq org-occur-highlights nil)
13005 (setq org-occur-parameters nil)
13006 (unless noremove
13007 (remove-hook 'before-change-functions
13008 'org-remove-occur-highlights 'local))))
13010 ;;;; Priorities
13012 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13013 "Regular expression matching the priority indicator.")
13015 (defvar org-remove-priority-next-time nil)
13017 (defun org-priority-up ()
13018 "Increase the priority of the current item."
13019 (interactive)
13020 (org-priority 'up))
13022 (defun org-priority-down ()
13023 "Decrease the priority of the current item."
13024 (interactive)
13025 (org-priority 'down))
13027 (defun org-priority (&optional action)
13028 "Change the priority of an item.
13029 ACTION can be `set', `up', `down', or a character."
13030 (interactive)
13031 (unless org-enable-priority-commands
13032 (error "Priority commands are disabled"))
13033 (setq action (or action 'set))
13034 (let (current new news have remove)
13035 (save-excursion
13036 (org-back-to-heading t)
13037 (if (looking-at org-priority-regexp)
13038 (setq current (string-to-char (match-string 2))
13039 have t))
13040 (cond
13041 ((eq action 'remove)
13042 (setq remove t new ?\ ))
13043 ((or (eq action 'set)
13044 (if (featurep 'xemacs) (characterp action) (integerp action)))
13045 (if (not (eq action 'set))
13046 (setq new action)
13047 (message "Priority %c-%c, SPC to remove: "
13048 org-highest-priority org-lowest-priority)
13049 (save-match-data
13050 (setq new (read-char-exclusive))))
13051 (if (and (= (upcase org-highest-priority) org-highest-priority)
13052 (= (upcase org-lowest-priority) org-lowest-priority))
13053 (setq new (upcase new)))
13054 (cond ((equal new ?\ ) (setq remove t))
13055 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13056 (error "Priority must be between `%c' and `%c'"
13057 org-highest-priority org-lowest-priority))))
13058 ((eq action 'up)
13059 (setq new (if have
13060 (1- current) ; normal cycling
13061 ;; last priority was empty
13062 (if (eq last-command this-command)
13063 org-lowest-priority ; wrap around empty to lowest
13064 ;; default
13065 (if org-priority-start-cycle-with-default
13066 org-default-priority
13067 (1- org-default-priority))))))
13068 ((eq action 'down)
13069 (setq new (if have
13070 (1+ current) ; normal cycling
13071 ;; last priority was empty
13072 (if (eq last-command this-command)
13073 org-highest-priority ; wrap around empty to highest
13074 ;; default
13075 (if org-priority-start-cycle-with-default
13076 org-default-priority
13077 (1+ org-default-priority))))))
13078 (t (error "Invalid action")))
13079 (if (or (< (upcase new) org-highest-priority)
13080 (> (upcase new) org-lowest-priority))
13081 (if (and (memq action '(up down))
13082 (not have) (not (eq last-command this-command)))
13083 ;; `new' is from default priority
13084 (error
13085 "The default can not be set, see `org-default-priority' why")
13086 ;; normal cycling: `new' is beyond highest/lowest priority
13087 ;; and is wrapped around to the empty priority
13088 (setq remove t)))
13089 (setq news (format "%c" new))
13090 (if have
13091 (if remove
13092 (replace-match "" t t nil 1)
13093 (replace-match news t t nil 2))
13094 (if remove
13095 (error "No priority cookie found in line")
13096 (let ((case-fold-search nil))
13097 (looking-at org-todo-line-regexp))
13098 (if (match-end 2)
13099 (progn
13100 (goto-char (match-end 2))
13101 (insert " [#" news "]"))
13102 (goto-char (match-beginning 3))
13103 (insert "[#" news "] "))))
13104 (org-preserve-lc (org-set-tags nil 'align)))
13105 (if remove
13106 (message "Priority removed")
13107 (message "Priority of current item set to %s" news))))
13109 (defun org-get-priority (s)
13110 "Find priority cookie and return priority."
13111 (if (functionp org-get-priority-function)
13112 (funcall org-get-priority-function)
13113 (save-match-data
13114 (if (not (string-match org-priority-regexp s))
13115 (* 1000 (- org-lowest-priority org-default-priority))
13116 (* 1000 (- org-lowest-priority
13117 (string-to-char (match-string 2 s))))))))
13119 ;;;; Tags
13121 (defvar org-agenda-archives-mode)
13122 (defvar org-map-continue-from nil
13123 "Position from where mapping should continue.
13124 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13126 (defvar org-scanner-tags nil
13127 "The current tag list while the tags scanner is running.")
13128 (defvar org-trust-scanner-tags nil
13129 "Should `org-get-tags-at' use the tags for the scanner.
13130 This is for internal dynamical scoping only.
13131 When this is non-nil, the function `org-get-tags-at' will return the value
13132 of `org-scanner-tags' instead of building the list by itself. This
13133 can lead to large speed-ups when the tags scanner is used in a file with
13134 many entries, and when the list of tags is retrieved, for example to
13135 obtain a list of properties. Building the tags list for each entry in such
13136 a file becomes an N^2 operation - but with this variable set, it scales
13137 as N.")
13139 (defun org-scan-tags (action matcher todo-only &optional start-level)
13140 "Scan headline tags with inheritance and produce output ACTION.
13142 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13143 or `agenda' to produce an entry list for an agenda view. It can also be
13144 a Lisp form or a function that should be called at each matched headline, in
13145 this case the return value is a list of all return values from these calls.
13147 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13148 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13149 only lines with a not-done TODO keyword are included in the output.
13150 This should be the same variable that was scoped into
13151 and set by `org-make-tags-matcher' when it constructed MATCHER.
13153 START-LEVEL can be a string with asterisks, reducing the scope to
13154 headlines matching this string."
13155 (require 'org-agenda)
13156 (let* ((re (concat "^"
13157 (if start-level
13158 ;; Get the correct level to match
13159 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13160 org-outline-regexp)
13161 " *\\(\\<\\("
13162 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13163 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13164 (props (list 'face 'default
13165 'done-face 'org-agenda-done
13166 'undone-face 'default
13167 'mouse-face 'highlight
13168 'org-not-done-regexp org-not-done-regexp
13169 'org-todo-regexp org-todo-regexp
13170 'org-complex-heading-regexp org-complex-heading-regexp
13171 'help-echo
13172 (format "mouse-2 or RET jump to org file %s"
13173 (abbreviate-file-name
13174 (or (buffer-file-name (buffer-base-buffer))
13175 (buffer-name (buffer-base-buffer)))))))
13176 (case-fold-search nil)
13177 (org-map-continue-from nil)
13178 lspos tags tags-list
13179 (tags-alist (list (cons 0 org-file-tags)))
13180 (llast 0) rtn rtn1 level category i txt
13181 todo marker entry priority)
13182 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13183 (setq action (list 'lambda nil action)))
13184 (save-excursion
13185 (goto-char (point-min))
13186 (when (eq action 'sparse-tree)
13187 (org-overview)
13188 (org-remove-occur-highlights))
13189 (while (re-search-forward re nil t)
13190 (setq org-map-continue-from nil)
13191 (catch :skip
13192 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13193 tags (if (match-end 4) (org-match-string-no-properties 4)))
13194 (goto-char (setq lspos (match-beginning 0)))
13195 (setq level (org-reduced-level (funcall outline-level))
13196 category (org-get-category))
13197 (setq i llast llast level)
13198 ;; remove tag lists from same and sublevels
13199 (while (>= i level)
13200 (when (setq entry (assoc i tags-alist))
13201 (setq tags-alist (delete entry tags-alist)))
13202 (setq i (1- i)))
13203 ;; add the next tags
13204 (when tags
13205 (setq tags (org-split-string tags ":")
13206 tags-alist
13207 (cons (cons level tags) tags-alist)))
13208 ;; compile tags for current headline
13209 (setq tags-list
13210 (if org-use-tag-inheritance
13211 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13212 tags)
13213 org-scanner-tags tags-list)
13214 (when org-use-tag-inheritance
13215 (setcdr (car tags-alist)
13216 (mapcar (lambda (x)
13217 (setq x (copy-sequence x))
13218 (org-add-prop-inherited x))
13219 (cdar tags-alist))))
13220 (when (and tags org-use-tag-inheritance
13221 (or (not (eq t org-use-tag-inheritance))
13222 org-tags-exclude-from-inheritance))
13223 ;; selective inheritance, remove uninherited ones
13224 (setcdr (car tags-alist)
13225 (org-remove-uninherited-tags (cdar tags-alist))))
13226 (when (and
13228 ;; eval matcher only when the todo condition is OK
13229 (and (or (not todo-only) (member todo org-not-done-keywords))
13230 (let ((case-fold-search t) (org-trust-scanner-tags t))
13231 (eval matcher)))
13233 ;; Call the skipper, but return t if it does not skip,
13234 ;; so that the `and' form continues evaluating
13235 (progn
13236 (unless (eq action 'sparse-tree) (org-agenda-skip))
13239 ;; Check if timestamps are deselecting this entry
13240 (or (not todo-only)
13241 (and (member todo org-not-done-keywords)
13242 (or (not org-agenda-tags-todo-honor-ignore-options)
13243 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13245 ;; Extra check for the archive tag
13246 ;; FIXME: Does the skipper already do this????
13248 (not (member org-archive-tag tags-list))
13249 ;; we have an archive tag, should we use this anyway?
13250 (or (not org-agenda-skip-archived-trees)
13251 (and (eq action 'agenda) org-agenda-archives-mode))))
13253 ;; select this headline
13255 (cond
13256 ((eq action 'sparse-tree)
13257 (and org-highlight-sparse-tree-matches
13258 (org-get-heading) (match-end 0)
13259 (org-highlight-new-match
13260 (match-beginning 1) (match-end 1)))
13261 (org-show-context 'tags-tree))
13262 ((eq action 'agenda)
13263 (setq txt (org-agenda-format-item
13265 (concat
13266 (if (eq org-tags-match-list-sublevels 'indented)
13267 (make-string (1- level) ?.) "")
13268 (org-get-heading))
13269 category
13270 tags-list)
13271 priority (org-get-priority txt))
13272 (goto-char lspos)
13273 (setq marker (org-agenda-new-marker))
13274 (org-add-props txt props
13275 'org-marker marker 'org-hd-marker marker 'org-category category
13276 'todo-state todo
13277 'priority priority 'type "tagsmatch")
13278 (push txt rtn))
13279 ((functionp action)
13280 (setq org-map-continue-from nil)
13281 (save-excursion
13282 (setq rtn1 (funcall action))
13283 (push rtn1 rtn)))
13284 (t (error "Invalid action")))
13286 ;; if we are to skip sublevels, jump to end of subtree
13287 (unless org-tags-match-list-sublevels
13288 (org-end-of-subtree t)
13289 (backward-char 1))))
13290 ;; Get the correct position from where to continue
13291 (if org-map-continue-from
13292 (goto-char org-map-continue-from)
13293 (and (= (point) lspos) (end-of-line 1)))))
13294 (when (and (eq action 'sparse-tree)
13295 (not org-sparse-tree-open-archived-trees))
13296 (org-hide-archived-subtrees (point-min) (point-max)))
13297 (nreverse rtn)))
13299 (defun org-remove-uninherited-tags (tags)
13300 "Remove all tags that are not inherited from the list TAGS."
13301 (cond
13302 ((eq org-use-tag-inheritance t)
13303 (if org-tags-exclude-from-inheritance
13304 (org-delete-all org-tags-exclude-from-inheritance tags)
13305 tags))
13306 ((not org-use-tag-inheritance) nil)
13307 ((stringp org-use-tag-inheritance)
13308 (delq nil (mapcar
13309 (lambda (x)
13310 (if (and (string-match org-use-tag-inheritance x)
13311 (not (member x org-tags-exclude-from-inheritance)))
13312 x nil))
13313 tags)))
13314 ((listp org-use-tag-inheritance)
13315 (delq nil (mapcar
13316 (lambda (x)
13317 (if (member x org-use-tag-inheritance) x nil))
13318 tags)))))
13320 (defun org-match-sparse-tree (&optional todo-only match)
13321 "Create a sparse tree according to tags string MATCH.
13322 MATCH can contain positive and negative selection of tags, like
13323 \"+WORK+URGENT-WITHBOSS\".
13324 If optional argument TODO-ONLY is non-nil, only select lines that are
13325 also TODO lines."
13326 (interactive "P")
13327 (org-agenda-prepare-buffers (list (current-buffer)))
13328 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13330 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13332 (defvar org-cached-props nil)
13333 (defun org-cached-entry-get (pom property)
13334 (if (or (eq t org-use-property-inheritance)
13335 (and (stringp org-use-property-inheritance)
13336 (string-match org-use-property-inheritance property))
13337 (and (listp org-use-property-inheritance)
13338 (member property org-use-property-inheritance)))
13339 ;; Caching is not possible, check it directly
13340 (org-entry-get pom property 'inherit)
13341 ;; Get all properties, so that we can do complicated checks easily
13342 (cdr (assoc property (or org-cached-props
13343 (setq org-cached-props
13344 (org-entry-properties pom)))))))
13346 (defun org-global-tags-completion-table (&optional files)
13347 "Return the list of all tags in all agenda buffer/files.
13348 Optional FILES argument is a list of files which can be used
13349 instead of the agenda files."
13350 (save-excursion
13351 (org-uniquify
13352 (delq nil
13353 (apply 'append
13354 (mapcar
13355 (lambda (file)
13356 (set-buffer (find-file-noselect file))
13357 (append (org-get-buffer-tags)
13358 (mapcar (lambda (x) (if (stringp (car-safe x))
13359 (list (car-safe x)) nil))
13360 org-tag-alist)))
13361 (if (and files (car files))
13362 files
13363 (org-agenda-files))))))))
13365 (defun org-make-tags-matcher (match)
13366 "Create the TAGS/TODO matcher form for the selection string MATCH.
13368 The variable `todo-only' is scoped dynamically into this function.
13369 It will be set to t if the matcher restricts matching to TODO entries,
13370 otherwise will not be touched.
13372 Returns a cons of the selection string MATCH and the constructed
13373 lisp form implementing the matcher. The matcher is to be evaluated
13374 at an Org entry, with point on the headline, and returns t if the
13375 entry matches the selection string MATCH. The returned lisp form
13376 references two variables with information about the entry, which
13377 must be bound around the form's evaluation: todo, the TODO keyword
13378 at the entry (or nil of none); and tags-list, the list of all tags
13379 at the entry including inherited ones. Additionally, the category
13380 of the entry (if any) must be specified as the text property
13381 'org-category on the headline.
13383 See also `org-scan-tags'.
13385 (declare (special todo-only))
13386 (unless (boundp 'todo-only)
13387 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13388 (unless match
13389 ;; Get a new match request, with completion
13390 (let ((org-last-tags-completion-table
13391 (org-global-tags-completion-table)))
13392 (setq match (org-completing-read-no-i
13393 "Match: " 'org-tags-completion-function nil nil nil
13394 'org-tags-history))))
13396 ;; Parse the string and create a lisp form
13397 (let ((match0 match)
13398 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13399 minus tag mm
13400 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13401 orterms term orlist re-p str-p level-p level-op time-p
13402 prop-p pn pv po gv rest)
13403 (if (string-match "/+" match)
13404 ;; match contains also a todo-matching request
13405 (progn
13406 (setq tagsmatch (substring match 0 (match-beginning 0))
13407 todomatch (substring match (match-end 0)))
13408 (if (string-match "^!" todomatch)
13409 (setq todo-only t todomatch (substring todomatch 1)))
13410 (if (string-match "^\\s-*$" todomatch)
13411 (setq todomatch nil)))
13412 ;; only matching tags
13413 (setq tagsmatch match todomatch nil))
13415 ;; Make the tags matcher
13416 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13417 (setq tagsmatcher t)
13418 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13419 (while (setq term (pop orterms))
13420 (while (and (equal (substring term -1) "\\") orterms)
13421 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13422 (while (string-match re term)
13423 (setq rest (substring term (match-end 0))
13424 minus (and (match-end 1)
13425 (equal (match-string 1 term) "-"))
13426 tag (save-match-data (replace-regexp-in-string
13427 "\\\\-" "-"
13428 (match-string 2 term)))
13429 re-p (equal (string-to-char tag) ?{)
13430 level-p (match-end 4)
13431 prop-p (match-end 5)
13432 mm (cond
13433 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13434 (level-p
13435 (setq level-op (org-op-to-function (match-string 3 term)))
13436 `(,level-op level ,(string-to-number
13437 (match-string 4 term))))
13438 (prop-p
13439 (setq pn (match-string 5 term)
13440 po (match-string 6 term)
13441 pv (match-string 7 term)
13442 re-p (equal (string-to-char pv) ?{)
13443 str-p (equal (string-to-char pv) ?\")
13444 time-p (save-match-data
13445 (string-match "^\"[[<].*[]>]\"$" pv))
13446 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13447 (if time-p (setq pv (org-matcher-time pv)))
13448 (setq po (org-op-to-function po (if time-p 'time str-p)))
13449 (cond
13450 ((equal pn "CATEGORY")
13451 (setq gv '(get-text-property (point) 'org-category)))
13452 ((equal pn "TODO")
13453 (setq gv 'todo))
13455 (setq gv `(org-cached-entry-get nil ,pn))))
13456 (if re-p
13457 (if (eq po 'org<>)
13458 `(not (string-match ,pv (or ,gv "")))
13459 `(string-match ,pv (or ,gv "")))
13460 (if str-p
13461 `(,po (or ,gv "") ,pv)
13462 `(,po (string-to-number (or ,gv ""))
13463 ,(string-to-number pv) ))))
13464 (t `(member ,tag tags-list)))
13465 mm (if minus (list 'not mm) mm)
13466 term rest)
13467 (push mm tagsmatcher))
13468 (push (if (> (length tagsmatcher) 1)
13469 (cons 'and tagsmatcher)
13470 (car tagsmatcher))
13471 orlist)
13472 (setq tagsmatcher nil))
13473 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13474 (setq tagsmatcher
13475 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13476 ;; Make the todo matcher
13477 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13478 (setq todomatcher t)
13479 (setq orterms (org-split-string todomatch "|") orlist nil)
13480 (while (setq term (pop orterms))
13481 (while (string-match re term)
13482 (setq minus (and (match-end 1)
13483 (equal (match-string 1 term) "-"))
13484 kwd (match-string 2 term)
13485 re-p (equal (string-to-char kwd) ?{)
13486 term (substring term (match-end 0))
13487 mm (if re-p
13488 `(string-match ,(substring kwd 1 -1) todo)
13489 (list 'equal 'todo kwd))
13490 mm (if minus (list 'not mm) mm))
13491 (push mm todomatcher))
13492 (push (if (> (length todomatcher) 1)
13493 (cons 'and todomatcher)
13494 (car todomatcher))
13495 orlist)
13496 (setq todomatcher nil))
13497 (setq todomatcher (if (> (length orlist) 1)
13498 (cons 'or orlist) (car orlist))))
13500 ;; Return the string and lisp forms of the matcher
13501 (setq matcher (if todomatcher
13502 (list 'and tagsmatcher todomatcher)
13503 tagsmatcher))
13504 (when todo-only
13505 (setq matcher (list 'and '(member todo org-not-done-keywords)
13506 matcher)))
13507 (cons match0 matcher)))
13509 (defun org-op-to-function (op &optional stringp)
13510 "Turn an operator into the appropriate function."
13511 (setq op
13512 (cond
13513 ((equal op "<" ) '(< string< org-time<))
13514 ((equal op ">" ) '(> org-string> org-time>))
13515 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13516 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13517 ((member op '("=" "==")) '(= string= org-time=))
13518 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13519 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13521 (defun org<> (a b) (not (= a b)))
13522 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13523 (defun org-string>= (a b) (not (string< a b)))
13524 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13525 (defun org-string<> (a b) (not (string= a b)))
13526 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13527 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13528 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13529 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13530 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13531 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13532 (defun org-2ft (s)
13533 "Convert S to a floating point time.
13534 If S is already a number, just return it. If it is a string, parse
13535 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13536 (cond
13537 ((numberp s) s)
13538 ((stringp s)
13539 (condition-case nil
13540 (float-time (apply 'encode-time (org-parse-time-string s)))
13541 (error 0.)))
13542 (t 0.)))
13544 (defun org-time-today ()
13545 "Time in seconds today at 0:00.
13546 Returns the float number of seconds since the beginning of the
13547 epoch to the beginning of today (00:00)."
13548 (float-time (apply 'encode-time
13549 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13551 (defun org-matcher-time (s)
13552 "Interpret a time comparison value."
13553 (save-match-data
13554 (cond
13555 ((string= s "<now>") (float-time))
13556 ((string= s "<today>") (org-time-today))
13557 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13558 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13559 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13560 (+ (org-time-today)
13561 (* (string-to-number (match-string 1 s))
13562 (cdr (assoc (match-string 2 s)
13563 '(("d" . 86400.0) ("w" . 604800.0)
13564 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13565 (t (org-2ft s)))))
13567 (defun org-match-any-p (re list)
13568 "Does re match any element of list?"
13569 (setq list (mapcar (lambda (x) (string-match re x)) list))
13570 (delq nil list))
13572 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13573 (defvar org-tags-overlay (make-overlay 1 1))
13574 (org-detach-overlay org-tags-overlay)
13576 (defun org-get-local-tags-at (&optional pos)
13577 "Get a list of tags defined in the current headline."
13578 (org-get-tags-at pos 'local))
13580 (defun org-get-local-tags ()
13581 "Get a list of tags defined in the current headline."
13582 (org-get-tags-at nil 'local))
13584 (defun org-get-tags-at (&optional pos local)
13585 "Get a list of all headline tags applicable at POS.
13586 POS defaults to point. If tags are inherited, the list contains
13587 the targets in the same sequence as the headlines appear, i.e.
13588 the tags of the current headline come last.
13589 When LOCAL is non-nil, only return tags from the current headline,
13590 ignore inherited ones."
13591 (interactive)
13592 (if (and org-trust-scanner-tags
13593 (or (not pos) (equal pos (point)))
13594 (not local))
13595 org-scanner-tags
13596 (let (tags ltags lastpos parent)
13597 (save-excursion
13598 (save-restriction
13599 (widen)
13600 (goto-char (or pos (point)))
13601 (save-match-data
13602 (catch 'done
13603 (condition-case nil
13604 (progn
13605 (org-back-to-heading t)
13606 (while (not (equal lastpos (point)))
13607 (setq lastpos (point))
13608 (when (looking-at
13609 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13610 (setq ltags (org-split-string
13611 (org-match-string-no-properties 1) ":"))
13612 (when parent
13613 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13614 (setq tags (append
13615 (if parent
13616 (org-remove-uninherited-tags ltags)
13617 ltags)
13618 tags)))
13619 (or org-use-tag-inheritance (throw 'done t))
13620 (if local (throw 'done t))
13621 (or (org-up-heading-safe) (error nil))
13622 (setq parent t)))
13623 (error nil)))))
13624 (if local
13625 tags
13626 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13628 (defun org-add-prop-inherited (s)
13629 (add-text-properties 0 (length s) '(inherited t) s)
13632 (defun org-toggle-tag (tag &optional onoff)
13633 "Toggle the tag TAG for the current line.
13634 If ONOFF is `on' or `off', don't toggle but set to this state."
13635 (let (res current)
13636 (save-excursion
13637 (org-back-to-heading t)
13638 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13639 (point-at-eol) t)
13640 (progn
13641 (setq current (match-string 1))
13642 (replace-match ""))
13643 (setq current ""))
13644 (setq current (nreverse (org-split-string current ":")))
13645 (cond
13646 ((eq onoff 'on)
13647 (setq res t)
13648 (or (member tag current) (push tag current)))
13649 ((eq onoff 'off)
13650 (or (not (member tag current)) (setq current (delete tag current))))
13651 (t (if (member tag current)
13652 (setq current (delete tag current))
13653 (setq res t)
13654 (push tag current))))
13655 (end-of-line 1)
13656 (if current
13657 (progn
13658 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13659 (org-set-tags nil t))
13660 (delete-horizontal-space))
13661 (run-hooks 'org-after-tags-change-hook))
13662 res))
13664 (defun org-align-tags-here (to-col)
13665 ;; Assumes that this is a headline
13666 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13667 (beginning-of-line 1)
13668 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13669 (< pos (match-beginning 2)))
13670 (progn
13671 (setq tags-l (- (match-end 2) (match-beginning 2)))
13672 (goto-char (match-beginning 1))
13673 (insert " ")
13674 (delete-region (point) (1+ (match-beginning 2)))
13675 (setq ncol (max (current-column)
13676 (1+ col)
13677 (if (> to-col 0)
13678 to-col
13679 (- (abs to-col) tags-l))))
13680 (setq p (point))
13681 (insert (make-string (- ncol (current-column)) ?\ ))
13682 (setq ncol (current-column))
13683 (when indent-tabs-mode (tabify p (point-at-eol)))
13684 (org-move-to-column (min ncol col) t))
13685 (goto-char pos))))
13687 (defun org-set-tags-command (&optional arg just-align)
13688 "Call the set-tags command for the current entry."
13689 (interactive "P")
13690 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13691 (org-set-tags arg just-align)
13692 (save-excursion
13693 (org-back-to-heading t)
13694 (org-set-tags arg just-align))))
13696 (defun org-set-tags-to (data)
13697 "Set the tags of the current entry to DATA, replacing the current tags.
13698 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13699 If DATA is nil or the empty string, any tags will be removed."
13700 (interactive "sTags: ")
13701 (setq data
13702 (cond
13703 ((eq data nil) "")
13704 ((equal data "") "")
13705 ((stringp data)
13706 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13707 ":"))
13708 ((listp data)
13709 (concat ":" (mapconcat 'identity data ":") ":"))))
13710 (when data
13711 (save-excursion
13712 (org-back-to-heading t)
13713 (when (looking-at org-complex-heading-regexp)
13714 (if (match-end 5)
13715 (progn
13716 (goto-char (match-beginning 5))
13717 (insert data)
13718 (delete-region (point) (point-at-eol))
13719 (org-set-tags nil 'align))
13720 (goto-char (point-at-eol))
13721 (insert " " data)
13722 (org-set-tags nil 'align)))
13723 (beginning-of-line 1)
13724 (if (looking-at ".*?\\([ \t]+\\)$")
13725 (delete-region (match-beginning 1) (match-end 1))))))
13727 (defun org-align-all-tags ()
13728 "Align the tags i all headings."
13729 (interactive)
13730 (save-excursion
13731 (or (ignore-errors (org-back-to-heading t))
13732 (outline-next-heading))
13733 (if (org-at-heading-p)
13734 (org-set-tags t)
13735 (message "No headings"))))
13737 (defvar org-indent-indentation-per-level)
13738 (defun org-set-tags (&optional arg just-align)
13739 "Set the tags for the current headline.
13740 With prefix ARG, realign all tags in headings in the current buffer."
13741 (interactive "P")
13742 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13743 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13744 'region-start-level 'region))
13745 org-loop-over-headlines-in-active-region)
13746 (org-map-entries
13747 ;; We don't use ARG and JUST-ALIGN here these args are not
13748 ;; useful when looping over headlines
13749 `(org-set-tags)
13750 org-loop-over-headlines-in-active-region
13751 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13752 (let* ((re org-outline-regexp-bol)
13753 (current (unless arg (org-get-tags-string)))
13754 (col (current-column))
13755 (org-setting-tags t)
13756 table current-tags inherited-tags ; computed below when needed
13757 tags p0 c0 c1 rpl di tc level)
13758 (if arg
13759 (save-excursion
13760 (goto-char (point-min))
13761 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13762 (while (re-search-forward re nil t)
13763 (org-set-tags nil t)
13764 (end-of-line 1)))
13765 (message "All tags realigned to column %d" org-tags-column))
13766 (if just-align
13767 (setq tags current)
13768 ;; Get a new set of tags from the user
13769 (save-excursion
13770 (setq table (append org-tag-persistent-alist
13771 (or org-tag-alist (org-get-buffer-tags))
13772 (and
13773 org-complete-tags-always-offer-all-agenda-tags
13774 (org-global-tags-completion-table
13775 (org-agenda-files))))
13776 org-last-tags-completion-table table
13777 current-tags (org-split-string current ":")
13778 inherited-tags (nreverse
13779 (nthcdr (length current-tags)
13780 (nreverse (org-get-tags-at))))
13781 tags
13782 (if (or (eq t org-use-fast-tag-selection)
13783 (and org-use-fast-tag-selection
13784 (delq nil (mapcar 'cdr table))))
13785 (org-fast-tag-selection
13786 current-tags inherited-tags table
13787 (if org-fast-tag-selection-include-todo
13788 org-todo-key-alist))
13789 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13790 (org-trim
13791 (org-icompleting-read "Tags: "
13792 'org-tags-completion-function
13793 nil nil current 'org-tags-history))))))
13794 (while (string-match "[-+&]+" tags)
13795 ;; No boolean logic, just a list
13796 (setq tags (replace-match ":" t t tags))))
13798 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13800 (if org-tags-sort-function
13801 (setq tags (mapconcat 'identity
13802 (sort (org-split-string
13803 tags (org-re "[^[:alnum:]_@#%]+"))
13804 org-tags-sort-function) ":")))
13806 (if (string-match "\\`[\t ]*\\'" tags)
13807 (setq tags "")
13808 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13809 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13811 ;; Insert new tags at the correct column
13812 (beginning-of-line 1)
13813 (setq level (or (and (looking-at org-outline-regexp)
13814 (- (match-end 0) (point) 1))
13816 (cond
13817 ((and (equal current "") (equal tags "")))
13818 ((re-search-forward
13819 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13820 (point-at-eol) t)
13821 (if (equal tags "")
13822 (setq rpl "")
13823 (goto-char (match-beginning 0))
13824 (setq c0 (current-column)
13825 ;; compute offset for the case of org-indent-mode active
13826 di (if org-indent-mode
13827 (* (1- org-indent-indentation-per-level) (1- level))
13829 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13830 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13831 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13832 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13833 (replace-match rpl t t)
13834 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13835 tags)
13836 (t (error "Tags alignment failed")))
13837 (org-move-to-column col)
13838 (unless just-align
13839 (run-hooks 'org-after-tags-change-hook))))))
13841 (defun org-change-tag-in-region (beg end tag off)
13842 "Add or remove TAG for each entry in the region.
13843 This works in the agenda, and also in an org-mode buffer."
13844 (interactive
13845 (list (region-beginning) (region-end)
13846 (let ((org-last-tags-completion-table
13847 (if (derived-mode-p 'org-mode)
13848 (org-get-buffer-tags)
13849 (org-global-tags-completion-table))))
13850 (org-icompleting-read
13851 "Tag: " 'org-tags-completion-function nil nil nil
13852 'org-tags-history))
13853 (progn
13854 (message "[s]et or [r]emove? ")
13855 (equal (read-char-exclusive) ?r))))
13856 (if (fboundp 'deactivate-mark) (deactivate-mark))
13857 (let ((agendap (equal major-mode 'org-agenda-mode))
13858 l1 l2 m buf pos newhead (cnt 0))
13859 (goto-char end)
13860 (setq l2 (1- (org-current-line)))
13861 (goto-char beg)
13862 (setq l1 (org-current-line))
13863 (loop for l from l1 to l2 do
13864 (org-goto-line l)
13865 (setq m (get-text-property (point) 'org-hd-marker))
13866 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13867 (and agendap m))
13868 (setq buf (if agendap (marker-buffer m) (current-buffer))
13869 pos (if agendap m (point)))
13870 (with-current-buffer buf
13871 (save-excursion
13872 (save-restriction
13873 (goto-char pos)
13874 (setq cnt (1+ cnt))
13875 (org-toggle-tag tag (if off 'off 'on))
13876 (setq newhead (org-get-heading)))))
13877 (and agendap (org-agenda-change-all-lines newhead m))))
13878 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13880 (defun org-tags-completion-function (string predicate &optional flag)
13881 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13882 (confirm (lambda (x) (stringp (car x)))))
13883 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13884 (setq s1 (match-string 1 string)
13885 s2 (match-string 2 string))
13886 (setq s1 "" s2 string))
13887 (cond
13888 ((eq flag nil)
13889 ;; try completion
13890 (setq rtn (try-completion s2 ctable confirm))
13891 (if (stringp rtn)
13892 (setq rtn
13893 (concat s1 s2 (substring rtn (length s2))
13894 (if (and org-add-colon-after-tag-completion
13895 (assoc rtn ctable))
13896 ":" ""))))
13897 rtn)
13898 ((eq flag t)
13899 ;; all-completions
13900 (all-completions s2 ctable confirm)
13902 ((eq flag 'lambda)
13903 ;; exact match?
13904 (assoc s2 ctable)))
13907 (defun org-fast-tag-insert (kwd tags face &optional end)
13908 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13909 (insert (format "%-12s" (concat kwd ":"))
13910 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13911 (or end "")))
13913 (defun org-fast-tag-show-exit (flag)
13914 (save-excursion
13915 (org-goto-line 3)
13916 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13917 (replace-match ""))
13918 (when flag
13919 (end-of-line 1)
13920 (org-move-to-column (- (window-width) 19) t)
13921 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13923 (defun org-set-current-tags-overlay (current prefix)
13924 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13925 (if (featurep 'xemacs)
13926 (org-overlay-display org-tags-overlay (concat prefix s)
13927 'secondary-selection)
13928 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13929 (org-overlay-display org-tags-overlay (concat prefix s)))))
13931 (defvar org-last-tag-selection-key nil)
13932 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13933 "Fast tag selection with single keys.
13934 CURRENT is the current list of tags in the headline, INHERITED is the
13935 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13936 possibly with grouping information. TODO-TABLE is a similar table with
13937 TODO keywords, should these have keys assigned to them.
13938 If the keys are nil, a-z are automatically assigned.
13939 Returns the new tags string, or nil to not change the current settings."
13940 (let* ((fulltable (append table todo-table))
13941 (maxlen (apply 'max (mapcar
13942 (lambda (x)
13943 (if (stringp (car x)) (string-width (car x)) 0))
13944 fulltable)))
13945 (buf (current-buffer))
13946 (expert (eq org-fast-tag-selection-single-key 'expert))
13947 (buffer-tags nil)
13948 (fwidth (+ maxlen 3 1 3))
13949 (ncol (/ (- (window-width) 4) fwidth))
13950 (i-face 'org-done)
13951 (c-face 'org-todo)
13952 tg cnt e c char c1 c2 ntable tbl rtn
13953 ov-start ov-end ov-prefix
13954 (exit-after-next org-fast-tag-selection-single-key)
13955 (done-keywords org-done-keywords)
13956 groups ingroup)
13957 (save-excursion
13958 (beginning-of-line 1)
13959 (if (looking-at
13960 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13961 (setq ov-start (match-beginning 1)
13962 ov-end (match-end 1)
13963 ov-prefix "")
13964 (setq ov-start (1- (point-at-eol))
13965 ov-end (1+ ov-start))
13966 (skip-chars-forward "^\n\r")
13967 (setq ov-prefix
13968 (concat
13969 (buffer-substring (1- (point)) (point))
13970 (if (> (current-column) org-tags-column)
13972 (make-string (- org-tags-column (current-column)) ?\ ))))))
13973 (move-overlay org-tags-overlay ov-start ov-end)
13974 (save-window-excursion
13975 (if expert
13976 (set-buffer (get-buffer-create " *Org tags*"))
13977 (delete-other-windows)
13978 (split-window-vertically)
13979 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13980 (erase-buffer)
13981 (org-set-local 'org-done-keywords done-keywords)
13982 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13983 (org-fast-tag-insert "Current" current c-face "\n\n")
13984 (org-fast-tag-show-exit exit-after-next)
13985 (org-set-current-tags-overlay current ov-prefix)
13986 (setq tbl fulltable char ?a cnt 0)
13987 (while (setq e (pop tbl))
13988 (cond
13989 ((equal (car e) :startgroup)
13990 (push '() groups) (setq ingroup t)
13991 (when (not (= cnt 0))
13992 (setq cnt 0)
13993 (insert "\n"))
13994 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13995 ((equal (car e) :endgroup)
13996 (setq ingroup nil cnt 0)
13997 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13998 ((equal e '(:newline))
13999 (when (not (= cnt 0))
14000 (setq cnt 0)
14001 (insert "\n")
14002 (setq e (car tbl))
14003 (while (equal (car tbl) '(:newline))
14004 (insert "\n")
14005 (setq tbl (cdr tbl)))))
14007 (setq tg (copy-sequence (car e)) c2 nil)
14008 (if (cdr e)
14009 (setq c (cdr e))
14010 ;; automatically assign a character.
14011 (setq c1 (string-to-char
14012 (downcase (substring
14013 tg (if (= (string-to-char tg) ?@) 1 0)))))
14014 (if (or (rassoc c1 ntable) (rassoc c1 table))
14015 (while (or (rassoc char ntable) (rassoc char table))
14016 (setq char (1+ char)))
14017 (setq c2 c1))
14018 (setq c (or c2 char)))
14019 (if ingroup (push tg (car groups)))
14020 (setq tg (org-add-props tg nil 'face
14021 (cond
14022 ((not (assoc tg table))
14023 (org-get-todo-face tg))
14024 ((member tg current) c-face)
14025 ((member tg inherited) i-face))))
14026 (if (and (= cnt 0) (not ingroup)) (insert " "))
14027 (insert "[" c "] " tg (make-string
14028 (- fwidth 4 (length tg)) ?\ ))
14029 (push (cons tg c) ntable)
14030 (when (= (setq cnt (1+ cnt)) ncol)
14031 (insert "\n")
14032 (if ingroup (insert " "))
14033 (setq cnt 0)))))
14034 (setq ntable (nreverse ntable))
14035 (insert "\n")
14036 (goto-char (point-min))
14037 (if (not expert) (org-fit-window-to-buffer))
14038 (setq rtn
14039 (catch 'exit
14040 (while t
14041 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14042 (if (not groups) "no " "")
14043 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14044 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14045 (setq org-last-tag-selection-key c)
14046 (cond
14047 ((= c ?\r) (throw 'exit t))
14048 ((= c ?!)
14049 (setq groups (not groups))
14050 (goto-char (point-min))
14051 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14052 ((= c ?\C-c)
14053 (if (not expert)
14054 (org-fast-tag-show-exit
14055 (setq exit-after-next (not exit-after-next)))
14056 (setq expert nil)
14057 (delete-other-windows)
14058 (set-window-buffer (split-window-vertically) " *Org tags*")
14059 (org-switch-to-buffer-other-window " *Org tags*")
14060 (org-fit-window-to-buffer)))
14061 ((or (= c ?\C-g)
14062 (and (= c ?q) (not (rassoc c ntable))))
14063 (org-detach-overlay org-tags-overlay)
14064 (setq quit-flag t))
14065 ((= c ?\ )
14066 (setq current nil)
14067 (if exit-after-next (setq exit-after-next 'now)))
14068 ((= c ?\t)
14069 (condition-case nil
14070 (setq tg (org-icompleting-read
14071 "Tag: "
14072 (or buffer-tags
14073 (with-current-buffer buf
14074 (org-get-buffer-tags)))))
14075 (quit (setq tg "")))
14076 (when (string-match "\\S-" tg)
14077 (add-to-list 'buffer-tags (list tg))
14078 (if (member tg current)
14079 (setq current (delete tg current))
14080 (push tg current)))
14081 (if exit-after-next (setq exit-after-next 'now)))
14082 ((setq e (rassoc c todo-table) tg (car e))
14083 (with-current-buffer buf
14084 (save-excursion (org-todo tg)))
14085 (if exit-after-next (setq exit-after-next 'now)))
14086 ((setq e (rassoc c ntable) tg (car e))
14087 (if (member tg current)
14088 (setq current (delete tg current))
14089 (loop for g in groups do
14090 (if (member tg g)
14091 (mapc (lambda (x)
14092 (setq current (delete x current)))
14093 g)))
14094 (push tg current))
14095 (if exit-after-next (setq exit-after-next 'now))))
14097 ;; Create a sorted list
14098 (setq current
14099 (sort current
14100 (lambda (a b)
14101 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14102 (if (eq exit-after-next 'now) (throw 'exit t))
14103 (goto-char (point-min))
14104 (beginning-of-line 2)
14105 (delete-region (point) (point-at-eol))
14106 (org-fast-tag-insert "Current" current c-face)
14107 (org-set-current-tags-overlay current ov-prefix)
14108 (while (re-search-forward
14109 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14110 (setq tg (match-string 1))
14111 (add-text-properties
14112 (match-beginning 1) (match-end 1)
14113 (list 'face
14114 (cond
14115 ((member tg current) c-face)
14116 ((member tg inherited) i-face)
14117 (t (get-text-property (match-beginning 1) 'face))))))
14118 (goto-char (point-min)))))
14119 (org-detach-overlay org-tags-overlay)
14120 (if rtn
14121 (mapconcat 'identity current ":")
14122 nil))))
14124 (defun org-get-tags-string ()
14125 "Get the TAGS string in the current headline."
14126 (unless (org-at-heading-p t)
14127 (error "Not on a heading"))
14128 (save-excursion
14129 (beginning-of-line 1)
14130 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14131 (org-match-string-no-properties 1)
14132 "")))
14134 (defun org-get-tags ()
14135 "Get the list of tags specified in the current headline."
14136 (org-split-string (org-get-tags-string) ":"))
14138 (defun org-get-buffer-tags ()
14139 "Get a table of all tags used in the buffer, for completion."
14140 (let (tags)
14141 (save-excursion
14142 (goto-char (point-min))
14143 (while (re-search-forward
14144 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14145 (when (equal (char-after (point-at-bol 0)) ?*)
14146 (mapc (lambda (x) (add-to-list 'tags x))
14147 (org-split-string (org-match-string-no-properties 1) ":")))))
14148 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14149 (mapcar 'list tags)))
14151 ;;;; The mapping API
14153 ;;;###autoload
14154 (defun org-map-entries (func &optional match scope &rest skip)
14155 "Call FUNC at each headline selected by MATCH in SCOPE.
14157 FUNC is a function or a lisp form. The function will be called without
14158 arguments, with the cursor positioned at the beginning of the headline.
14159 The return values of all calls to the function will be collected and
14160 returned as a list.
14162 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14163 does not need to preserve point. After evaluation, the cursor will be
14164 moved to the end of the line (presumably of the headline of the
14165 processed entry) and search continues from there. Under some
14166 circumstances, this may not produce the wanted results. For example,
14167 if you have removed (e.g. archived) the current (sub)tree it could
14168 mean that the next entry will be skipped entirely. In such cases, you
14169 can specify the position from where search should continue by making
14170 FUNC set the variable `org-map-continue-from' to the desired buffer
14171 position.
14173 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14174 Only headlines that are matched by this query will be considered during
14175 the iteration. When MATCH is nil or t, all headlines will be
14176 visited by the iteration.
14178 SCOPE determines the scope of this command. It can be any of:
14180 nil The current buffer, respecting the restriction if any
14181 tree The subtree started with the entry at point
14182 region The entries within the active region, if any
14183 region-start-level
14184 The entries within the active region, but only those at
14185 the same level than the first one.
14186 file The current buffer, without restriction
14187 file-with-archives
14188 The current buffer, and any archives associated with it
14189 agenda All agenda files
14190 agenda-with-archives
14191 All agenda files with any archive files associated with them
14192 \(file1 file2 ...)
14193 If this is a list, all files in the list will be scanned
14195 The remaining args are treated as settings for the skipping facilities of
14196 the scanner. The following items can be given here:
14198 archive skip trees with the archive tag.
14199 comment skip trees with the COMMENT keyword
14200 function or Emacs Lisp form:
14201 will be used as value for `org-agenda-skip-function', so whenever
14202 the function returns t, FUNC will not be called for that
14203 entry and search will continue from the point where the
14204 function leaves it.
14206 If your function needs to retrieve the tags including inherited tags
14207 at the *current* entry, you can use the value of the variable
14208 `org-scanner-tags' which will be much faster than getting the value
14209 with `org-get-tags-at'. If your function gets properties with
14210 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14211 to t around the call to `org-entry-properties' to get the same speedup.
14212 Note that if your function moves around to retrieve tags and properties at
14213 a *different* entry, you cannot use these techniques."
14214 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14215 (not (org-region-active-p)))
14216 (let* ((org-agenda-archives-mode nil) ; just to make sure
14217 (org-agenda-skip-archived-trees (memq 'archive skip))
14218 (org-agenda-skip-comment-trees (memq 'comment skip))
14219 (org-agenda-skip-function
14220 (car (org-delete-all '(comment archive) skip)))
14221 (org-tags-match-list-sublevels t)
14222 (start-level (eq scope 'region-start-level))
14223 matcher file res
14224 org-todo-keywords-for-agenda
14225 org-done-keywords-for-agenda
14226 org-todo-keyword-alist-for-agenda
14227 org-drawers-for-agenda
14228 org-tag-alist-for-agenda
14229 todo-only)
14231 (cond
14232 ((eq match t) (setq matcher t))
14233 ((eq match nil) (setq matcher t))
14234 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14236 (save-excursion
14237 (save-restriction
14238 (cond ((eq scope 'tree)
14239 (org-back-to-heading t)
14240 (org-narrow-to-subtree)
14241 (setq scope nil))
14242 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14243 (org-region-active-p))
14244 ;; If needed, set start-level to a string like "2"
14245 (when start-level
14246 (save-excursion
14247 (goto-char (region-beginning))
14248 (unless (org-at-heading-p) (outline-next-heading))
14249 (setq start-level (org-current-level))))
14250 (narrow-to-region (region-beginning)
14251 (save-excursion
14252 (goto-char (region-end))
14253 (unless (and (bolp) (org-at-heading-p))
14254 (outline-next-heading))
14255 (point)))
14256 (setq scope nil)))
14258 (if (not scope)
14259 (progn
14260 (org-agenda-prepare-buffers
14261 (list (buffer-file-name (current-buffer))))
14262 (setq res (org-scan-tags func matcher todo-only start-level)))
14263 ;; Get the right scope
14264 (cond
14265 ((and scope (listp scope) (symbolp (car scope)))
14266 (setq scope (eval scope)))
14267 ((eq scope 'agenda)
14268 (setq scope (org-agenda-files t)))
14269 ((eq scope 'agenda-with-archives)
14270 (setq scope (org-agenda-files t))
14271 (setq scope (org-add-archive-files scope)))
14272 ((eq scope 'file)
14273 (setq scope (list (buffer-file-name))))
14274 ((eq scope 'file-with-archives)
14275 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14276 (org-agenda-prepare-buffers scope)
14277 (while (setq file (pop scope))
14278 (with-current-buffer (org-find-base-buffer-visiting file)
14279 (save-excursion
14280 (save-restriction
14281 (widen)
14282 (goto-char (point-min))
14283 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14284 res)))
14286 ;;;; Properties
14288 ;;; Setting and retrieving properties
14290 (defconst org-special-properties
14291 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14292 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14293 "The special properties valid in Org-mode.
14295 These are properties that are not defined in the property drawer,
14296 but in some other way.")
14298 (defconst org-default-properties
14299 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14300 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14301 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14302 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14303 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14304 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14305 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14306 "Some properties that are used by Org-mode for various purposes.
14307 Being in this list makes sure that they are offered for completion.")
14309 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14310 "Regular expression matching the first line of a property drawer.")
14312 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14313 "Regular expression matching the last line of a property drawer.")
14315 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14316 "Regular expression matching the first line of a property drawer.")
14318 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14319 "Regular expression matching the first line of a property drawer.")
14321 (defconst org-property-drawer-re
14322 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14323 org-property-end-re "\\)\n?")
14324 "Matches an entire property drawer.")
14326 (defconst org-clock-drawer-re
14327 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14328 org-property-end-re "\\)\n?")
14329 "Matches an entire clock drawer.")
14331 (defsubst org-re-property (property)
14332 "Return a regexp matching a PROPERTY line.
14333 Match group 1 will be set to the value."
14334 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14336 (defsubst org-re-property-keyword (property)
14337 "Return a regexp matching a PROPERTY line, possibly with no
14338 value for the property."
14339 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14341 (defun org-property-action ()
14342 "Do an action on properties."
14343 (interactive)
14344 (let (c)
14345 (org-at-property-p)
14346 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14347 (setq c (read-char-exclusive))
14348 (cond
14349 ((equal c ?s)
14350 (call-interactively 'org-set-property))
14351 ((equal c ?d)
14352 (call-interactively 'org-delete-property))
14353 ((equal c ?D)
14354 (call-interactively 'org-delete-property-globally))
14355 ((equal c ?c)
14356 (call-interactively 'org-compute-property-at-point))
14357 (t (error "No such property action %c" c)))))
14359 (defun org-inc-effort ()
14360 "Increment the value of the effort property in the current entry."
14361 (interactive)
14362 (org-set-effort nil t))
14364 (defun org-set-effort (&optional value increment)
14365 "Set the effort property of the current entry.
14366 With numerical prefix arg, use the nth allowed value, 0 stands for the
14367 10th allowed value.
14369 When INCREMENT is non-nil, set the property to the next allowed value."
14370 (interactive "P")
14371 (if (equal value 0) (setq value 10))
14372 (let* ((completion-ignore-case t)
14373 (prop org-effort-property)
14374 (cur (org-entry-get nil prop))
14375 (allowed (org-property-get-allowed-values nil prop 'table))
14376 (existing (mapcar 'list (org-property-values prop)))
14378 (val (cond
14379 ((stringp value) value)
14380 ((and allowed (integerp value))
14381 (or (car (nth (1- value) allowed))
14382 (car (org-last allowed))))
14383 ((and allowed increment)
14384 (or (caadr (member (list cur) allowed))
14385 (error "Allowed effort values are not set")))
14386 (allowed
14387 (message "Select 1-9,0, [RET%s]: %s"
14388 (if cur (concat "=" cur) "")
14389 (mapconcat 'car allowed " "))
14390 (setq rpl (read-char-exclusive))
14391 (if (equal rpl ?\r)
14393 (setq rpl (- rpl ?0))
14394 (if (equal rpl 0) (setq rpl 10))
14395 (if (and (> rpl 0) (<= rpl (length allowed)))
14396 (car (nth (1- rpl) allowed))
14397 (org-completing-read "Effort: " allowed nil))))
14399 (let (org-completion-use-ido org-completion-use-iswitchb)
14400 (org-completing-read
14401 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14402 (concat "[" cur "]") "")
14403 ": ")
14404 existing nil nil "" nil cur))))))
14405 (unless (equal (org-entry-get nil prop) val)
14406 (org-entry-put nil prop val))
14407 (message "%s is now %s" prop val)))
14409 (defun org-at-property-p ()
14410 "Is cursor inside a property drawer?"
14411 (save-excursion
14412 (beginning-of-line 1)
14413 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14414 (save-match-data ;; Used by calling procedures
14415 (let ((p (point))
14416 (range (unless (org-before-first-heading-p)
14417 (org-get-property-block))))
14418 (and range (<= (car range) p) (< p (cdr range))))))))
14420 (defun org-get-property-block (&optional beg end force)
14421 "Return the (beg . end) range of the body of the property drawer.
14422 BEG and END are the beginning and end of the current subtree, or of
14423 the part before the first headline. If they are not given, they will
14424 be found. If the drawer does not exist and FORCE is non-nil, create
14425 the drawer."
14426 (catch 'exit
14427 (save-excursion
14428 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14429 (progn (org-back-to-heading t) (point))))
14430 (end (or end (and (not (outline-next-heading)) (point-max))
14431 (point))))
14432 (goto-char beg)
14433 (if (re-search-forward org-property-start-re end t)
14434 (setq beg (1+ (match-end 0)))
14435 (if force
14436 (save-excursion
14437 (org-insert-property-drawer)
14438 (setq end (progn (outline-next-heading) (point))))
14439 (throw 'exit nil))
14440 (goto-char beg)
14441 (if (re-search-forward org-property-start-re end t)
14442 (setq beg (1+ (match-end 0)))))
14443 (if (re-search-forward org-property-end-re end t)
14444 (setq end (match-beginning 0))
14445 (or force (throw 'exit nil))
14446 (goto-char beg)
14447 (setq end beg)
14448 (org-indent-line)
14449 (insert ":END:\n"))
14450 (cons beg end)))))
14452 (defun org-entry-properties (&optional pom which specific)
14453 "Get all properties of the entry at point-or-marker POM.
14454 This includes the TODO keyword, the tags, time strings for deadline,
14455 scheduled, and clocking, and any additional properties defined in the
14456 entry. The return value is an alist, keys may occur multiple times
14457 if the property key was used several times.
14458 POM may also be nil, in which case the current entry is used.
14459 If WHICH is nil or `all', get all properties. If WHICH is
14460 `special' or `standard', only get that subclass. If WHICH
14461 is a string only get exactly this property. SPECIFIC can be a string, the
14462 specific property we are interested in. Specifying it can speed
14463 things up because then unnecessary parsing is avoided."
14464 (setq which (or which 'all))
14465 (org-with-point-at pom
14466 (let ((clockstr (substring org-clock-string 0 -1))
14467 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14468 (case-fold-search nil)
14469 beg end range props sum-props key key1 value string clocksum clocksumt)
14470 (save-excursion
14471 (when (condition-case nil
14472 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14473 (error nil))
14474 (setq beg (point))
14475 (setq sum-props (get-text-property (point) 'org-summaries))
14476 (setq clocksum (get-text-property (point) :org-clock-minutes)
14477 clocksumt (get-text-property (point) :org-clock-minutes-today))
14478 (outline-next-heading)
14479 (setq end (point))
14480 (when (memq which '(all special))
14481 ;; Get the special properties, like TODO and tags
14482 (goto-char beg)
14483 (when (and (or (not specific) (string= specific "TODO"))
14484 (looking-at org-todo-line-regexp) (match-end 2))
14485 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14486 (when (and (or (not specific) (string= specific "PRIORITY"))
14487 (looking-at org-priority-regexp))
14488 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14489 (when (or (not specific) (string= specific "FILE"))
14490 (push (cons "FILE" buffer-file-name) props))
14491 (when (and (or (not specific) (string= specific "TAGS"))
14492 (setq value (org-get-tags-string))
14493 (string-match "\\S-" value))
14494 (push (cons "TAGS" value) props))
14495 (when (and (or (not specific) (string= specific "ALLTAGS"))
14496 (setq value (org-get-tags-at)))
14497 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14498 ":"))
14499 props))
14500 (when (or (not specific) (string= specific "BLOCKED"))
14501 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14502 (when (or (not specific)
14503 (member specific
14504 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14505 "TIMESTAMP" "TIMESTAMP_IA")))
14506 (catch 'match
14507 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14508 (setq key (if (match-end 1)
14509 (substring (org-match-string-no-properties 1)
14510 0 -1))
14511 string (if (equal key clockstr)
14512 (org-trim
14513 (buffer-substring-no-properties
14514 (match-beginning 3) (goto-char
14515 (point-at-eol))))
14516 (substring (org-match-string-no-properties 3)
14517 1 -1)))
14518 ;; Get the correct property name from the key. This is
14519 ;; necessary if the user has configured time keywords.
14520 (setq key1 (concat key ":"))
14521 (cond
14522 ((not key)
14523 (setq key
14524 (if (= (char-after (match-beginning 3)) ?\[)
14525 "TIMESTAMP_IA" "TIMESTAMP")))
14526 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14527 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14528 ((equal key1 org-closed-string) (setq key "CLOSED"))
14529 ((equal key1 org-clock-string) (setq key "CLOCK")))
14530 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14531 (progn
14532 (push (cons key string) props)
14533 ;; no need to search further if match is found
14534 (throw 'match t))
14535 (when (or (equal key "CLOCK") (not (assoc key props)))
14536 (push (cons key string) props)))))))
14538 (when (memq which '(all standard))
14539 ;; Get the standard properties, like :PROP: ...
14540 (setq range (org-get-property-block beg end))
14541 (when range
14542 (goto-char (car range))
14543 (while (re-search-forward
14544 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14545 (cdr range) t)
14546 (setq key (org-match-string-no-properties 1)
14547 value (org-trim (or (org-match-string-no-properties 2) "")))
14548 (unless (member key excluded)
14549 (push (cons key (or value "")) props)))))
14550 (if clocksum
14551 (push (cons "CLOCKSUM"
14552 (org-columns-number-to-string (/ (float clocksum) 60.)
14553 'add_times))
14554 props))
14555 (if clocksumt
14556 (push (cons "CLOCKSUM_T"
14557 (org-columns-number-to-string (/ (float clocksumt) 60.)
14558 'add_times))
14559 props))
14560 (unless (assoc "CATEGORY" props)
14561 (push (cons "CATEGORY" (org-get-category)) props))
14562 (append sum-props (nreverse props)))))))
14564 (defun org-entry-get (pom property &optional inherit literal-nil)
14565 "Get value of PROPERTY for entry or content at point-or-marker POM.
14566 If INHERIT is non-nil and the entry does not have the property,
14567 then also check higher levels of the hierarchy.
14568 If INHERIT is the symbol `selective', use inheritance only if the setting
14569 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14570 If the property is present but empty, the return value is the empty string.
14571 If the property is not present at all, nil is returned.
14573 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14574 do not interpret it as the list atom nil. This is used for inheritance
14575 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14576 (org-with-point-at pom
14577 (if (and inherit (if (eq inherit 'selective)
14578 (org-property-inherit-p property)
14580 (org-entry-get-with-inheritance property literal-nil)
14581 (if (member property org-special-properties)
14582 ;; We need a special property. Use `org-entry-properties' to
14583 ;; retrieve it, but specify the wanted property
14584 (cdr (assoc property (org-entry-properties nil 'special property)))
14585 (let* ((range (org-get-property-block))
14586 (props (list (or (assoc property org-file-properties)
14587 (assoc property org-global-properties)
14588 (assoc property org-global-properties-fixed))))
14589 (ap (lambda (key)
14590 (when (re-search-forward
14591 (org-re-property key) (cdr range) t)
14592 (setq props
14593 (org-update-property-plist
14595 (if (match-end 1)
14596 (org-match-string-no-properties 1) "")
14597 props)))))
14598 val)
14599 (when (and range (goto-char (car range)))
14600 (funcall ap property)
14601 (goto-char (car range))
14602 (while (funcall ap (concat property "+")))
14603 (setq val (cdr (assoc property props)))
14604 (when val (if literal-nil val (org-not-nil val)))))))))
14606 (defun org-property-or-variable-value (var &optional inherit)
14607 "Check if there is a property fixing the value of VAR.
14608 If yes, return this value. If not, return the current value of the variable."
14609 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14610 (if (and prop (stringp prop) (string-match "\\S-" prop))
14611 (read prop)
14612 (symbol-value var))))
14614 (defun org-entry-delete (pom property)
14615 "Delete the property PROPERTY from entry at point-or-marker POM."
14616 (org-with-point-at pom
14617 (if (member property org-special-properties)
14618 nil ; cannot delete these properties.
14619 (let ((range (org-get-property-block)))
14620 (if (and range
14621 (goto-char (car range))
14622 (re-search-forward
14623 (org-re-property property)
14624 (cdr range) t))
14625 (progn
14626 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14628 nil)))))
14630 ;; Multi-values properties are properties that contain multiple values
14631 ;; These values are assumed to be single words, separated by whitespace.
14632 (defun org-entry-add-to-multivalued-property (pom property value)
14633 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14634 (let* ((old (org-entry-get pom property))
14635 (values (and old (org-split-string old "[ \t]"))))
14636 (setq value (org-entry-protect-space value))
14637 (unless (member value values)
14638 (setq values (cons value values))
14639 (org-entry-put pom property
14640 (mapconcat 'identity values " ")))))
14642 (defun org-entry-remove-from-multivalued-property (pom property value)
14643 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14644 (let* ((old (org-entry-get pom property))
14645 (values (and old (org-split-string old "[ \t]"))))
14646 (setq value (org-entry-protect-space value))
14647 (when (member value values)
14648 (setq values (delete value values))
14649 (org-entry-put pom property
14650 (mapconcat 'identity values " ")))))
14652 (defun org-entry-member-in-multivalued-property (pom property value)
14653 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14654 (let* ((old (org-entry-get pom property))
14655 (values (and old (org-split-string old "[ \t]"))))
14656 (setq value (org-entry-protect-space value))
14657 (member value values)))
14659 (defun org-entry-get-multivalued-property (pom property)
14660 "Return a list of values in a multivalued property."
14661 (let* ((value (org-entry-get pom property))
14662 (values (and value (org-split-string value "[ \t]"))))
14663 (mapcar 'org-entry-restore-space values)))
14665 (defun org-entry-put-multivalued-property (pom property &rest values)
14666 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14667 VALUES should be a list of strings. Spaces will be protected."
14668 (org-entry-put pom property
14669 (mapconcat 'org-entry-protect-space values " "))
14670 (let* ((value (org-entry-get pom property))
14671 (values (and value (org-split-string value "[ \t]"))))
14672 (mapcar 'org-entry-restore-space values)))
14674 (defun org-entry-protect-space (s)
14675 "Protect spaces and newline in string S."
14676 (while (string-match " " s)
14677 (setq s (replace-match "%20" t t s)))
14678 (while (string-match "\n" s)
14679 (setq s (replace-match "%0A" t t s)))
14682 (defun org-entry-restore-space (s)
14683 "Restore spaces and newline in string S."
14684 (while (string-match "%20" s)
14685 (setq s (replace-match " " t t s)))
14686 (while (string-match "%0A" s)
14687 (setq s (replace-match "\n" t t s)))
14690 (defvar org-entry-property-inherited-from (make-marker)
14691 "Marker pointing to the entry from where a property was inherited.
14692 Each call to `org-entry-get-with-inheritance' will set this marker to the
14693 location of the entry where the inheritance search matched. If there was
14694 no match, the marker will point nowhere.
14695 Note that also `org-entry-get' calls this function, if the INHERIT flag
14696 is set.")
14698 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14699 "Get PROPERTY of entry or content at point, search higher levels if needed.
14700 The search will stop at the first ancestor which has the property defined.
14701 If the value found is \"nil\", return nil to show that the property
14702 should be considered as undefined (this is the meaning of nil here).
14703 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14704 (move-marker org-entry-property-inherited-from nil)
14705 (let (tmp)
14706 (save-excursion
14707 (save-restriction
14708 (widen)
14709 (catch 'ex
14710 (while t
14711 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14712 (or (ignore-errors (org-back-to-heading t))
14713 (goto-char (point-min)))
14714 (move-marker org-entry-property-inherited-from (point))
14715 (throw 'ex tmp))
14716 (or (ignore-errors (org-up-heading-safe))
14717 (throw 'ex nil))))))
14718 (setq tmp (or tmp
14719 (cdr (assoc property org-file-properties))
14720 (cdr (assoc property org-global-properties))
14721 (cdr (assoc property org-global-properties-fixed))))
14722 (if literal-nil tmp (org-not-nil tmp))))
14724 (defvar org-property-changed-functions nil
14725 "Hook called when the value of a property has changed.
14726 Each hook function should accept two arguments, the name of the property
14727 and the new value.")
14729 (defun org-entry-put (pom property value)
14730 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14731 (org-with-point-at pom
14732 (org-back-to-heading t)
14733 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14734 range)
14735 (cond
14736 ((equal property "TODO")
14737 (when (and (stringp value) (string-match "\\S-" value)
14738 (not (member value org-todo-keywords-1)))
14739 (error "\"%s\" is not a valid TODO state" value))
14740 (if (or (not value)
14741 (not (string-match "\\S-" value)))
14742 (setq value 'none))
14743 (org-todo value)
14744 (org-set-tags nil 'align))
14745 ((equal property "PRIORITY")
14746 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14747 (string-to-char value) ?\ ))
14748 (org-set-tags nil 'align))
14749 ((equal property "SCHEDULED")
14750 (if (re-search-forward org-scheduled-time-regexp end t)
14751 (cond
14752 ((eq value 'earlier) (org-timestamp-change -1 'day))
14753 ((eq value 'later) (org-timestamp-change 1 'day))
14754 (t (call-interactively 'org-schedule)))
14755 (call-interactively 'org-schedule)))
14756 ((equal property "DEADLINE")
14757 (if (re-search-forward org-deadline-time-regexp end t)
14758 (cond
14759 ((eq value 'earlier) (org-timestamp-change -1 'day))
14760 ((eq value 'later) (org-timestamp-change 1 'day))
14761 (t (call-interactively 'org-deadline)))
14762 (call-interactively 'org-deadline)))
14763 ((member property org-special-properties)
14764 (error "The %s property can not yet be set with `org-entry-put'"
14765 property))
14766 (t ; a non-special property
14767 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14768 (setq range (org-get-property-block beg end 'force))
14769 (goto-char (car range))
14770 (if (re-search-forward
14771 (org-re-property-keyword property) (cdr range) t)
14772 (progn
14773 (delete-region (match-beginning 0) (match-end 0))
14774 (goto-char (match-beginning 0)))
14775 (goto-char (cdr range))
14776 (insert "\n")
14777 (backward-char 1)
14778 (org-indent-line))
14779 (insert ":" property ":")
14780 (and value (insert " " value))
14781 (org-indent-line)))))
14782 (run-hook-with-args 'org-property-changed-functions property value)))
14784 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14785 "Get all property keys in the current buffer.
14786 With INCLUDE-SPECIALS, also list the special properties that reflect things
14787 like tags and TODO state.
14788 With INCLUDE-DEFAULTS, also include properties that has special meaning
14789 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14790 and others.
14791 With INCLUDE-COLUMNS, also include property names given in COLUMN
14792 formats in the current buffer."
14793 (let (rtn range cfmt s p)
14794 (save-excursion
14795 (save-restriction
14796 (widen)
14797 (goto-char (point-min))
14798 (while (re-search-forward org-property-start-re nil t)
14799 (setq range (org-get-property-block))
14800 (goto-char (car range))
14801 (while (re-search-forward
14802 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14803 (cdr range) t)
14804 (add-to-list 'rtn (org-match-string-no-properties 1)))
14805 (outline-next-heading))))
14807 (when include-specials
14808 (setq rtn (append org-special-properties rtn)))
14810 (when include-defaults
14811 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14812 (add-to-list 'rtn org-effort-property))
14814 (when include-columns
14815 (save-excursion
14816 (save-restriction
14817 (widen)
14818 (goto-char (point-min))
14819 (while (re-search-forward
14820 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14821 nil t)
14822 (setq cfmt (match-string 2) s 0)
14823 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14824 cfmt s)
14825 (setq s (match-end 0)
14826 p (match-string 1 cfmt))
14827 (unless (or (equal p "ITEM")
14828 (member p org-special-properties))
14829 (add-to-list 'rtn (match-string 1 cfmt))))))))
14831 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14833 (defun org-property-values (key)
14834 "Return a list of all values of property KEY in the current buffer."
14835 (save-excursion
14836 (save-restriction
14837 (widen)
14838 (goto-char (point-min))
14839 (let ((re (org-re-property key))
14840 values)
14841 (while (re-search-forward re nil t)
14842 (add-to-list 'values (org-trim (match-string 1))))
14843 (delete "" values)))))
14845 (defun org-insert-property-drawer ()
14846 "Insert a property drawer into the current entry."
14847 (org-back-to-heading t)
14848 (looking-at org-outline-regexp)
14849 (let ((indent (if org-adapt-indentation
14850 (- (match-end 0) (match-beginning 0))
14852 (beg (point))
14853 (re (concat "^[ \t]*" org-keyword-time-regexp))
14854 end hiddenp)
14855 (outline-next-heading)
14856 (setq end (point))
14857 (goto-char beg)
14858 (while (re-search-forward re end t))
14859 (setq hiddenp (outline-invisible-p))
14860 (end-of-line 1)
14861 (and (equal (char-after) ?\n) (forward-char 1))
14862 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14863 (if (member (match-string 1) '("CLOCK:" ":END:"))
14864 ;; just skip this line
14865 (beginning-of-line 2)
14866 ;; Drawer start, find the end
14867 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14868 (beginning-of-line 1)))
14869 (org-skip-over-state-notes)
14870 (skip-chars-backward " \t\n\r")
14871 (if (eq (char-before) ?*) (forward-char 1))
14872 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14873 (beginning-of-line 0)
14874 (org-indent-to-column indent)
14875 (beginning-of-line 2)
14876 (org-indent-to-column indent)
14877 (beginning-of-line 0)
14878 (if hiddenp
14879 (save-excursion
14880 (org-back-to-heading t)
14881 (hide-entry))
14882 (org-flag-drawer t))))
14884 (defun org-insert-drawer (&optional arg drawer)
14885 "Insert a drawer at point.
14887 Optional argument DRAWER, when non-nil, is a string representing
14888 drawer's name. Otherwise, the user is prompted for a name.
14890 If a region is active, insert the drawer around that region
14891 instead.
14893 Point is left between drawer's boundaries."
14894 (interactive "P")
14895 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14896 "LOGBOOK"))
14897 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14898 ;; internally by Org. They are meant to be inserted
14899 ;; automatically.
14900 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14901 ;; Remove system drawers from list. Note: For some reason,
14902 ;; `org-completing-read' ignores the predicate while
14903 ;; `completing-read' handles it fine.
14904 (drawer (if arg "PROPERTIES"
14905 (or drawer
14906 (completing-read
14907 "Drawer: " org-drawers
14908 (lambda (d) (not (member d system-drawers))))))))
14909 (cond
14910 ;; With C-u, fall back on `org-insert-property-drawer'
14911 (arg (org-insert-property-drawer))
14912 ;; With an active region, insert a drawer at point.
14913 ((not (org-region-active-p))
14914 (progn
14915 (unless (bolp) (insert "\n"))
14916 (insert (format ":%s:\n\n:END:\n" drawer))
14917 (forward-line -2)))
14918 ;; Otherwise, insert the drawer at point
14920 (let ((rbeg (region-beginning))
14921 (rend (copy-marker (region-end))))
14922 (unwind-protect
14923 (progn
14924 (goto-char rbeg)
14925 (beginning-of-line)
14926 (when (save-excursion
14927 (re-search-forward org-outline-regexp-bol rend t))
14928 (error "Drawers cannot contain headlines"))
14929 ;; Position point at the beginning of the first
14930 ;; non-blank line in region. Insert drawer's opening
14931 ;; there, then indent it.
14932 (org-skip-whitespace)
14933 (beginning-of-line)
14934 (insert ":" drawer ":\n")
14935 (forward-line -1)
14936 (indent-for-tab-command)
14937 ;; Move point to the beginning of the first blank line
14938 ;; after the last non-blank line in region. Insert
14939 ;; drawer's closing, then indent it.
14940 (goto-char rend)
14941 (skip-chars-backward " \r\t\n")
14942 (insert "\n:END:")
14943 (indent-for-tab-command)
14944 (unless (eolp) (insert "\n")))
14945 ;; Clear marker, whatever the outcome of insertion is.
14946 (set-marker rend nil)))))))
14948 (defvar org-property-set-functions-alist nil
14949 "Property set function alist.
14950 Each entry should have the following format:
14952 (PROPERTY . READ-FUNCTION)
14954 The read function will be called with the same argument as
14955 `org-completing-read'.")
14957 (defun org-set-property-function (property)
14958 "Get the function that should be used to set PROPERTY.
14959 This is computed according to `org-property-set-functions-alist'."
14960 (or (cdr (assoc property org-property-set-functions-alist))
14961 'org-completing-read))
14963 (defun org-read-property-value (property)
14964 "Read PROPERTY value from user."
14965 (let* ((completion-ignore-case t)
14966 (allowed (org-property-get-allowed-values nil property 'table))
14967 (cur (org-entry-get nil property))
14968 (prompt (concat property " value"
14969 (if (and cur (string-match "\\S-" cur))
14970 (concat " [" cur "]") "") ": "))
14971 (set-function (org-set-property-function property))
14972 (val (if allowed
14973 (funcall set-function prompt allowed nil
14974 (not (get-text-property 0 'org-unrestricted
14975 (caar allowed))))
14976 (let (org-completion-use-ido org-completion-use-iswitchb)
14977 (funcall set-function prompt
14978 (mapcar 'list (org-property-values property))
14979 nil nil "" nil cur)))))
14980 (if (equal val "")
14982 val)))
14984 (defvar org-last-set-property nil)
14985 (defun org-read-property-name ()
14986 "Read a property name."
14987 (let* ((completion-ignore-case t)
14988 (keys (org-buffer-property-keys nil t t))
14989 (default-prop (or (save-excursion
14990 (save-match-data
14991 (beginning-of-line)
14992 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14993 (null (string= (match-string 1) "END"))
14994 (match-string 1))))
14995 org-last-set-property))
14996 (property (org-icompleting-read
14997 (concat "Property"
14998 (if default-prop (concat " [" default-prop "]") "")
14999 ": ")
15000 (mapcar 'list keys)
15001 nil nil nil nil
15002 default-prop
15004 (if (member property keys)
15005 property
15006 (or (cdr (assoc (downcase property)
15007 (mapcar (lambda (x) (cons (downcase x) x))
15008 keys)))
15009 property))))
15011 (defun org-set-property (property value)
15012 "In the current entry, set PROPERTY to VALUE.
15013 When called interactively, this will prompt for a property name, offering
15014 completion on existing and default properties. And then it will prompt
15015 for a value, offering completion either on allowed values (via an inherited
15016 xxx_ALL property) or on existing values in other instances of this property
15017 in the current file."
15018 (interactive (list nil nil))
15019 (let* ((property (or property (org-read-property-name)))
15020 (value (or value (org-read-property-value property)))
15021 (fn (cdr (assoc property org-properties-postprocess-alist))))
15022 (setq org-last-set-property property)
15023 ;; Possibly postprocess the inserted value:
15024 (when fn (setq value (funcall fn value)))
15025 (unless (equal (org-entry-get nil property) value)
15026 (org-entry-put nil property value))))
15028 (defun org-delete-property (property)
15029 "In the current entry, delete PROPERTY."
15030 (interactive
15031 (let* ((completion-ignore-case t)
15032 (prop (org-icompleting-read "Property: "
15033 (org-entry-properties nil 'standard))))
15034 (list prop)))
15035 (message "Property %s %s" property
15036 (if (org-entry-delete nil property)
15037 "deleted"
15038 "was not present in the entry")))
15040 (defun org-delete-property-globally (property)
15041 "Remove PROPERTY globally, from all entries."
15042 (interactive
15043 (let* ((completion-ignore-case t)
15044 (prop (org-icompleting-read
15045 "Globally remove property: "
15046 (mapcar 'list (org-buffer-property-keys)))))
15047 (list prop)))
15048 (save-excursion
15049 (save-restriction
15050 (widen)
15051 (goto-char (point-min))
15052 (let ((cnt 0))
15053 (while (re-search-forward
15054 (org-re-property property)
15055 nil t)
15056 (setq cnt (1+ cnt))
15057 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15058 (message "Property \"%s\" removed from %d entries" property cnt)))))
15060 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15062 (defun org-compute-property-at-point ()
15063 "Compute the property at point.
15064 This looks for an enclosing column format, extracts the operator and
15065 then applies it to the property in the column format's scope."
15066 (interactive)
15067 (unless (org-at-property-p)
15068 (error "Not at a property"))
15069 (let ((prop (org-match-string-no-properties 2)))
15070 (org-columns-get-format-and-top-level)
15071 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15072 (error "No operator defined for property %s" prop))
15073 (org-columns-compute prop)))
15075 (defvar org-property-allowed-value-functions nil
15076 "Hook for functions supplying allowed values for a specific property.
15077 The functions must take a single argument, the name of the property, and
15078 return a flat list of allowed values. If \":ETC\" is one of
15079 the values, this means that these values are intended as defaults for
15080 completion, but that other values should be allowed too.
15081 The functions must return nil if they are not responsible for this
15082 property.")
15084 (defun org-property-get-allowed-values (pom property &optional table)
15085 "Get allowed values for the property PROPERTY.
15086 When TABLE is non-nil, return an alist that can directly be used for
15087 completion."
15088 (let (vals)
15089 (cond
15090 ((equal property "TODO")
15091 (setq vals (org-with-point-at pom
15092 (append org-todo-keywords-1 '("")))))
15093 ((equal property "PRIORITY")
15094 (let ((n org-lowest-priority))
15095 (while (>= n org-highest-priority)
15096 (push (char-to-string n) vals)
15097 (setq n (1- n)))))
15098 ((member property org-special-properties))
15099 ((setq vals (run-hook-with-args-until-success
15100 'org-property-allowed-value-functions property)))
15102 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15103 (when (and vals (string-match "\\S-" vals))
15104 (setq vals (car (read-from-string (concat "(" vals ")"))))
15105 (setq vals (mapcar (lambda (x)
15106 (cond ((stringp x) x)
15107 ((numberp x) (number-to-string x))
15108 ((symbolp x) (symbol-name x))
15109 (t "???")))
15110 vals)))))
15111 (when (member ":ETC" vals)
15112 (setq vals (remove ":ETC" vals))
15113 (org-add-props (car vals) '(org-unrestricted t)))
15114 (if table (mapcar 'list vals) vals)))
15116 (defun org-property-previous-allowed-value (&optional previous)
15117 "Switch to the next allowed value for this property."
15118 (interactive)
15119 (org-property-next-allowed-value t))
15121 (defun org-property-next-allowed-value (&optional previous)
15122 "Switch to the next allowed value for this property."
15123 (interactive)
15124 (unless (org-at-property-p)
15125 (error "Not at a property"))
15126 (let* ((key (match-string 2))
15127 (value (match-string 3))
15128 (allowed (or (org-property-get-allowed-values (point) key)
15129 (and (member value '("[ ]" "[-]" "[X]"))
15130 '("[ ]" "[X]"))))
15131 nval)
15132 (unless allowed
15133 (error "Allowed values for this property have not been defined"))
15134 (if previous (setq allowed (reverse allowed)))
15135 (if (member value allowed)
15136 (setq nval (car (cdr (member value allowed)))))
15137 (setq nval (or nval (car allowed)))
15138 (if (equal nval value)
15139 (error "Only one allowed value for this property"))
15140 (org-at-property-p)
15141 (replace-match (concat " :" key ": " nval) t t)
15142 (org-indent-line)
15143 (beginning-of-line 1)
15144 (skip-chars-forward " \t")
15145 (run-hook-with-args 'org-property-changed-functions key nval)))
15147 (defun org-find-olp (path &optional this-buffer)
15148 "Return a marker pointing to the entry at outline path OLP.
15149 If anything goes wrong, throw an error.
15150 You can wrap this call to catch the error like this:
15152 (condition-case msg
15153 (org-mobile-locate-entry (match-string 4))
15154 (error (nth 1 msg)))
15156 The return value will then be either a string with the error message,
15157 or a marker if everything is OK.
15159 If THIS-BUFFER is set, the outline path does not contain a file,
15160 only headings."
15161 (let* ((file (if this-buffer buffer-file-name (pop path)))
15162 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15163 (level 1)
15164 (lmin 1)
15165 (lmax 1)
15166 limit re end found pos heading cnt flevel)
15167 (unless buffer (error "File not found :%s" file))
15168 (with-current-buffer buffer
15169 (save-excursion
15170 (save-restriction
15171 (widen)
15172 (setq limit (point-max))
15173 (goto-char (point-min))
15174 (while (setq heading (pop path))
15175 (setq re (format org-complex-heading-regexp-format
15176 (regexp-quote heading)))
15177 (setq cnt 0 pos (point))
15178 (while (re-search-forward re end t)
15179 (setq level (- (match-end 1) (match-beginning 1)))
15180 (if (and (>= level lmin) (<= level lmax))
15181 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15182 (when (= cnt 0) (error "Heading not found on level %d: %s"
15183 lmax heading))
15184 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15185 lmax heading))
15186 (goto-char found)
15187 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15188 (setq end (save-excursion (org-end-of-subtree t t))))
15189 (when (org-at-heading-p)
15190 (move-marker (make-marker) (point))))))))
15192 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15193 "Find node HEADING in BUFFER.
15194 Return a marker to the heading if it was found, or nil if not.
15195 If POS-ONLY is set, return just the position instead of a marker.
15197 The heading text must match exact, but it may have a TODO keyword,
15198 a priority cookie and tags in the standard locations."
15199 (with-current-buffer (or buffer (current-buffer))
15200 (save-excursion
15201 (save-restriction
15202 (widen)
15203 (goto-char (point-min))
15204 (let (case-fold-search)
15205 (if (re-search-forward
15206 (format org-complex-heading-regexp-format
15207 (regexp-quote heading)) nil t)
15208 (if pos-only
15209 (match-beginning 0)
15210 (move-marker (make-marker) (match-beginning 0)))))))))
15212 (defun org-find-exact-heading-in-directory (heading &optional dir)
15213 "Find Org node headline HEADING in all .org files in directory DIR.
15214 When the target headline is found, return a marker to this location."
15215 (let ((files (directory-files (or dir default-directory)
15216 nil "\\`[^.#].*\\.org\\'"))
15217 file visiting m buffer)
15218 (catch 'found
15219 (while (setq file (pop files))
15220 (message "trying %s" file)
15221 (setq visiting (org-find-base-buffer-visiting file))
15222 (setq buffer (or visiting (find-file-noselect file)))
15223 (setq m (org-find-exact-headline-in-buffer
15224 heading buffer))
15225 (when (and (not m) (not visiting)) (kill-buffer buffer))
15226 (and m (throw 'found m))))))
15228 (defun org-find-entry-with-id (ident)
15229 "Locate the entry that contains the ID property with exact value IDENT.
15230 IDENT can be a string, a symbol or a number, this function will search for
15231 the string representation of it.
15232 Return the position where this entry starts, or nil if there is no such entry."
15233 (interactive "sID: ")
15234 (let ((id (cond
15235 ((stringp ident) ident)
15236 ((symbol-name ident) (symbol-name ident))
15237 ((numberp ident) (number-to-string ident))
15238 (t (error "IDENT %s must be a string, symbol or number" ident))))
15239 (case-fold-search nil))
15240 (save-excursion
15241 (save-restriction
15242 (widen)
15243 (goto-char (point-min))
15244 (when (re-search-forward
15245 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15246 nil t)
15247 (org-back-to-heading t)
15248 (point))))))
15250 ;;;; Timestamps
15252 (defvar org-last-changed-timestamp nil)
15253 (defvar org-last-inserted-timestamp nil
15254 "The last time stamp inserted with `org-insert-time-stamp'.")
15255 (defvar org-time-was-given) ; dynamically scoped parameter
15256 (defvar org-end-time-was-given) ; dynamically scoped parameter
15257 (defvar org-ts-what) ; dynamically scoped parameter
15259 (defun org-time-stamp (arg &optional inactive)
15260 "Prompt for a date/time and insert a time stamp.
15261 If the user specifies a time like HH:MM or if this command is
15262 called with at least one prefix argument, the time stamp contains
15263 the date and the time. Otherwise, only the date is be included.
15265 All parts of a date not specified by the user is filled in from
15266 the current date/time. So if you just press return without
15267 typing anything, the time stamp will represent the current
15268 date/time.
15270 If there is already a timestamp at the cursor, it will be
15271 modified.
15273 With two universal prefix arguments, insert an active timestamp
15274 with the current time without prompting the user."
15275 (interactive "P")
15276 (let* ((ts nil)
15277 (default-time
15278 ;; Default time is either today, or, when entering a range,
15279 ;; the range start.
15280 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15281 (save-excursion
15282 (re-search-backward
15283 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15284 (- (point) 20) t)))
15285 (apply 'encode-time (org-parse-time-string (match-string 1)))
15286 (current-time)))
15287 (default-input (and ts (org-get-compact-tod ts)))
15288 (repeater (save-excursion
15289 (save-match-data
15290 (beginning-of-line)
15291 (when (re-search-forward
15292 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15293 (save-excursion (progn (end-of-line) (point))) t)
15294 (match-string 0)))))
15295 org-time-was-given org-end-time-was-given time)
15296 (cond
15297 ((and (org-at-timestamp-p t)
15298 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15299 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15300 (insert "--")
15301 (setq time (let ((this-command this-command))
15302 (org-read-date arg 'totime nil nil
15303 default-time default-input inactive)))
15304 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15305 ((org-at-timestamp-p t)
15306 (setq time (let ((this-command this-command))
15307 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15308 (when (org-at-timestamp-p t) ; just to get the match data
15309 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15310 (replace-match "")
15311 (setq org-last-changed-timestamp
15312 (org-insert-time-stamp
15313 time (or org-time-was-given arg)
15314 inactive nil nil (list org-end-time-was-given)))
15315 (when repeater (goto-char (1- (point))) (insert " " repeater)
15316 (setq org-last-changed-timestamp
15317 (concat (substring org-last-inserted-timestamp 0 -1)
15318 " " repeater ">"))))
15319 (message "Timestamp updated"))
15320 ((equal arg '(16))
15321 (org-insert-time-stamp (current-time) t))
15323 (setq time (let ((this-command this-command))
15324 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15325 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15326 nil nil (list org-end-time-was-given))))))
15328 ;; FIXME: can we use this for something else, like computing time differences?
15329 (defun org-get-compact-tod (s)
15330 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15331 (let* ((t1 (match-string 1 s))
15332 (h1 (string-to-number (match-string 2 s)))
15333 (m1 (string-to-number (match-string 3 s)))
15334 (t2 (and (match-end 4) (match-string 5 s)))
15335 (h2 (and t2 (string-to-number (match-string 6 s))))
15336 (m2 (and t2 (string-to-number (match-string 7 s))))
15337 dh dm)
15338 (if (not t2)
15340 (setq dh (- h2 h1) dm (- m2 m1))
15341 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15342 (concat t1 "+" (number-to-string dh)
15343 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15345 (defun org-time-stamp-inactive (&optional arg)
15346 "Insert an inactive time stamp.
15347 An inactive time stamp is enclosed in square brackets instead of angle
15348 brackets. It is inactive in the sense that it does not trigger agenda entries,
15349 does not link to the calendar and cannot be changed with the S-cursor keys.
15350 So these are more for recording a certain time/date."
15351 (interactive "P")
15352 (org-time-stamp arg 'inactive))
15354 (defvar org-date-ovl (make-overlay 1 1))
15355 (overlay-put org-date-ovl 'face 'org-date-selected)
15356 (org-detach-overlay org-date-ovl)
15358 (defvar org-ans1) ; dynamically scoped parameter
15359 (defvar org-ans2) ; dynamically scoped parameter
15361 (defvar org-plain-time-of-day-regexp) ; defined below
15363 (defvar org-overriding-default-time nil) ; dynamically scoped
15364 (defvar org-read-date-overlay nil)
15365 (defvar org-dcst nil) ; dynamically scoped
15366 (defvar org-read-date-history nil)
15367 (defvar org-read-date-final-answer nil)
15368 (defvar org-read-date-analyze-futurep nil)
15369 (defvar org-read-date-analyze-forced-year nil)
15370 (defvar org-read-date-inactive)
15372 (defun org-read-date (&optional org-with-time to-time from-string prompt
15373 default-time default-input inactive)
15374 "Read a date, possibly a time, and make things smooth for the user.
15375 The prompt will suggest to enter an ISO date, but you can also enter anything
15376 which will at least partially be understood by `parse-time-string'.
15377 Unrecognized parts of the date will default to the current day, month, year,
15378 hour and minute. If this command is called to replace a timestamp at point,
15379 or to enter the second timestamp of a range, the default time is taken
15380 from the existing stamp. Furthermore, the command prefers the future,
15381 so if you are giving a date where the year is not given, and the day-month
15382 combination is already past in the current year, it will assume you
15383 mean next year. For details, see the manual. A few examples:
15385 3-2-5 --> 2003-02-05
15386 feb 15 --> currentyear-02-15
15387 2/15 --> currentyear-02-15
15388 sep 12 9 --> 2009-09-12
15389 12:45 --> today 12:45
15390 22 sept 0:34 --> currentyear-09-22 0:34
15391 12 --> currentyear-currentmonth-12
15392 Fri --> nearest Friday (today or later)
15393 etc.
15395 Furthermore you can specify a relative date by giving, as the *first* thing
15396 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15397 change in days weeks, months, years.
15398 With a single plus or minus, the date is relative to today. With a double
15399 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15400 +4d --> four days from today
15401 +4 --> same as above
15402 +2w --> two weeks from today
15403 ++5 --> five days from default date
15405 The function understands only English month and weekday abbreviations.
15407 While prompting, a calendar is popped up - you can also select the
15408 date with the mouse (button 1). The calendar shows a period of three
15409 months. To scroll it to other months, use the keys `>' and `<'.
15410 If you don't like the calendar, turn it off with
15411 \(setq org-read-date-popup-calendar nil)
15413 With optional argument TO-TIME, the date will immediately be converted
15414 to an internal time.
15415 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15416 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15417 still enter a time, and this function will inform the calling routine
15418 about this change. The calling routine may then choose to change the
15419 format used to insert the time stamp into the buffer to include the time.
15420 With optional argument FROM-STRING, read from this string instead from
15421 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15422 the time/date that is used for everything that is not specified by the
15423 user."
15424 (require 'parse-time)
15425 (let* ((org-time-stamp-rounding-minutes
15426 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15427 (org-dcst org-display-custom-times)
15428 (ct (org-current-time))
15429 (org-def (or org-overriding-default-time default-time ct))
15430 (org-defdecode (decode-time org-def))
15431 (dummy (progn
15432 (when (< (nth 2 org-defdecode) org-extend-today-until)
15433 (setcar (nthcdr 2 org-defdecode) -1)
15434 (setcar (nthcdr 1 org-defdecode) 59)
15435 (setq org-def (apply 'encode-time org-defdecode)
15436 org-defdecode (decode-time org-def)))))
15437 (calendar-frame-setup nil)
15438 (calendar-setup nil)
15439 (calendar-move-hook nil)
15440 (calendar-view-diary-initially-flag nil)
15441 (calendar-view-holidays-initially-flag nil)
15442 (timestr (format-time-string
15443 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15444 (prompt (concat (if prompt (concat prompt " ") "")
15445 (format "Date+time [%s]: " timestr)))
15446 ans (org-ans0 "") org-ans1 org-ans2 final)
15448 (cond
15449 (from-string (setq ans from-string))
15450 (org-read-date-popup-calendar
15451 (save-excursion
15452 (save-window-excursion
15453 (calendar)
15454 (org-eval-in-calendar '(setq cursor-type nil) t)
15455 (unwind-protect
15456 (progn
15457 (calendar-forward-day (- (time-to-days org-def)
15458 (calendar-absolute-from-gregorian
15459 (calendar-current-date))))
15460 (org-eval-in-calendar nil t)
15461 (let* ((old-map (current-local-map))
15462 (map (copy-keymap calendar-mode-map))
15463 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15464 (org-defkey map (kbd "RET") 'org-calendar-select)
15465 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15466 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15467 (org-defkey minibuffer-local-map [(meta shift left)]
15468 (lambda () (interactive)
15469 (org-eval-in-calendar '(calendar-backward-month 1))))
15470 (org-defkey minibuffer-local-map [(meta shift right)]
15471 (lambda () (interactive)
15472 (org-eval-in-calendar '(calendar-forward-month 1))))
15473 (org-defkey minibuffer-local-map [(meta shift up)]
15474 (lambda () (interactive)
15475 (org-eval-in-calendar '(calendar-backward-year 1))))
15476 (org-defkey minibuffer-local-map [(meta shift down)]
15477 (lambda () (interactive)
15478 (org-eval-in-calendar '(calendar-forward-year 1))))
15479 (org-defkey minibuffer-local-map [?\e (shift left)]
15480 (lambda () (interactive)
15481 (org-eval-in-calendar '(calendar-backward-month 1))))
15482 (org-defkey minibuffer-local-map [?\e (shift right)]
15483 (lambda () (interactive)
15484 (org-eval-in-calendar '(calendar-forward-month 1))))
15485 (org-defkey minibuffer-local-map [?\e (shift up)]
15486 (lambda () (interactive)
15487 (org-eval-in-calendar '(calendar-backward-year 1))))
15488 (org-defkey minibuffer-local-map [?\e (shift down)]
15489 (lambda () (interactive)
15490 (org-eval-in-calendar '(calendar-forward-year 1))))
15491 (org-defkey minibuffer-local-map [(shift up)]
15492 (lambda () (interactive)
15493 (org-eval-in-calendar '(calendar-backward-week 1))))
15494 (org-defkey minibuffer-local-map [(shift down)]
15495 (lambda () (interactive)
15496 (org-eval-in-calendar '(calendar-forward-week 1))))
15497 (org-defkey minibuffer-local-map [(shift left)]
15498 (lambda () (interactive)
15499 (org-eval-in-calendar '(calendar-backward-day 1))))
15500 (org-defkey minibuffer-local-map [(shift right)]
15501 (lambda () (interactive)
15502 (org-eval-in-calendar '(calendar-forward-day 1))))
15503 (org-defkey minibuffer-local-map ">"
15504 (lambda () (interactive)
15505 (org-eval-in-calendar '(scroll-calendar-left 1))))
15506 (org-defkey minibuffer-local-map "<"
15507 (lambda () (interactive)
15508 (org-eval-in-calendar '(scroll-calendar-right 1))))
15509 (org-defkey minibuffer-local-map "\C-v"
15510 (lambda () (interactive)
15511 (org-eval-in-calendar
15512 '(calendar-scroll-left-three-months 1))))
15513 (org-defkey minibuffer-local-map "\M-v"
15514 (lambda () (interactive)
15515 (org-eval-in-calendar
15516 '(calendar-scroll-right-three-months 1))))
15517 (run-hooks 'org-read-date-minibuffer-setup-hook)
15518 (unwind-protect
15519 (progn
15520 (use-local-map map)
15521 (setq org-read-date-inactive inactive)
15522 (add-hook 'post-command-hook 'org-read-date-display)
15523 (setq org-ans0 (read-string prompt default-input
15524 'org-read-date-history nil))
15525 ;; org-ans0: from prompt
15526 ;; org-ans1: from mouse click
15527 ;; org-ans2: from calendar motion
15528 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15529 (remove-hook 'post-command-hook 'org-read-date-display)
15530 (use-local-map old-map)
15531 (when org-read-date-overlay
15532 (delete-overlay org-read-date-overlay)
15533 (setq org-read-date-overlay nil)))))
15534 (bury-buffer "*Calendar*")))))
15536 (t ; Naked prompt only
15537 (unwind-protect
15538 (setq ans (read-string prompt default-input
15539 'org-read-date-history timestr))
15540 (when org-read-date-overlay
15541 (delete-overlay org-read-date-overlay)
15542 (setq org-read-date-overlay nil)))))
15544 (setq final (org-read-date-analyze ans org-def org-defdecode))
15546 (when org-read-date-analyze-forced-year
15547 (message "Year was forced into %s"
15548 (if org-read-date-force-compatible-dates
15549 "compatible range (1970-2037)"
15550 "range representable on this machine"))
15551 (ding))
15553 ;; One round trip to get rid of 34th of August and stuff like that....
15554 (setq final (decode-time (apply 'encode-time final)))
15556 (setq org-read-date-final-answer ans)
15558 (if to-time
15559 (apply 'encode-time final)
15560 (if (and (boundp 'org-time-was-given) org-time-was-given)
15561 (format "%04d-%02d-%02d %02d:%02d"
15562 (nth 5 final) (nth 4 final) (nth 3 final)
15563 (nth 2 final) (nth 1 final))
15564 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15566 (defvar org-def)
15567 (defvar org-defdecode)
15568 (defvar org-with-time)
15569 (defun org-read-date-display ()
15570 "Display the current date prompt interpretation in the minibuffer."
15571 (when org-read-date-display-live
15572 (when org-read-date-overlay
15573 (delete-overlay org-read-date-overlay))
15574 (when (minibufferp (current-buffer))
15575 (save-excursion
15576 (end-of-line 1)
15577 (while (not (equal (buffer-substring
15578 (max (point-min) (- (point) 4)) (point))
15579 " "))
15580 (insert " ")))
15581 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15582 " " (or org-ans1 org-ans2)))
15583 (org-end-time-was-given nil)
15584 (f (org-read-date-analyze ans org-def org-defdecode))
15585 (fmts (if org-dcst
15586 org-time-stamp-custom-formats
15587 org-time-stamp-formats))
15588 (fmt (if (or org-with-time
15589 (and (boundp 'org-time-was-given) org-time-was-given))
15590 (cdr fmts)
15591 (car fmts)))
15592 (txt (format-time-string fmt (apply 'encode-time f)))
15593 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15594 (txt (concat "=> " txt)))
15595 (when (and org-end-time-was-given
15596 (string-match org-plain-time-of-day-regexp txt))
15597 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15598 org-end-time-was-given
15599 (substring txt (match-end 0)))))
15600 (when org-read-date-analyze-futurep
15601 (setq txt (concat txt " (=>F)")))
15602 (setq org-read-date-overlay
15603 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15604 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15606 (defun org-read-date-analyze (ans org-def org-defdecode)
15607 "Analyze the combined answer of the date prompt."
15608 ;; FIXME: cleanup and comment
15609 (let ((nowdecode (decode-time (current-time)))
15610 delta deltan deltaw deltadef year month day
15611 hour minute second wday pm h2 m2 tl wday1
15612 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15613 (setq org-read-date-analyze-futurep nil
15614 org-read-date-analyze-forced-year nil)
15615 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15616 (setq ans "+0"))
15618 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15619 (unless (save-match-data (string-match org-plain-time-of-day-regexp ans))
15620 (setq ans (replace-match "" t t ans)
15621 deltan (car delta)
15622 deltaw (nth 1 delta)
15623 deltadef (nth 2 delta))))
15625 ;; Check if there is an iso week date in there
15626 ;; If yes, store the info and postpone interpreting it until the rest
15627 ;; of the parsing is done
15628 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15629 (setq iso-year (if (match-end 1)
15630 (org-small-year-to-year
15631 (string-to-number (match-string 1 ans))))
15632 iso-weekday (if (match-end 3)
15633 (string-to-number (match-string 3 ans)))
15634 iso-week (string-to-number (match-string 2 ans)))
15635 (setq ans (replace-match "" t t ans)))
15637 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15638 (when (string-match
15639 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15640 (setq year (if (match-end 2)
15641 (string-to-number (match-string 2 ans))
15642 (progn (setq kill-year t)
15643 (string-to-number (format-time-string "%Y"))))
15644 month (string-to-number (match-string 3 ans))
15645 day (string-to-number (match-string 4 ans)))
15646 (if (< year 100) (setq year (+ 2000 year)))
15647 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15648 t nil ans)))
15650 ;; Help matching dotted european dates
15651 (when (string-match
15652 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15653 (setq year (if (match-end 3)
15654 (string-to-number (match-string 3 ans))
15655 (progn (setq kill-year t)
15656 (string-to-number (format-time-string "%Y"))))
15657 day (string-to-number (match-string 1 ans))
15658 month (string-to-number (match-string 2 ans))
15659 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15660 t nil ans)))
15662 ;; Help matching american dates, like 5/30 or 5/30/7
15663 (when (string-match
15664 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15665 (setq year (if (match-end 4)
15666 (string-to-number (match-string 4 ans))
15667 (progn (setq kill-year t)
15668 (string-to-number (format-time-string "%Y"))))
15669 month (string-to-number (match-string 1 ans))
15670 day (string-to-number (match-string 2 ans)))
15671 (if (< year 100) (setq year (+ 2000 year)))
15672 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15673 t nil ans)))
15674 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15675 ;; If there is a time with am/pm, and *no* time without it, we convert
15676 ;; so that matching will be successful.
15677 (loop for i from 1 to 2 do ; twice, for end time as well
15678 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15679 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15680 (setq hour (string-to-number (match-string 1 ans))
15681 minute (if (match-end 3)
15682 (string-to-number (match-string 3 ans))
15684 pm (equal ?p
15685 (string-to-char (downcase (match-string 4 ans)))))
15686 (if (and (= hour 12) (not pm))
15687 (setq hour 0)
15688 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15689 (setq ans (replace-match (format "%02d:%02d" hour minute)
15690 t t ans))))
15692 ;; Check if a time range is given as a duration
15693 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15694 (setq hour (string-to-number (match-string 1 ans))
15695 h2 (+ hour (string-to-number (match-string 3 ans)))
15696 minute (string-to-number (match-string 2 ans))
15697 m2 (+ minute (if (match-end 5) (string-to-number
15698 (match-string 5 ans))0)))
15699 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15700 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15701 t t ans)))
15703 ;; Check if there is a time range
15704 (when (boundp 'org-end-time-was-given)
15705 (setq org-time-was-given nil)
15706 (when (and (string-match org-plain-time-of-day-regexp ans)
15707 (match-end 8))
15708 (setq org-end-time-was-given (match-string 8 ans))
15709 (setq ans (concat (substring ans 0 (match-beginning 7))
15710 (substring ans (match-end 7))))))
15712 (setq tl (parse-time-string ans)
15713 day (or (nth 3 tl) (nth 3 org-defdecode))
15714 month (or (nth 4 tl)
15715 (if (and org-read-date-prefer-future
15716 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15717 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15718 (nth 4 org-defdecode)))
15719 year (or (and (not kill-year) (nth 5 tl))
15720 (if (and org-read-date-prefer-future
15721 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15722 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15723 (nth 5 org-defdecode)))
15724 hour (or (nth 2 tl) (nth 2 org-defdecode))
15725 minute (or (nth 1 tl) (nth 1 org-defdecode))
15726 second (or (nth 0 tl) 0)
15727 wday (nth 6 tl))
15729 (when (and (eq org-read-date-prefer-future 'time)
15730 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15731 (equal day (nth 3 nowdecode))
15732 (equal month (nth 4 nowdecode))
15733 (equal year (nth 5 nowdecode))
15734 (nth 2 tl)
15735 (or (< (nth 2 tl) (nth 2 nowdecode))
15736 (and (= (nth 2 tl) (nth 2 nowdecode))
15737 (nth 1 tl)
15738 (< (nth 1 tl) (nth 1 nowdecode)))))
15739 (setq day (1+ day)
15740 futurep t))
15742 ;; Special date definitions below
15743 (cond
15744 (iso-week
15745 ;; There was an iso week
15746 (require 'cal-iso)
15747 (setq futurep nil)
15748 (setq year (or iso-year year)
15749 day (or iso-weekday wday 1)
15750 wday nil ; to make sure that the trigger below does not match
15751 iso-date (calendar-gregorian-from-absolute
15752 (calendar-absolute-from-iso
15753 (list iso-week day year))))
15754 ; FIXME: Should we also push ISO weeks into the future?
15755 ; (when (and org-read-date-prefer-future
15756 ; (not iso-year)
15757 ; (< (calendar-absolute-from-gregorian iso-date)
15758 ; (time-to-days (current-time))))
15759 ; (setq year (1+ year)
15760 ; iso-date (calendar-gregorian-from-absolute
15761 ; (calendar-absolute-from-iso
15762 ; (list iso-week day year)))))
15763 (setq month (car iso-date)
15764 year (nth 2 iso-date)
15765 day (nth 1 iso-date)))
15766 (deltan
15767 (setq futurep nil)
15768 (unless deltadef
15769 (let ((now (decode-time (current-time))))
15770 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15771 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15772 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15773 ((equal deltaw "m") (setq month (+ month deltan)))
15774 ((equal deltaw "y") (setq year (+ year deltan)))))
15775 ((and wday (not (nth 3 tl)))
15776 ;; Weekday was given, but no day, so pick that day in the week
15777 ;; on or after the derived date.
15778 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15779 (unless (equal wday wday1)
15780 (setq day (+ day (% (- wday wday1 -7) 7))))))
15781 (if (and (boundp 'org-time-was-given)
15782 (nth 2 tl))
15783 (setq org-time-was-given t))
15784 (if (< year 100) (setq year (+ 2000 year)))
15785 ;; Check of the date is representable
15786 (if org-read-date-force-compatible-dates
15787 (progn
15788 (if (< year 1970)
15789 (setq year 1970 org-read-date-analyze-forced-year t))
15790 (if (> year 2037)
15791 (setq year 2037 org-read-date-analyze-forced-year t)))
15792 (condition-case nil
15793 (ignore (encode-time second minute hour day month year))
15794 (error
15795 (setq year (nth 5 org-defdecode))
15796 (setq org-read-date-analyze-forced-year t))))
15797 (setq org-read-date-analyze-futurep futurep)
15798 (list second minute hour day month year)))
15800 (defvar parse-time-weekdays)
15801 (defun org-read-date-get-relative (s today default)
15802 "Check string S for special relative date string.
15803 TODAY and DEFAULT are internal times, for today and for a default.
15804 Return shift list (N what def-flag)
15805 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15806 N is the number of WHATs to shift.
15807 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15808 the DEFAULT date rather than TODAY."
15809 (require 'parse-time)
15810 (when (and
15811 (string-match
15812 (concat
15813 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15814 "\\([0-9]+\\)?"
15815 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15816 "\\([ \t]\\|$\\)") s)
15817 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15818 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15819 (string-to-char (substring (match-string 1 s) -1))
15820 ?+))
15821 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15822 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15823 (what (if (match-end 3) (match-string 3 s) "d"))
15824 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15825 (date (if rel default today))
15826 (wday (nth 6 (decode-time date)))
15827 delta)
15828 (if wday1
15829 (progn
15830 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15831 (if (= dir ?-) (setq delta (- delta 7)))
15832 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15833 (list delta "d" rel))
15834 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15836 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15837 "Turn a user-specified date into the internal representation.
15838 The internal representation needed by the calendar is (month day year).
15839 This is a wrapper to handle the brain-dead convention in calendar that
15840 user function argument order change dependent on argument order."
15841 (if (boundp 'calendar-date-style)
15842 (cond
15843 ((eq calendar-date-style 'american)
15844 (list arg1 arg2 arg3))
15845 ((eq calendar-date-style 'european)
15846 (list arg2 arg1 arg3))
15847 ((eq calendar-date-style 'iso)
15848 (list arg2 arg3 arg1)))
15849 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15850 (if (org-bound-and-true-p european-calendar-style)
15851 (list arg2 arg1 arg3)
15852 (list arg1 arg2 arg3)))))
15854 (defun org-eval-in-calendar (form &optional keepdate)
15855 "Eval FORM in the calendar window and return to current window.
15856 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15857 otherwise stick to the current value of `org-ans2'."
15858 (let ((sf (selected-frame))
15859 (sw (selected-window)))
15860 (select-window (get-buffer-window "*Calendar*" t))
15861 (eval form)
15862 (when (and (not keepdate) (calendar-cursor-to-date))
15863 (let* ((date (calendar-cursor-to-date))
15864 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15865 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15866 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15867 (select-window sw)
15868 (org-select-frame-set-input-focus sf)))
15870 (defun org-calendar-select ()
15871 "Return to `org-read-date' with the date currently selected.
15872 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15873 (interactive)
15874 (when (calendar-cursor-to-date)
15875 (let* ((date (calendar-cursor-to-date))
15876 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15877 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15878 (if (active-minibuffer-window) (exit-minibuffer))))
15880 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15881 "Insert a date stamp for the date given by the internal TIME.
15882 WITH-HM means use the stamp format that includes the time of the day.
15883 INACTIVE means use square brackets instead of angular ones, so that the
15884 stamp will not contribute to the agenda.
15885 PRE and POST are optional strings to be inserted before and after the
15886 stamp.
15887 The command returns the inserted time stamp."
15888 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15889 stamp)
15890 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15891 (insert-before-markers (or pre ""))
15892 (when (listp extra)
15893 (setq extra (car extra))
15894 (if (and (stringp extra)
15895 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15896 (setq extra (format "-%02d:%02d"
15897 (string-to-number (match-string 1 extra))
15898 (string-to-number (match-string 2 extra))))
15899 (setq extra nil)))
15900 (when extra
15901 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15902 (insert-before-markers (setq stamp (format-time-string fmt time)))
15903 (insert-before-markers (or post ""))
15904 (setq org-last-inserted-timestamp stamp)))
15906 (defun org-toggle-time-stamp-overlays ()
15907 "Toggle the use of custom time stamp formats."
15908 (interactive)
15909 (setq org-display-custom-times (not org-display-custom-times))
15910 (unless org-display-custom-times
15911 (let ((p (point-min)) (bmp (buffer-modified-p)))
15912 (while (setq p (next-single-property-change p 'display))
15913 (if (and (get-text-property p 'display)
15914 (eq (get-text-property p 'face) 'org-date))
15915 (remove-text-properties
15916 p (setq p (next-single-property-change p 'display))
15917 '(display t))))
15918 (set-buffer-modified-p bmp)))
15919 (if (featurep 'xemacs)
15920 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15921 (org-restart-font-lock)
15922 (setq org-table-may-need-update t)
15923 (if org-display-custom-times
15924 (message "Time stamps are overlaid with custom format")
15925 (message "Time stamp overlays removed")))
15927 (defun org-display-custom-time (beg end)
15928 "Overlay modified time stamp format over timestamp between BEG and END."
15929 (let* ((ts (buffer-substring beg end))
15930 t1 w1 with-hm tf time str w2 (off 0))
15931 (save-match-data
15932 (setq t1 (org-parse-time-string ts t))
15933 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15934 (setq off (- (match-end 0) (match-beginning 0)))))
15935 (setq end (- end off))
15936 (setq w1 (- end beg)
15937 with-hm (and (nth 1 t1) (nth 2 t1))
15938 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15939 time (org-fix-decoded-time t1)
15940 str (org-add-props
15941 (format-time-string
15942 (substring tf 1 -1) (apply 'encode-time time))
15943 nil 'mouse-face 'highlight)
15944 w2 (length str))
15945 (if (not (= w2 w1))
15946 (add-text-properties (1+ beg) (+ 2 beg)
15947 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15948 (if (featurep 'xemacs)
15949 (progn
15950 (put-text-property beg end 'invisible t)
15951 (put-text-property beg end 'end-glyph (make-glyph str)))
15952 (put-text-property beg end 'display str))))
15954 (defun org-translate-time (string)
15955 "Translate all timestamps in STRING to custom format.
15956 But do this only if the variable `org-display-custom-times' is set."
15957 (when org-display-custom-times
15958 (save-match-data
15959 (let* ((start 0)
15960 (re org-ts-regexp-both)
15961 t1 with-hm inactive tf time str beg end)
15962 (while (setq start (string-match re string start))
15963 (setq beg (match-beginning 0)
15964 end (match-end 0)
15965 t1 (save-match-data
15966 (org-parse-time-string (substring string beg end) t))
15967 with-hm (and (nth 1 t1) (nth 2 t1))
15968 inactive (equal (substring string beg (1+ beg)) "[")
15969 tf (funcall (if with-hm 'cdr 'car)
15970 org-time-stamp-custom-formats)
15971 time (org-fix-decoded-time t1)
15972 str (format-time-string
15973 (concat
15974 (if inactive "[" "<") (substring tf 1 -1)
15975 (if inactive "]" ">"))
15976 (apply 'encode-time time))
15977 string (replace-match str t t string)
15978 start (+ start (length str)))))))
15979 string)
15981 (defun org-fix-decoded-time (time)
15982 "Set 0 instead of nil for the first 6 elements of time.
15983 Don't touch the rest."
15984 (let ((n 0))
15985 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15987 (defun org-days-to-time (timestamp-string)
15988 "Difference between TIMESTAMP-STRING and now in days."
15989 (- (time-to-days (org-time-string-to-time timestamp-string))
15990 (time-to-days (current-time))))
15992 (defun org-deadline-close (timestamp-string &optional ndays)
15993 "Is the time in TIMESTAMP-STRING close to the current date?"
15994 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15995 (and (< (org-days-to-time timestamp-string) ndays)
15996 (not (org-entry-is-done-p))))
15998 (defun org-get-wdays (ts)
15999 "Get the deadline lead time appropriate for timestring TS."
16000 (cond
16001 ((<= org-deadline-warning-days 0)
16002 ;; 0 or negative, enforce this value no matter what
16003 (- org-deadline-warning-days))
16004 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16005 ;; lead time is specified.
16006 (floor (* (string-to-number (match-string 1 ts))
16007 (cdr (assoc (match-string 2 ts)
16008 '(("d" . 1) ("w" . 7)
16009 ("m" . 30.4) ("y" . 365.25)))))))
16010 ;; go for the default.
16011 (t org-deadline-warning-days)))
16013 (defun org-calendar-select-mouse (ev)
16014 "Return to `org-read-date' with the date currently selected.
16015 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16016 (interactive "e")
16017 (mouse-set-point ev)
16018 (when (calendar-cursor-to-date)
16019 (let* ((date (calendar-cursor-to-date))
16020 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16021 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16022 (if (active-minibuffer-window) (exit-minibuffer))))
16024 (defun org-check-deadlines (ndays)
16025 "Check if there are any deadlines due or past due.
16026 A deadline is considered due if it happens within `org-deadline-warning-days'
16027 days from today's date. If the deadline appears in an entry marked DONE,
16028 it is not shown. The prefix arg NDAYS can be used to test that many
16029 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16030 (interactive "P")
16031 (let* ((org-warn-days
16032 (cond
16033 ((equal ndays '(4)) 100000)
16034 (ndays (prefix-numeric-value ndays))
16035 (t (abs org-deadline-warning-days))))
16036 (case-fold-search nil)
16037 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16038 (callback
16039 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16041 (message "%d deadlines past-due or due within %d days"
16042 (org-occur regexp nil callback)
16043 org-warn-days)))
16045 (defsubst org-re-timestamp (type)
16046 "Return a regexp for timestamp TYPE.
16047 Allowed values for TYPE are:
16049 all: all timestamps
16050 active: only active timestamps (<...>)
16051 inactive: only inactive timestamps ([...])
16052 scheduled: only scheduled timestamps
16053 deadline: only deadline timestamps
16055 When TYPE is nil, fall back on returning a regexp that matches
16056 both scheduled and deadline timestamps."
16057 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16058 ((eq type 'active) org-ts-regexp)
16059 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16060 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16061 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16062 ((eq type 'scheduled-or-deadline)
16063 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16065 (defun org-check-before-date (date)
16066 "Check if there are deadlines or scheduled entries before DATE."
16067 (interactive (list (org-read-date)))
16068 (let ((case-fold-search nil)
16069 (regexp (org-re-timestamp org-ts-type))
16070 (callback
16071 (lambda () (time-less-p
16072 (org-time-string-to-time (match-string 1))
16073 (org-time-string-to-time date)))))
16074 (message "%d entries before %s"
16075 (org-occur regexp nil callback) date)))
16077 (defun org-check-after-date (date)
16078 "Check if there are deadlines or scheduled entries after DATE."
16079 (interactive (list (org-read-date)))
16080 (let ((case-fold-search nil)
16081 (regexp (org-re-timestamp org-ts-type))
16082 (callback
16083 (lambda () (not
16084 (time-less-p
16085 (org-time-string-to-time (match-string 1))
16086 (org-time-string-to-time date))))))
16087 (message "%d entries after %s"
16088 (org-occur regexp nil callback) date)))
16090 (defun org-check-dates-range (start-date end-date)
16091 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16092 (interactive (list (org-read-date nil nil nil "Range starts")
16093 (org-read-date nil nil nil "Range end")))
16094 (let ((case-fold-search nil)
16095 (regexp (org-re-timestamp org-ts-type))
16096 (callback
16097 (lambda ()
16098 (let ((match (match-string 1)))
16099 (and
16100 (not (time-less-p
16101 (org-time-string-to-time match)
16102 (org-time-string-to-time start-date)))
16103 (time-less-p
16104 (org-time-string-to-time match)
16105 (org-time-string-to-time end-date)))))))
16106 (message "%d entries between %s and %s"
16107 (org-occur regexp nil callback) start-date end-date)))
16109 (defun org-evaluate-time-range (&optional to-buffer)
16110 "Evaluate a time range by computing the difference between start and end.
16111 Normally the result is just printed in the echo area, but with prefix arg
16112 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16113 If the time range is actually in a table, the result is inserted into the
16114 next column.
16115 For time difference computation, a year is assumed to be exactly 365
16116 days in order to avoid rounding problems."
16117 (interactive "P")
16119 (org-clock-update-time-maybe)
16120 (save-excursion
16121 (unless (org-at-date-range-p t)
16122 (goto-char (point-at-bol))
16123 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16124 (if (not (org-at-date-range-p t))
16125 (error "Not at a time-stamp range, and none found in current line")))
16126 (let* ((ts1 (match-string 1))
16127 (ts2 (match-string 2))
16128 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16129 (match-end (match-end 0))
16130 (time1 (org-time-string-to-time ts1))
16131 (time2 (org-time-string-to-time ts2))
16132 (t1 (org-float-time time1))
16133 (t2 (org-float-time time2))
16134 (diff (abs (- t2 t1)))
16135 (negative (< (- t2 t1) 0))
16136 ;; (ys (floor (* 365 24 60 60)))
16137 (ds (* 24 60 60))
16138 (hs (* 60 60))
16139 (fy "%dy %dd %02d:%02d")
16140 (fy1 "%dy %dd")
16141 (fd "%dd %02d:%02d")
16142 (fd1 "%dd")
16143 (fh "%02d:%02d")
16144 y d h m align)
16145 (if havetime
16146 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16148 d (floor (/ diff ds)) diff (mod diff ds)
16149 h (floor (/ diff hs)) diff (mod diff hs)
16150 m (floor (/ diff 60)))
16151 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16153 d (floor (+ (/ diff ds) 0.5))
16154 h 0 m 0))
16155 (if (not to-buffer)
16156 (message "%s" (org-make-tdiff-string y d h m))
16157 (if (org-at-table-p)
16158 (progn
16159 (goto-char match-end)
16160 (setq align t)
16161 (and (looking-at " *|") (goto-char (match-end 0))))
16162 (goto-char match-end))
16163 (if (looking-at
16164 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16165 (replace-match ""))
16166 (if negative (insert " -"))
16167 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16168 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16169 (insert " " (format fh h m))))
16170 (if align (org-table-align))
16171 (message "Time difference inserted")))))
16173 (defun org-make-tdiff-string (y d h m)
16174 (let ((fmt "")
16175 (l nil))
16176 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16177 l (push y l)))
16178 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16179 l (push d l)))
16180 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16181 l (push h l)))
16182 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16183 l (push m l)))
16184 (apply 'format fmt (nreverse l))))
16186 (defun org-time-string-to-time (s &optional buffer pos)
16187 (condition-case errdata
16188 (apply 'encode-time (org-parse-time-string s))
16189 (error (error "Bad timestamp `%s'%s\nError was: %s"
16190 s (if (not (and buffer pos))
16192 (format " at %d in buffer `%s'" pos buffer))
16193 (cdr errdata)))))
16195 (defun org-time-string-to-seconds (s)
16196 (org-float-time (org-time-string-to-time s)))
16198 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16199 "Convert a time stamp to an absolute day number.
16200 If there is a specifier for a cyclic time stamp, get the closest date to
16201 DAYNR.
16202 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16203 The variable date is bound by the calendar when this is called."
16204 (cond
16205 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16206 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16207 daynr
16208 (+ daynr 1000)))
16209 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16210 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16211 (time-to-days (current-time))) (match-string 0 s)
16212 prefer show-all))
16213 (t (time-to-days
16214 (condition-case errdata
16215 (apply 'encode-time (org-parse-time-string s))
16216 (error (error "Bad timestamp `%s'%s\nError was: %s"
16217 s (if (not (and buffer pos))
16219 (format " at %d in buffer `%s'" pos buffer))
16220 (cdr errdata))))))))
16222 (defun org-days-to-iso-week (days)
16223 "Return the iso week number."
16224 (require 'cal-iso)
16225 (car (calendar-iso-from-absolute days)))
16227 (defun org-small-year-to-year (year)
16228 "Convert 2-digit years into 4-digit years.
16229 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16230 The year 2000 cannot be abbreviated. Any year larger than 99
16231 is returned unchanged."
16232 (if (< year 38)
16233 (setq year (+ 2000 year))
16234 (if (< year 100)
16235 (setq year (+ 1900 year))))
16236 year)
16238 (defun org-time-from-absolute (d)
16239 "Return the time corresponding to date D.
16240 D may be an absolute day number, or a calendar-type list (month day year)."
16241 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16242 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16244 (defun org-calendar-holiday ()
16245 "List of holidays, for Diary display in Org-mode."
16246 (require 'holidays)
16247 (let ((hl (funcall
16248 (if (fboundp 'calendar-check-holidays)
16249 'calendar-check-holidays 'check-calendar-holidays) date)))
16250 (if hl (mapconcat 'identity hl "; "))))
16252 (defun org-diary-sexp-entry (sexp entry date)
16253 "Process a SEXP diary ENTRY for DATE."
16254 (require 'diary-lib)
16255 (let ((result (if calendar-debug-sexp
16256 (let ((stack-trace-on-error t))
16257 (eval (car (read-from-string sexp))))
16258 (condition-case nil
16259 (eval (car (read-from-string sexp)))
16260 (error
16261 (beep)
16262 (message "Bad sexp at line %d in %s: %s"
16263 (org-current-line)
16264 (buffer-file-name) sexp)
16265 (sleep-for 2))))))
16266 (cond ((stringp result) (split-string result "; "))
16267 ((and (consp result)
16268 (not (consp (cdr result)))
16269 (stringp (cdr result))) (cdr result))
16270 ((and (consp result)
16271 (stringp (car result))) result)
16272 (result entry))))
16274 (defun org-diary-to-ical-string (frombuf)
16275 "Get iCalendar entries from diary entries in buffer FROMBUF.
16276 This uses the icalendar.el library."
16277 (let* ((tmpdir (if (featurep 'xemacs)
16278 (temp-directory)
16279 temporary-file-directory))
16280 (tmpfile (make-temp-name
16281 (expand-file-name "orgics" tmpdir)))
16282 buf rtn b e)
16283 (with-current-buffer frombuf
16284 (icalendar-export-region (point-min) (point-max) tmpfile)
16285 (setq buf (find-buffer-visiting tmpfile))
16286 (set-buffer buf)
16287 (goto-char (point-min))
16288 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16289 (setq b (match-beginning 0)))
16290 (goto-char (point-max))
16291 (if (re-search-backward "^END:VEVENT" nil t)
16292 (setq e (match-end 0)))
16293 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16294 (kill-buffer buf)
16295 (delete-file tmpfile)
16296 rtn))
16298 (defun org-closest-date (start current change prefer show-all)
16299 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16300 When PREFER is `past', return a date that is either CURRENT or past.
16301 When PREFER is `future', return a date that is either CURRENT or future.
16302 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16303 ;; Make the proper lists from the dates
16304 (catch 'exit
16305 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16306 dn dw sday cday n1 n2 n0
16307 d m y y1 y2 date1 date2 nmonths nm ny m2)
16309 (setq start (org-date-to-gregorian start)
16310 current (org-date-to-gregorian
16311 (if show-all
16312 current
16313 (time-to-days (current-time))))
16314 sday (calendar-absolute-from-gregorian start)
16315 cday (calendar-absolute-from-gregorian current))
16317 (if (<= cday sday) (throw 'exit sday))
16319 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16320 (setq dn (string-to-number (match-string 1 change))
16321 dw (cdr (assoc (match-string 2 change) a1)))
16322 (error "Invalid change specifier: %s" change))
16323 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16324 (cond
16325 ((eq dw 'day)
16326 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16327 n2 (+ n1 dn)))
16328 ((eq dw 'year)
16329 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16330 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16331 (setq date1 (list m d y1)
16332 n1 (calendar-absolute-from-gregorian date1)
16333 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16334 n2 (calendar-absolute-from-gregorian date2)))
16335 ((eq dw 'month)
16336 ;; approx number of month between the two dates
16337 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16338 ;; How often does dn fit in there?
16339 (setq d (nth 1 start) m (car start) y (nth 2 start)
16340 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16341 m (+ m nm)
16342 ny (floor (/ m 12))
16343 y (+ y ny)
16344 m (- m (* ny 12)))
16345 (while (> m 12) (setq m (- m 12) y (1+ y)))
16346 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16347 (setq m2 (+ m dn) y2 y)
16348 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16349 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16350 (while (<= n2 cday)
16351 (setq n1 n2 m m2 y y2)
16352 (setq m2 (+ m dn) y2 y)
16353 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16354 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16355 ;; Make sure n1 is the earlier date
16356 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16357 (if show-all
16358 (cond
16359 ((eq prefer 'past) (if (= cday n2) n2 n1))
16360 ((eq prefer 'future) (if (= cday n1) n1 n2))
16361 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16362 (cond
16363 ((eq prefer 'past) (if (= cday n2) n2 n1))
16364 ((eq prefer 'future) (if (= cday n1) n1 n2))
16365 (t (if (= cday n1) n1 n2)))))))
16367 (defun org-date-to-gregorian (date)
16368 "Turn any specification of DATE into a Gregorian date for the calendar."
16369 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16370 ((and (listp date) (= (length date) 3)) date)
16371 ((stringp date)
16372 (setq date (org-parse-time-string date))
16373 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16374 ((listp date)
16375 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16377 (defun org-parse-time-string (s &optional nodefault)
16378 "Parse the standard Org-mode time string.
16379 This should be a lot faster than the normal `parse-time-string'.
16380 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16381 hour and minute fields will be nil if not given."
16382 (if (string-match org-ts-regexp0 s)
16383 (list 0
16384 (if (or (match-beginning 8) (not nodefault))
16385 (string-to-number (or (match-string 8 s) "0")))
16386 (if (or (match-beginning 7) (not nodefault))
16387 (string-to-number (or (match-string 7 s) "0")))
16388 (string-to-number (match-string 4 s))
16389 (string-to-number (match-string 3 s))
16390 (string-to-number (match-string 2 s))
16391 nil nil nil)
16392 (error "Not a standard Org-mode time string: %s" s)))
16394 (defun org-timestamp-up (&optional arg)
16395 "Increase the date item at the cursor by one.
16396 If the cursor is on the year, change the year. If it is on the month,
16397 the day or the time, change that.
16398 With prefix ARG, change by that many units."
16399 (interactive "p")
16400 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16402 (defun org-timestamp-down (&optional arg)
16403 "Decrease the date item at the cursor by one.
16404 If the cursor is on the year, change the year. If it is on the month,
16405 the day or the time, change that.
16406 With prefix ARG, change by that many units."
16407 (interactive "p")
16408 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16410 (defun org-timestamp-up-day (&optional arg)
16411 "Increase the date in the time stamp by one day.
16412 With prefix ARG, change that many days."
16413 (interactive "p")
16414 (if (and (not (org-at-timestamp-p t))
16415 (org-at-heading-p))
16416 (org-todo 'up)
16417 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16419 (defun org-timestamp-down-day (&optional arg)
16420 "Decrease the date in the time stamp by one day.
16421 With prefix ARG, change that many days."
16422 (interactive "p")
16423 (if (and (not (org-at-timestamp-p t))
16424 (org-at-heading-p))
16425 (org-todo 'down)
16426 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16428 (defun org-at-timestamp-p (&optional inactive-ok)
16429 "Determine if the cursor is in or at a timestamp."
16430 (interactive)
16431 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16432 (pos (point))
16433 (ans (or (looking-at tsr)
16434 (save-excursion
16435 (skip-chars-backward "^[<\n\r\t")
16436 (if (> (point) (point-min)) (backward-char 1))
16437 (and (looking-at tsr)
16438 (> (- (match-end 0) pos) -1))))))
16439 (and ans
16440 (boundp 'org-ts-what)
16441 (setq org-ts-what
16442 (cond
16443 ((= pos (match-beginning 0)) 'bracket)
16444 ;; Point is considered to be "on the bracket" whether
16445 ;; it's really on it or right after it.
16446 ((= pos (1- (match-end 0))) 'bracket)
16447 ((= pos (match-end 0)) 'after)
16448 ((org-pos-in-match-range pos 2) 'year)
16449 ((org-pos-in-match-range pos 3) 'month)
16450 ((org-pos-in-match-range pos 7) 'hour)
16451 ((org-pos-in-match-range pos 8) 'minute)
16452 ((or (org-pos-in-match-range pos 4)
16453 (org-pos-in-match-range pos 5)) 'day)
16454 ((and (> pos (or (match-end 8) (match-end 5)))
16455 (< pos (match-end 0)))
16456 (- pos (or (match-end 8) (match-end 5))))
16457 (t 'day))))
16458 ans))
16460 (defun org-toggle-timestamp-type ()
16461 "Toggle the type (<active> or [inactive]) of a time stamp."
16462 (interactive)
16463 (when (org-at-timestamp-p t)
16464 (let ((beg (match-beginning 0)) (end (match-end 0))
16465 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16466 (save-excursion
16467 (goto-char beg)
16468 (while (re-search-forward "[][<>]" end t)
16469 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16470 t t)))
16471 (message "Timestamp is now %sactive"
16472 (if (equal (char-after beg) ?<) "" "in")))))
16474 (defvar org-clock-history) ; defined in org-clock.el
16475 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16476 (defun org-timestamp-change (n &optional what updown)
16477 "Change the date in the time stamp at point.
16478 The date will be changed by N times WHAT. WHAT can be `day', `month',
16479 `year', `minute', `second'. If WHAT is not given, the cursor position
16480 in the timestamp determines what will be changed."
16481 (let ((origin (point)) origin-cat
16482 with-hm inactive
16483 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16484 org-ts-what
16485 extra rem
16486 ts time time0 fixnext clrgx)
16487 (if (not (org-at-timestamp-p t))
16488 (error "Not at a timestamp"))
16489 (if (and (not what) (eq org-ts-what 'bracket))
16490 (org-toggle-timestamp-type)
16491 ;; Point isn't on brackets. Remember the part of the time-stamp
16492 ;; the point was in. Indeed, size of time-stamps may change,
16493 ;; but point must be kept in the same category nonetheless.
16494 (setq origin-cat org-ts-what)
16495 (if (and (not what) (not (eq org-ts-what 'day))
16496 org-display-custom-times
16497 (get-text-property (point) 'display)
16498 (not (get-text-property (1- (point)) 'display)))
16499 (setq org-ts-what 'day))
16500 (setq org-ts-what (or what org-ts-what)
16501 inactive (= (char-after (match-beginning 0)) ?\[)
16502 ts (match-string 0))
16503 (replace-match "")
16504 (if (string-match
16505 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16507 (setq extra (match-string 1 ts)))
16508 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16509 (setq with-hm t))
16510 (setq time0 (org-parse-time-string ts))
16511 (when (and updown
16512 (eq org-ts-what 'minute)
16513 (not current-prefix-arg))
16514 ;; This looks like s-up and s-down. Change by one rounding step.
16515 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16516 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16517 (setcar (cdr time0) (+ (nth 1 time0)
16518 (if (> n 0) (- rem) (- dm rem))))))
16519 (setq time
16520 (encode-time (or (car time0) 0)
16521 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16522 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16523 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16524 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16525 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16526 (nthcdr 6 time0)))
16527 (when (and (member org-ts-what '(hour minute))
16528 extra
16529 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16530 (setq extra (org-modify-ts-extra
16531 extra
16532 (if (eq org-ts-what 'hour) 2 5)
16533 n dm)))
16534 (when (integerp org-ts-what)
16535 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16536 (if (eq what 'calendar)
16537 (let ((cal-date (org-get-date-from-calendar)))
16538 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16539 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16540 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16541 (setcar time0 (or (car time0) 0))
16542 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16543 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16544 (setq time (apply 'encode-time time0))))
16545 ;; Insert the new time-stamp, and ensure point stays in the same
16546 ;; category as before (i.e. not after the last position in that
16547 ;; category).
16548 (let ((pos (point)))
16549 ;; Stay before inserted string. `save-excursion' is of no use.
16550 (setq org-last-changed-timestamp
16551 (org-insert-time-stamp time with-hm inactive nil nil extra))
16552 (goto-char pos))
16553 (save-match-data
16554 (looking-at org-ts-regexp3)
16555 (goto-char (cond
16556 ;; `day' category ends before `hour' if any, or at
16557 ;; the end of the day name.
16558 ((eq origin-cat 'day)
16559 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16560 ((eq origin-cat 'hour) (min (match-end 7) origin))
16561 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16562 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16563 ;; `year' and `month' have both fixed size: point
16564 ;; couldn't have moved into another part.
16565 (t origin))))
16566 ;; Update clock if on a CLOCK line.
16567 (org-clock-update-time-maybe)
16568 ;; Maybe adjust the closest clock in `org-clock-history'
16569 (when org-clock-adjust-closest
16570 (if (not (and (org-at-clock-log-p)
16571 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16572 org-clock-history))))))
16573 (message "No clock to adjust")
16574 (cond ((save-excursion ; fix previous clock?
16575 (re-search-backward org-ts-regexp0 nil t)
16576 (org-looking-back (concat org-clock-string " \\[")))
16577 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16578 ((save-excursion ; fix next clock?
16579 (re-search-backward org-ts-regexp0 nil t)
16580 (looking-at (concat org-ts-regexp0 "\\] =>")))
16581 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16582 (save-window-excursion
16583 ;; Find closest clock to point, adjust the previous/next one in history
16584 (let* ((p (save-excursion (org-back-to-heading t)))
16585 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16586 (clfixnth
16587 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16588 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16589 (if (not clfixpos)
16590 (message "No clock to adjust")
16591 (save-excursion
16592 (org-goto-marker-or-bmk clfixpos)
16593 (org-show-subtree)
16594 (when (re-search-forward clrgx nil t)
16595 (goto-char (match-beginning 1))
16596 (let (org-clock-adjust-closest)
16597 (org-timestamp-change n org-ts-what updown))
16598 (message "Clock adjusted in %s for heading: %s"
16599 (file-name-nondirectory (buffer-file-name))
16600 (org-get-heading t t)))))))))
16601 ;; Try to recenter the calendar window, if any.
16602 (if (and org-calendar-follow-timestamp-change
16603 (get-buffer-window "*Calendar*" t)
16604 (memq org-ts-what '(day month year)))
16605 (org-recenter-calendar (time-to-days time))))))
16607 (defun org-modify-ts-extra (s pos n dm)
16608 "Change the different parts of the lead-time and repeat fields in timestamp."
16609 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16610 ng h m new rem)
16611 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16612 (cond
16613 ((or (org-pos-in-match-range pos 2)
16614 (org-pos-in-match-range pos 3))
16615 (setq m (string-to-number (match-string 3 s))
16616 h (string-to-number (match-string 2 s)))
16617 (if (org-pos-in-match-range pos 2)
16618 (setq h (+ h n))
16619 (setq n (* dm (org-no-warnings (signum n))))
16620 (when (not (= 0 (setq rem (% m dm))))
16621 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16622 (setq m (+ m n)))
16623 (if (< m 0) (setq m (+ m 60) h (1- h)))
16624 (if (> m 59) (setq m (- m 60) h (1+ h)))
16625 (setq h (min 24 (max 0 h)))
16626 (setq ng 1 new (format "-%02d:%02d" h m)))
16627 ((org-pos-in-match-range pos 6)
16628 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16629 ((org-pos-in-match-range pos 5)
16630 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16632 ((org-pos-in-match-range pos 9)
16633 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16634 ((org-pos-in-match-range pos 8)
16635 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16637 (when ng
16638 (setq s (concat
16639 (substring s 0 (match-beginning ng))
16641 (substring s (match-end ng))))))
16644 (defun org-recenter-calendar (date)
16645 "If the calendar is visible, recenter it to DATE."
16646 (let ((cwin (get-buffer-window "*Calendar*" t)))
16647 (when cwin
16648 (let ((calendar-move-hook nil))
16649 (with-selected-window cwin
16650 (calendar-goto-date (if (listp date) date
16651 (calendar-gregorian-from-absolute date))))))))
16653 (defun org-goto-calendar (&optional arg)
16654 "Go to the Emacs calendar at the current date.
16655 If there is a time stamp in the current line, go to that date.
16656 A prefix ARG can be used to force the current date."
16657 (interactive "P")
16658 (let ((tsr org-ts-regexp) diff
16659 (calendar-move-hook nil)
16660 (calendar-view-holidays-initially-flag nil)
16661 (calendar-view-diary-initially-flag nil))
16662 (if (or (org-at-timestamp-p)
16663 (save-excursion
16664 (beginning-of-line 1)
16665 (looking-at (concat ".*" tsr))))
16666 (let ((d1 (time-to-days (current-time)))
16667 (d2 (time-to-days
16668 (org-time-string-to-time (match-string 1)))))
16669 (setq diff (- d2 d1))))
16670 (calendar)
16671 (calendar-goto-today)
16672 (if (and diff (not arg)) (calendar-forward-day diff))))
16674 (defun org-get-date-from-calendar ()
16675 "Return a list (month day year) of date at point in calendar."
16676 (with-current-buffer "*Calendar*"
16677 (save-match-data
16678 (calendar-cursor-to-date))))
16680 (defun org-date-from-calendar ()
16681 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16682 If there is already a time stamp at the cursor position, update it."
16683 (interactive)
16684 (if (org-at-timestamp-p t)
16685 (org-timestamp-change 0 'calendar)
16686 (let ((cal-date (org-get-date-from-calendar)))
16687 (org-insert-time-stamp
16688 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16690 (defun org-minutes-to-hh:mm-string (m)
16691 "Compute H:MM from a number of minutes."
16692 (let ((h (/ m 60)))
16693 (setq m (- m (* 60 h)))
16694 (format org-time-clocksum-format h m)))
16696 (defun org-hh:mm-string-to-minutes (s)
16697 "Convert a string H:MM to a number of minutes.
16698 If the string is just a number, interpret it as minutes.
16699 In fact, the first hh:mm or number in the string will be taken,
16700 there can be extra stuff in the string.
16701 If no number is found, the return value is 0."
16702 (cond
16703 ((integerp s) s)
16704 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16705 (+ (* (string-to-number (match-string 1 s)) 60)
16706 (string-to-number (match-string 2 s))))
16707 ((string-match "\\([0-9]+\\)" s)
16708 (string-to-number (match-string 1 s)))
16709 (t 0)))
16711 (defcustom org-effort-durations
16712 `(("h" . 60)
16713 ("d" . ,(* 60 8))
16714 ("w" . ,(* 60 8 5))
16715 ("m" . ,(* 60 8 5 4))
16716 ("y" . ,(* 60 8 5 40)))
16717 "Conversion factor to minutes for an effort modifier.
16719 Each entry has the form (MODIFIER . MINUTES).
16721 In an effort string, a number followed by MODIFIER is multiplied
16722 by the specified number of MINUTES to obtain an effort in
16723 minutes.
16725 For example, if the value of this variable is ((\"hours\" . 60)), then an
16726 effort string \"2hours\" is equivalent to 120 minutes."
16727 :group 'org-agenda
16728 :version "24.1"
16729 :type '(alist :key-type (string :tag "Modifier")
16730 :value-type (number :tag "Minutes")))
16732 (defun org-duration-string-to-minutes (s &optional output-to-string)
16733 "Convert a duration string S to minutes.
16735 A bare number is interpreted as minutes, modifiers can be set by
16736 customizing `org-effort-durations' (which see).
16738 Entries containing a colon are interpreted as H:MM by
16739 `org-hh:mm-string-to-minutes'."
16740 (let ((result 0)
16741 (re (concat "\\([0-9.]+\\) *\\("
16742 (regexp-opt (mapcar 'car org-effort-durations))
16743 "\\)")))
16744 (while (string-match re s)
16745 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16746 (string-to-number (match-string 1 s))))
16747 (setq s (replace-match "" nil t s)))
16748 (setq result (floor result))
16749 (incf result (org-hh:mm-string-to-minutes s))
16750 (if output-to-string (number-to-string result) result)))
16752 ;;;; Files
16754 (defun org-save-all-org-buffers ()
16755 "Save all Org-mode buffers without user confirmation."
16756 (interactive)
16757 (message "Saving all Org-mode buffers...")
16758 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16759 (when (featurep 'org-id) (org-id-locations-save))
16760 (message "Saving all Org-mode buffers... done"))
16762 (defun org-revert-all-org-buffers ()
16763 "Revert all Org-mode buffers.
16764 Prompt for confirmation when there are unsaved changes.
16765 Be sure you know what you are doing before letting this function
16766 overwrite your changes.
16768 This function is useful in a setup where one tracks org files
16769 with a version control system, to revert on one machine after pulling
16770 changes from another. I believe the procedure must be like this:
16772 1. M-x org-save-all-org-buffers
16773 2. Pull changes from the other machine, resolve conflicts
16774 3. M-x org-revert-all-org-buffers"
16775 (interactive)
16776 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16777 (error "Abort"))
16778 (save-excursion
16779 (save-window-excursion
16780 (mapc
16781 (lambda (b)
16782 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16783 (with-current-buffer b buffer-file-name))
16784 (org-pop-to-buffer-same-window b)
16785 (revert-buffer t 'no-confirm)))
16786 (buffer-list))
16787 (when (and (featurep 'org-id) org-id-track-globally)
16788 (org-id-locations-load)))))
16790 ;;;; Agenda files
16792 ;;;###autoload
16793 (defun org-switchb (&optional arg)
16794 "Switch between Org buffers.
16795 With one prefix argument, restrict available buffers to files.
16796 With two prefix arguments, restrict available buffers to agenda files.
16798 Defaults to `iswitchb' for buffer name completion.
16799 Set `org-completion-use-ido' to make it use ido instead."
16800 (interactive "P")
16801 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16802 ((equal arg '(16)) (org-buffer-list 'agenda))
16803 (t (org-buffer-list))))
16804 (org-completion-use-iswitchb org-completion-use-iswitchb)
16805 (org-completion-use-ido org-completion-use-ido))
16806 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16807 (setq org-completion-use-iswitchb t))
16808 (org-pop-to-buffer-same-window
16809 (org-icompleting-read "Org buffer: "
16810 (mapcar 'list (mapcar 'buffer-name blist))
16811 nil t))))
16813 ;;; Define some older names previously used for this functionality
16814 ;;;###autoload
16815 (defalias 'org-ido-switchb 'org-switchb)
16816 ;;;###autoload
16817 (defalias 'org-iswitchb 'org-switchb)
16819 (defun org-buffer-list (&optional predicate exclude-tmp)
16820 "Return a list of Org buffers.
16821 PREDICATE can be `export', `files' or `agenda'.
16823 export restrict the list to Export buffers.
16824 files restrict the list to buffers visiting Org files.
16825 agenda restrict the list to buffers visiting agenda files.
16827 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16828 (let* ((bfn nil)
16829 (agenda-files (and (eq predicate 'agenda)
16830 (mapcar 'file-truename (org-agenda-files t))))
16831 (filter
16832 (cond
16833 ((eq predicate 'files)
16834 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16835 ((eq predicate 'export)
16836 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16837 ((eq predicate 'agenda)
16838 (lambda (b)
16839 (with-current-buffer b
16840 (and (derived-mode-p 'org-mode)
16841 (setq bfn (buffer-file-name b))
16842 (member (file-truename bfn) agenda-files)))))
16843 (t (lambda (b) (with-current-buffer b
16844 (or (derived-mode-p 'org-mode)
16845 (string-match "\*Org .*Export"
16846 (buffer-name b)))))))))
16847 (delq nil
16848 (mapcar
16849 (lambda(b)
16850 (if (and (funcall filter b)
16851 (or (not exclude-tmp)
16852 (not (string-match "tmp" (buffer-name b)))))
16854 nil))
16855 (buffer-list)))))
16857 (defun org-agenda-files (&optional unrestricted archives)
16858 "Get the list of agenda files.
16859 Optional UNRESTRICTED means return the full list even if a restriction
16860 is currently in place.
16861 When ARCHIVES is t, include all archive files that are really being
16862 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16863 `org-agenda-archives-mode' is t."
16864 (let ((files
16865 (cond
16866 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16867 ((stringp org-agenda-files) (org-read-agenda-file-list))
16868 ((listp org-agenda-files) org-agenda-files)
16869 (t (error "Invalid value of `org-agenda-files'")))))
16870 (setq files (apply 'append
16871 (mapcar (lambda (f)
16872 (if (file-directory-p f)
16873 (directory-files
16874 f t org-agenda-file-regexp)
16875 (list f)))
16876 files)))
16877 (when org-agenda-skip-unavailable-files
16878 (setq files (delq nil
16879 (mapcar (function
16880 (lambda (file)
16881 (and (file-readable-p file) file)))
16882 files))))
16883 (when (or (eq archives t)
16884 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16885 (setq files (org-add-archive-files files)))
16886 files))
16888 (defun org-agenda-file-p (&optional file)
16889 "Return non-nil, if FILE is an agenda file.
16890 If FILE is omitted, use the file associated with the current
16891 buffer."
16892 (member (or file (buffer-file-name))
16893 (org-agenda-files t)))
16895 (defun org-edit-agenda-file-list ()
16896 "Edit the list of agenda files.
16897 Depending on setup, this either uses customize to edit the variable
16898 `org-agenda-files', or it visits the file that is holding the list. In the
16899 latter case, the buffer is set up in a way that saving it automatically kills
16900 the buffer and restores the previous window configuration."
16901 (interactive)
16902 (if (stringp org-agenda-files)
16903 (let ((cw (current-window-configuration)))
16904 (find-file org-agenda-files)
16905 (org-set-local 'org-window-configuration cw)
16906 (org-add-hook 'after-save-hook
16907 (lambda ()
16908 (set-window-configuration
16909 (prog1 org-window-configuration
16910 (kill-buffer (current-buffer))))
16911 (org-install-agenda-files-menu)
16912 (message "New agenda file list installed"))
16913 nil 'local)
16914 (message "%s" (substitute-command-keys
16915 "Edit list and finish with \\[save-buffer]")))
16916 (customize-variable 'org-agenda-files)))
16918 (defun org-store-new-agenda-file-list (list)
16919 "Set new value for the agenda file list and save it correctly."
16920 (if (stringp org-agenda-files)
16921 (let ((fe (org-read-agenda-file-list t)) b u)
16922 (while (setq b (find-buffer-visiting org-agenda-files))
16923 (kill-buffer b))
16924 (with-temp-file org-agenda-files
16925 (insert
16926 (mapconcat
16927 (lambda (f) ;; Keep un-expanded entries.
16928 (if (setq u (assoc f fe))
16929 (cdr u)
16931 list "\n")
16932 "\n")))
16933 (let ((org-mode-hook nil) (org-inhibit-startup t)
16934 (org-insert-mode-line-in-empty-file nil))
16935 (setq org-agenda-files list)
16936 (customize-save-variable 'org-agenda-files org-agenda-files))))
16938 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16939 "Read the list of agenda files from a file.
16940 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16941 filenames, used by `org-store-new-agenda-file-list' to write back
16942 un-expanded file names."
16943 (when (file-directory-p org-agenda-files)
16944 (error "`org-agenda-files' cannot be a single directory"))
16945 (when (stringp org-agenda-files)
16946 (with-temp-buffer
16947 (insert-file-contents org-agenda-files)
16948 (mapcar
16949 (lambda (f)
16950 (let ((e (expand-file-name (substitute-in-file-name f)
16951 org-directory)))
16952 (if pair-with-expansion
16953 (cons e f)
16954 e)))
16955 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16957 ;;;###autoload
16958 (defun org-cycle-agenda-files ()
16959 "Cycle through the files in `org-agenda-files'.
16960 If the current buffer visits an agenda file, find the next one in the list.
16961 If the current buffer does not, find the first agenda file."
16962 (interactive)
16963 (let* ((fs (org-agenda-files t))
16964 (files (append fs (list (car fs))))
16965 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16966 file)
16967 (unless files (error "No agenda files"))
16968 (catch 'exit
16969 (while (setq file (pop files))
16970 (if (equal (file-truename file) tcf)
16971 (when (car files)
16972 (find-file (car files))
16973 (throw 'exit t))))
16974 (find-file (car fs)))
16975 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16977 (defun org-agenda-file-to-front (&optional to-end)
16978 "Move/add the current file to the top of the agenda file list.
16979 If the file is not present in the list, it is added to the front. If it is
16980 present, it is moved there. With optional argument TO-END, add/move to the
16981 end of the list."
16982 (interactive "P")
16983 (let ((org-agenda-skip-unavailable-files nil)
16984 (file-alist (mapcar (lambda (x)
16985 (cons (file-truename x) x))
16986 (org-agenda-files t)))
16987 (ctf (file-truename buffer-file-name))
16988 x had)
16989 (setq x (assoc ctf file-alist) had x)
16991 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16992 (if to-end
16993 (setq file-alist (append (delq x file-alist) (list x)))
16994 (setq file-alist (cons x (delq x file-alist))))
16995 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16996 (org-install-agenda-files-menu)
16997 (message "File %s to %s of agenda file list"
16998 (if had "moved" "added") (if to-end "end" "front"))))
17000 (defun org-remove-file (&optional file)
17001 "Remove current file from the list of files in variable `org-agenda-files'.
17002 These are the files which are being checked for agenda entries.
17003 Optional argument FILE means use this file instead of the current."
17004 (interactive)
17005 (let* ((org-agenda-skip-unavailable-files nil)
17006 (file (or file buffer-file-name))
17007 (true-file (file-truename file))
17008 (afile (abbreviate-file-name file))
17009 (files (delq nil (mapcar
17010 (lambda (x)
17011 (if (equal true-file
17012 (file-truename x))
17013 nil x))
17014 (org-agenda-files t)))))
17015 (if (not (= (length files) (length (org-agenda-files t))))
17016 (progn
17017 (org-store-new-agenda-file-list files)
17018 (org-install-agenda-files-menu)
17019 (message "Removed file: %s" afile))
17020 (message "File was not in list: %s (not removed)" afile))))
17022 (defun org-file-menu-entry (file)
17023 (vector file (list 'find-file file) t))
17025 (defun org-check-agenda-file (file)
17026 "Make sure FILE exists. If not, ask user what to do."
17027 (when (not (file-exists-p file))
17028 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17029 (abbreviate-file-name file))
17030 (let ((r (downcase (read-char-exclusive))))
17031 (cond
17032 ((equal r ?r)
17033 (org-remove-file file)
17034 (throw 'nextfile t))
17035 (t (error "Abort"))))))
17037 (defun org-get-agenda-file-buffer (file)
17038 "Get a buffer visiting FILE. If the buffer needs to be created, add
17039 it to the list of buffers which might be released later."
17040 (let ((buf (org-find-base-buffer-visiting file)))
17041 (if buf
17042 buf ; just return it
17043 ;; Make a new buffer and remember it
17044 (setq buf (find-file-noselect file))
17045 (if buf (push buf org-agenda-new-buffers))
17046 buf)))
17048 (defun org-release-buffers (blist)
17049 "Release all buffers in list, asking the user for confirmation when needed.
17050 When a buffer is unmodified, it is just killed. When modified, it is saved
17051 \(if the user agrees) and then killed."
17052 (let (buf file)
17053 (while (setq buf (pop blist))
17054 (setq file (buffer-file-name buf))
17055 (when (and (buffer-modified-p buf)
17056 file
17057 (y-or-n-p (format "Save file %s? " file)))
17058 (with-current-buffer buf (save-buffer)))
17059 (kill-buffer buf))))
17061 (defun org-agenda-prepare-buffers (files)
17062 "Create buffers for all agenda files, protect archived trees and comments."
17063 (interactive)
17064 (let ((pa '(:org-archived t))
17065 (pc '(:org-comment t))
17066 (pall '(:org-archived t :org-comment t))
17067 (inhibit-read-only t)
17068 (rea (concat ":" org-archive-tag ":"))
17069 bmp file re)
17070 (save-excursion
17071 (save-restriction
17072 (while (setq file (pop files))
17073 (catch 'nextfile
17074 (if (bufferp file)
17075 (set-buffer file)
17076 (org-check-agenda-file file)
17077 (set-buffer (org-get-agenda-file-buffer file)))
17078 (widen)
17079 (setq bmp (buffer-modified-p))
17080 (org-refresh-category-properties)
17081 (setq org-todo-keywords-for-agenda
17082 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17083 (setq org-done-keywords-for-agenda
17084 (append org-done-keywords-for-agenda org-done-keywords))
17085 (setq org-todo-keyword-alist-for-agenda
17086 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17087 (setq org-drawers-for-agenda
17088 (append org-drawers-for-agenda org-drawers))
17089 (setq org-tag-alist-for-agenda
17090 (append org-tag-alist-for-agenda org-tag-alist))
17092 (save-excursion
17093 (remove-text-properties (point-min) (point-max) pall)
17094 (when org-agenda-skip-archived-trees
17095 (goto-char (point-min))
17096 (while (re-search-forward rea nil t)
17097 (if (org-at-heading-p t)
17098 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17099 (goto-char (point-min))
17100 (setq re (format org-heading-keyword-regexp-format
17101 org-comment-string))
17102 (while (re-search-forward re nil t)
17103 (add-text-properties
17104 (match-beginning 0) (org-end-of-subtree t) pc)))
17105 (set-buffer-modified-p bmp)))))
17106 (setq org-todo-keywords-for-agenda
17107 (org-uniquify org-todo-keywords-for-agenda))
17108 (setq org-todo-keyword-alist-for-agenda
17109 (org-uniquify org-todo-keyword-alist-for-agenda)
17110 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17112 ;;;; Embedded LaTeX
17114 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17115 "Keymap for the minor `org-cdlatex-mode'.")
17117 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17118 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17119 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17120 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17121 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17123 (defvar org-cdlatex-texmathp-advice-is-done nil
17124 "Flag remembering if we have applied the advice to texmathp already.")
17126 (define-minor-mode org-cdlatex-mode
17127 "Toggle the minor `org-cdlatex-mode'.
17128 This mode supports entering LaTeX environment and math in LaTeX fragments
17129 in Org-mode.
17130 \\{org-cdlatex-mode-map}"
17131 nil " OCDL" nil
17132 (when org-cdlatex-mode
17133 (require 'cdlatex)
17134 (run-hooks 'cdlatex-mode-hook)
17135 (cdlatex-compute-tables))
17136 (unless org-cdlatex-texmathp-advice-is-done
17137 (setq org-cdlatex-texmathp-advice-is-done t)
17138 (defadvice texmathp (around org-math-always-on activate)
17139 "Always return t in org-mode buffers.
17140 This is because we want to insert math symbols without dollars even outside
17141 the LaTeX math segments. If Orgmode thinks that point is actually inside
17142 an embedded LaTeX fragment, let texmathp do its job.
17143 \\[org-cdlatex-mode-map]"
17144 (interactive)
17145 (let (p)
17146 (cond
17147 ((not (derived-mode-p 'org-mode)) ad-do-it)
17148 ((eq this-command 'cdlatex-math-symbol)
17149 (setq ad-return-value t
17150 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17152 (let ((p (org-inside-LaTeX-fragment-p)))
17153 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17154 (setq ad-return-value t
17155 texmathp-why '("Org-mode embedded math" . 0))
17156 (if p ad-do-it)))))))))
17158 (defun turn-on-org-cdlatex ()
17159 "Unconditionally turn on `org-cdlatex-mode'."
17160 (org-cdlatex-mode 1))
17162 (defun org-inside-LaTeX-fragment-p ()
17163 "Test if point is inside a LaTeX fragment.
17164 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17165 sequence appearing also before point.
17166 Even though the matchers for math are configurable, this function assumes
17167 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17168 delimiters are skipped when they have been removed by customization.
17169 The return value is nil, or a cons cell with the delimiter and the
17170 position of this delimiter.
17172 This function does a reasonably good job, but can locally be fooled by
17173 for example currency specifications. For example it will assume being in
17174 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17175 fragments that are properly closed, but during editing, we have to live
17176 with the uncertainty caused by missing closing delimiters. This function
17177 looks only before point, not after."
17178 (catch 'exit
17179 (let ((pos (point))
17180 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17181 (lim (progn
17182 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17183 (point)))
17184 dd-on str (start 0) m re)
17185 (goto-char pos)
17186 (when dodollar
17187 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17188 re (nth 1 (assoc "$" org-latex-regexps)))
17189 (while (string-match re str start)
17190 (cond
17191 ((= (match-end 0) (length str))
17192 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17193 ((= (match-end 0) (- (length str) 5))
17194 (throw 'exit nil))
17195 (t (setq start (match-end 0))))))
17196 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17197 (goto-char pos)
17198 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17199 (and (match-beginning 2) (throw 'exit nil))
17200 ;; count $$
17201 (while (re-search-backward "\\$\\$" lim t)
17202 (setq dd-on (not dd-on)))
17203 (goto-char pos)
17204 (if dd-on (cons "$$" m))))))
17206 (defun org-inside-latex-macro-p ()
17207 "Is point inside a LaTeX macro or its arguments?"
17208 (save-match-data
17209 (org-in-regexp
17210 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17212 (defun org-try-cdlatex-tab ()
17213 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17214 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17215 - inside a LaTeX fragment, or
17216 - after the first word in a line, where an abbreviation expansion could
17217 insert a LaTeX environment."
17218 (when org-cdlatex-mode
17219 (cond
17220 ;; Before any word on the line: No expansion possible.
17221 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17222 ;; Just after first word on the line: Expand it. Make sure it
17223 ;; cannot happen on headlines, though.
17224 ((save-excursion
17225 (skip-chars-backward "a-zA-Z0-9*")
17226 (skip-chars-backward " \t")
17227 (and (bolp) (not (org-at-heading-p))))
17228 (cdlatex-tab) t)
17229 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17231 (defun org-cdlatex-underscore-caret (&optional arg)
17232 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17233 Revert to the normal definition outside of these fragments."
17234 (interactive "P")
17235 (if (org-inside-LaTeX-fragment-p)
17236 (call-interactively 'cdlatex-sub-superscript)
17237 (let (org-cdlatex-mode)
17238 (call-interactively (key-binding (vector last-input-event))))))
17240 (defun org-cdlatex-math-modify (&optional arg)
17241 "Execute `cdlatex-math-modify' in LaTeX fragments.
17242 Revert to the normal definition outside of these fragments."
17243 (interactive "P")
17244 (if (org-inside-LaTeX-fragment-p)
17245 (call-interactively 'cdlatex-math-modify)
17246 (let (org-cdlatex-mode)
17247 (call-interactively (key-binding (vector last-input-event))))))
17249 (defvar org-latex-fragment-image-overlays nil
17250 "List of overlays carrying the images of latex fragments.")
17251 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17253 (defun org-remove-latex-fragment-image-overlays ()
17254 "Remove all overlays with LaTeX fragment images in current buffer."
17255 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17256 (setq org-latex-fragment-image-overlays nil))
17258 (defun org-preview-latex-fragment (&optional subtree)
17259 "Preview the LaTeX fragment at point, or all locally or globally.
17260 If the cursor is in a LaTeX fragment, create the image and overlay
17261 it over the source code. If there is no fragment at point, display
17262 all fragments in the current text, from one headline to the next. With
17263 prefix SUBTREE, display all fragments in the current subtree. With a
17264 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17265 the cursor is before the first headline,
17266 display all fragments in the buffer.
17267 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17268 (interactive "P")
17269 (unless buffer-file-name
17270 (error "Can't preview LaTeX fragment in a non-file buffer"))
17271 (org-remove-latex-fragment-image-overlays)
17272 (save-excursion
17273 (save-restriction
17274 (let (beg end at msg)
17275 (cond
17276 ((or (equal subtree '(16))
17277 (not (save-excursion
17278 (re-search-backward org-outline-regexp-bol nil t))))
17279 (setq beg (point-min) end (point-max)
17280 msg "Creating images for buffer...%s"))
17281 ((equal subtree '(4))
17282 (org-back-to-heading)
17283 (setq beg (point) end (org-end-of-subtree t)
17284 msg "Creating images for subtree...%s"))
17286 (if (setq at (org-inside-LaTeX-fragment-p))
17287 (goto-char (max (point-min) (- (cdr at) 2)))
17288 (org-back-to-heading))
17289 (setq beg (point) end (progn (outline-next-heading) (point))
17290 msg (if at "Creating image...%s"
17291 "Creating images for entry...%s"))))
17292 (message msg "")
17293 (narrow-to-region beg end)
17294 (goto-char beg)
17295 (org-format-latex
17296 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17297 (file-name-nondirectory
17298 buffer-file-name)))
17299 default-directory 'overlays msg at 'forbuffer
17300 org-latex-create-formula-image-program)
17301 (message msg "done. Use `C-c C-c' to remove images.")))))
17303 (defvar org-latex-regexps
17304 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17305 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17306 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17307 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17308 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17309 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17310 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17311 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17312 "Regular expressions for matching embedded LaTeX.")
17314 (defvar org-export-have-math nil) ;; dynamic scoping
17315 (defun org-format-latex (prefix &optional dir overlays msg at
17316 forbuffer processing-type)
17317 "Replace LaTeX fragments with links to an image, and produce images.
17318 Some of the options can be changed using the variable
17319 `org-format-latex-options'."
17320 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17321 (let* ((prefixnodir (file-name-nondirectory prefix))
17322 (absprefix (expand-file-name prefix dir))
17323 (todir (file-name-directory absprefix))
17324 (opt org-format-latex-options)
17325 (matchers (plist-get opt :matchers))
17326 (re-list org-latex-regexps)
17327 (org-format-latex-header-extra
17328 (plist-get (org-infile-export-plist) :latex-header-extra))
17329 (cnt 0) txt hash link beg end re e checkdir
17330 executables-checked string
17331 m n block-type block linkfile movefile ov)
17332 ;; Check the different regular expressions
17333 (while (setq e (pop re-list))
17334 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17335 block (if block-type "\n\n" ""))
17336 (when (member m matchers)
17337 (goto-char (point-min))
17338 (while (re-search-forward re nil t)
17339 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17340 (not (get-text-property (match-beginning n)
17341 'org-protected))
17342 (or (not overlays)
17343 (not (eq (get-char-property (match-beginning n)
17344 'org-overlay-type)
17345 'org-latex-overlay))))
17346 (setq org-export-have-math t)
17347 (cond
17348 ((eq processing-type 'verbatim)
17349 ;; Leave the text verbatim, just protect it
17350 (add-text-properties (match-beginning n) (match-end n)
17351 '(org-protected t)))
17352 ((eq processing-type 'mathjax)
17353 ;; Prepare for MathJax processing
17354 (setq string (match-string n))
17355 (if (member m '("$" "$1"))
17356 (save-excursion
17357 (delete-region (match-beginning n) (match-end n))
17358 (goto-char (match-beginning n))
17359 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17360 "\\)")
17361 '(org-protected t))))
17362 (add-text-properties (match-beginning n) (match-end n)
17363 '(org-protected t))))
17364 ((or (eq processing-type 'dvipng)
17365 (eq processing-type 'imagemagick))
17366 ;; Process to an image
17367 (setq txt (match-string n)
17368 beg (match-beginning n) end (match-end n)
17369 cnt (1+ cnt))
17370 (let (print-length print-level) ; make sure full list is printed
17371 (setq hash (sha1 (prin1-to-string
17372 (list org-format-latex-header
17373 org-format-latex-header-extra
17374 org-export-latex-default-packages-alist
17375 org-export-latex-packages-alist
17376 org-format-latex-options
17377 forbuffer txt)))
17378 linkfile (format "%s_%s.png" prefix hash)
17379 movefile (format "%s_%s.png" absprefix hash)))
17380 (setq link (concat block "[[file:" linkfile "]]" block))
17381 (if msg (message msg cnt))
17382 (goto-char beg)
17383 (unless checkdir ; make sure the directory exists
17384 (setq checkdir t)
17385 (or (file-directory-p todir) (make-directory todir t)))
17386 (cond
17387 ((eq processing-type 'dvipng)
17388 (unless executables-checked
17389 (org-check-external-command
17390 "latex" "needed to convert LaTeX fragments to images")
17391 (org-check-external-command
17392 "dvipng" "needed to convert LaTeX fragments to images")
17393 (setq executables-checked t))
17394 (unless (file-exists-p movefile)
17395 (org-create-formula-image-with-dvipng
17396 txt movefile opt forbuffer)))
17397 ((eq processing-type 'imagemagick)
17398 (unless executables-checked
17399 (org-check-external-command
17400 "convert" "you need to install imagemagick")
17401 (setq executables-checked t))
17402 (unless (file-exists-p movefile)
17403 (org-create-formula-image-with-imagemagick
17404 txt movefile opt forbuffer))))
17405 (if overlays
17406 (progn
17407 (mapc (lambda (o)
17408 (if (eq (overlay-get o 'org-overlay-type)
17409 'org-latex-overlay)
17410 (delete-overlay o)))
17411 (overlays-in beg end))
17412 (setq ov (make-overlay beg end))
17413 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17414 (if (featurep 'xemacs)
17415 (progn
17416 (overlay-put ov 'invisible t)
17417 (overlay-put
17418 ov 'end-glyph
17419 (make-glyph (vector 'png :file movefile))))
17420 (overlay-put
17421 ov 'display
17422 (list 'image :type 'png :file movefile :ascent 'center)))
17423 (push ov org-latex-fragment-image-overlays)
17424 (goto-char end))
17425 (delete-region beg end)
17426 (insert (org-add-props link
17427 (list 'org-latex-src
17428 (replace-regexp-in-string
17429 "\"" "" txt)
17430 'org-latex-src-embed-type
17431 (if block-type 'paragraph 'character))))))
17432 ((eq processing-type 'mathml)
17433 ;; Process to MathML
17434 (unless executables-checked
17435 (unless (save-match-data (org-format-latex-mathml-available-p))
17436 (error "LaTeX to MathML converter not configured"))
17437 (setq executables-checked t))
17438 (setq txt (match-string n)
17439 beg (match-beginning n) end (match-end n)
17440 cnt (1+ cnt))
17441 (if msg (message msg cnt))
17442 (goto-char beg)
17443 (delete-region beg end)
17444 (insert (org-format-latex-as-mathml
17445 txt block-type prefix dir)))
17447 (error "Unknown conversion type %s for latex fragments"
17448 processing-type)))))))))
17450 (defun org-create-math-formula (latex-frag &optional mathml-file)
17451 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17452 Use `org-latex-to-mathml-convert-command'. If the conversion is
17453 sucessful, return the portion between \"<math...> </math>\"
17454 elements otherwise return nil. When MATHML-FILE is specified,
17455 write the results in to that file. When invoked as an
17456 interactive command, prompt for LATEX-FRAG, with initial value
17457 set to the current active region and echo the results for user
17458 inspection."
17459 (interactive (list (let ((frag (when (org-region-active-p)
17460 (buffer-substring-no-properties
17461 (region-beginning) (region-end)))))
17462 (read-string "LaTeX Fragment: " frag nil frag))))
17463 (unless latex-frag (error "Invalid latex-frag"))
17464 (let* ((tmp-in-file (file-relative-name
17465 (make-temp-name (expand-file-name "ltxmathml-in"))))
17466 (ignore (write-region latex-frag nil tmp-in-file))
17467 (tmp-out-file (file-relative-name
17468 (make-temp-name (expand-file-name "ltxmathml-out"))))
17469 (cmd (format-spec
17470 org-latex-to-mathml-convert-command
17471 `((?j . ,(shell-quote-argument
17472 (expand-file-name org-latex-to-mathml-jar-file)))
17473 (?I . ,(shell-quote-argument tmp-in-file))
17474 (?o . ,(shell-quote-argument tmp-out-file)))))
17475 mathml shell-command-output)
17476 (when (org-called-interactively-p 'any)
17477 (unless (org-format-latex-mathml-available-p)
17478 (error "LaTeX to MathML converter not configured")))
17479 (message "Running %s" cmd)
17480 (setq shell-command-output (shell-command-to-string cmd))
17481 (setq mathml
17482 (when (file-readable-p tmp-out-file)
17483 (with-current-buffer (find-file-noselect tmp-out-file t)
17484 (goto-char (point-min))
17485 (when (re-search-forward
17486 (concat
17487 (regexp-quote
17488 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17489 "\\(.\\|\n\\)*"
17490 (regexp-quote "</math>")) nil t)
17491 (prog1 (match-string 0) (kill-buffer))))))
17492 (cond
17493 (mathml
17494 (setq mathml
17495 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17496 (when mathml-file
17497 (write-region mathml nil mathml-file))
17498 (when (org-called-interactively-p 'any)
17499 (message mathml)))
17500 ((message "LaTeX to MathML conversion failed")
17501 (message shell-command-output)))
17502 (delete-file tmp-in-file)
17503 (when (file-exists-p tmp-out-file)
17504 (delete-file tmp-out-file))
17505 mathml))
17507 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17508 prefix &optional dir)
17509 "Use `org-create-math-formula' but check local cache first."
17510 (let* ((absprefix (expand-file-name prefix dir))
17511 (print-length nil) (print-level nil)
17512 (formula-id (concat
17513 "formula-"
17514 (sha1
17515 (prin1-to-string
17516 (list latex-frag
17517 org-latex-to-mathml-convert-command)))))
17518 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17519 (formula-cache-dir (file-name-directory formula-cache)))
17521 (unless (file-directory-p formula-cache-dir)
17522 (make-directory formula-cache-dir t))
17524 (unless (file-exists-p formula-cache)
17525 (org-create-math-formula latex-frag formula-cache))
17527 (if (file-exists-p formula-cache)
17528 ;; Successful conversion. Return the link to MathML file.
17529 (org-add-props
17530 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17531 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17532 'org-latex-src-embed-type (if latex-frag-type
17533 'paragraph 'character)))
17534 ;; Failed conversion. Return the LaTeX fragment verbatim
17535 (add-text-properties
17536 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17537 latex-frag)))
17539 ;; This function borrows from Ganesh Swami's latex2png.el
17540 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17541 "This calls dvipng."
17542 (require 'org-latex)
17543 (let* ((tmpdir (if (featurep 'xemacs)
17544 (temp-directory)
17545 temporary-file-directory))
17546 (texfilebase (make-temp-name
17547 (expand-file-name "orgtex" tmpdir)))
17548 (texfile (concat texfilebase ".tex"))
17549 (dvifile (concat texfilebase ".dvi"))
17550 (pngfile (concat texfilebase ".png"))
17551 (fnh (if (featurep 'xemacs)
17552 (font-height (face-font 'default))
17553 (face-attribute 'default :height nil)))
17554 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17555 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17556 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17557 "Black"))
17558 (bg (or (plist-get options (if buffer :background :html-background))
17559 "Transparent")))
17560 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17561 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17562 (with-temp-file texfile
17563 (insert (org-splice-latex-header
17564 org-format-latex-header
17565 org-export-latex-default-packages-alist
17566 org-export-latex-packages-alist t
17567 org-format-latex-header-extra))
17568 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17569 (require 'org-latex)
17570 (org-export-latex-fix-inputenc))
17571 (let ((dir default-directory))
17572 (condition-case nil
17573 (progn
17574 (cd tmpdir)
17575 (call-process "latex" nil nil nil texfile))
17576 (error nil))
17577 (cd dir))
17578 (if (not (file-exists-p dvifile))
17579 (progn (message "Failed to create dvi file from %s" texfile) nil)
17580 (condition-case nil
17581 (if (featurep 'xemacs)
17582 (call-process "dvipng" nil nil nil
17583 "-fg" fg "-bg" bg
17584 "-T" "tight"
17585 "-o" pngfile
17586 dvifile)
17587 (call-process "dvipng" nil nil nil
17588 "-fg" fg "-bg" bg
17589 "-D" dpi
17590 ;;"-x" scale "-y" scale
17591 "-T" "tight"
17592 "-o" pngfile
17593 dvifile))
17594 (error nil))
17595 (if (not (file-exists-p pngfile))
17596 (if org-format-latex-signal-error
17597 (error "Failed to create png file from %s" texfile)
17598 (message "Failed to create png file from %s" texfile)
17599 nil)
17600 ;; Use the requested file name and clean up
17601 (copy-file pngfile tofile 'replace)
17602 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17603 (if (file-exists-p (concat texfilebase e))
17604 (delete-file (concat texfilebase e))))
17605 pngfile))))
17607 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17608 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17609 "This calls convert, which is included into imagemagick."
17610 (require 'org-latex)
17611 (let* ((tmpdir (if (featurep 'xemacs)
17612 (temp-directory)
17613 temporary-file-directory))
17614 (texfilebase (make-temp-name
17615 (expand-file-name "orgtex" tmpdir)))
17616 (texfile (concat texfilebase ".tex"))
17617 (pdffile (concat texfilebase ".pdf"))
17618 (pngfile (concat texfilebase ".png"))
17619 (fnh (if (featurep 'xemacs)
17620 (font-height (face-font 'default))
17621 (face-attribute 'default :height nil)))
17622 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17623 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17624 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17625 "black"))
17626 (bg (or (plist-get options (if buffer :background :html-background))
17627 "white")))
17628 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17629 (setq fg (org-latex-color-format fg)))
17630 (if (eq bg 'default) (setq bg (org-latex-color :background))
17631 (setq bg (org-latex-color-format
17632 (if (string= bg "Transparent")(setq bg "white")))))
17633 (with-temp-file texfile
17634 (insert (org-splice-latex-header
17635 org-format-latex-header
17636 org-export-latex-default-packages-alist
17637 org-export-latex-packages-alist t
17638 org-format-latex-header-extra))
17639 (insert "\n\\begin{document}\n"
17640 "\\definecolor{fg}{rgb}{" fg "}\n"
17641 "\\definecolor{bg}{rgb}{" bg "}\n"
17642 "\n\\pagecolor{bg}\n"
17643 "\n{\\color{fg}\n"
17644 string
17645 "\n}\n"
17646 "\n\\end{document}\n" )
17647 (require 'org-latex)
17648 (org-export-latex-fix-inputenc))
17649 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17650 (condition-case nil
17651 (progn
17652 (cd tmpdir)
17653 (setq cmds org-latex-to-pdf-process)
17654 (while cmds
17655 (setq latex-frags-cmds (pop cmds))
17656 (if (listp latex-frags-cmds)
17657 (setq cmds nil)
17658 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17659 (while latex-frags-cmds
17660 (setq cmd (pop latex-frags-cmds))
17661 (while (string-match "%b" cmd)
17662 (setq cmd (replace-match
17663 (save-match-data
17664 (shell-quote-argument texfile))
17665 t t cmd)))
17666 (while (string-match "%f" cmd)
17667 (setq cmd (replace-match
17668 (save-match-data
17669 (shell-quote-argument (file-name-nondirectory texfile)))
17670 t t cmd)))
17671 (while (string-match "%o" cmd)
17672 (setq cmd (replace-match
17673 (save-match-data
17674 (shell-quote-argument (file-name-directory texfile)))
17675 t t cmd)))
17676 (setq cmd (split-string cmd))
17677 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17678 (error nil))
17679 (cd dir))
17680 (if (not (file-exists-p pdffile))
17681 (progn (message "Failed to create pdf file from %s" texfile) nil)
17682 (condition-case nil
17683 (if (featurep 'xemacs)
17684 (call-process "convert" nil nil nil
17685 "-density" "96"
17686 "-trim"
17687 "-antialias"
17688 pdffile
17689 "-quality" "100"
17690 ;; "-sharpen" "0x1.0"
17691 pngfile)
17692 (call-process "convert" nil nil nil
17693 "-density" dpi
17694 "-trim"
17695 "-antialias"
17696 pdffile
17697 "-quality" "100"
17698 ; "-sharpen" "0x1.0"
17699 pngfile))
17700 (error nil))
17701 (if (not (file-exists-p pngfile))
17702 (if org-format-latex-signal-error
17703 (error "Failed to create png file from %s" texfile)
17704 (message "Failed to create png file from %s" texfile)
17705 nil)
17706 ;; Use the requested file name and clean up
17707 (copy-file pngfile tofile 'replace)
17708 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17709 (if (file-exists-p (concat texfilebase e))
17710 (delete-file (concat texfilebase e))))
17711 pngfile))))
17713 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17714 "Fill a LaTeX header template TPL.
17715 In the template, the following place holders will be recognized:
17717 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17718 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17719 [PACKAGES] \\usepackage statements for PKG
17720 [NO-PACKAGES] do not include PKG
17721 [EXTRA] the string EXTRA
17722 [NO-EXTRA] do not include EXTRA
17724 For backward compatibility, if both the positive and the negative place
17725 holder is missing, the positive one (without the \"NO-\") will be
17726 assumed to be present at the end of the template.
17727 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17728 EXTRA is a string.
17729 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17730 (let (rpl (end ""))
17731 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17732 (setq rpl (if (or (match-end 1) (not def-pkg))
17733 "" (org-latex-packages-to-string def-pkg snippets-p t))
17734 tpl (replace-match rpl t t tpl))
17735 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17737 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17738 (setq rpl (if (or (match-end 1) (not pkg))
17739 "" (org-latex-packages-to-string pkg snippets-p t))
17740 tpl (replace-match rpl t t tpl))
17741 (if pkg (setq end
17742 (concat end "\n"
17743 (org-latex-packages-to-string pkg snippets-p)))))
17745 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17746 (setq rpl (if (or (match-end 1) (not extra))
17747 "" (concat extra "\n"))
17748 tpl (replace-match rpl t t tpl))
17749 (if (and extra (string-match "\\S-" extra))
17750 (setq end (concat end "\n" extra))))
17752 (if (string-match "\\S-" end)
17753 (concat tpl "\n" end)
17754 tpl)))
17756 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17757 "Turn an alist of packages into a string with the \\usepackage macros."
17758 (setq pkg (mapconcat (lambda(p)
17759 (cond
17760 ((stringp p) p)
17761 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17762 (format "%% Package %s omitted" (cadr p)))
17763 ((equal "" (car p))
17764 (format "\\usepackage{%s}" (cadr p)))
17766 (format "\\usepackage[%s]{%s}"
17767 (car p) (cadr p)))))
17769 "\n"))
17770 (if newline (concat pkg "\n") pkg))
17772 (defun org-dvipng-color (attr)
17773 "Return a RGB color specification for dvipng."
17774 (apply 'format "rgb %s %s %s"
17775 (mapcar 'org-normalize-color
17776 (if (featurep 'xemacs)
17777 (color-rgb-components
17778 (face-property 'default
17779 (cond ((eq attr :foreground) 'foreground)
17780 ((eq attr :background) 'background))))
17781 (color-values (face-attribute 'default attr nil))))))
17783 (defun org-latex-color (attr)
17784 "Return a RGB color for the LaTeX color package."
17785 (apply 'format "%s,%s,%s"
17786 (mapcar 'org-normalize-color
17787 (if (featurep 'xemacs)
17788 (color-rgb-components
17789 (face-property 'default
17790 (cond ((eq attr :foreground) 'foreground)
17791 ((eq attr :background) 'background))))
17792 (color-values (face-attribute 'default attr nil))))))
17794 (defun org-latex-color-format (color-name)
17795 "Convert COLOR-NAME to a RGB color value."
17796 (apply 'format "%s,%s,%s"
17797 (mapcar 'org-normalize-color
17798 (color-values color-name))))
17800 (defun org-normalize-color (value)
17801 "Return string to be used as color value for an RGB component."
17802 (format "%g" (/ value 65535.0)))
17804 ;; Image display
17807 (defvar org-inline-image-overlays nil)
17808 (make-variable-buffer-local 'org-inline-image-overlays)
17810 (defun org-toggle-inline-images (&optional include-linked)
17811 "Toggle the display of inline images.
17812 INCLUDE-LINKED is passed to `org-display-inline-images'."
17813 (interactive "P")
17814 (if org-inline-image-overlays
17815 (progn
17816 (org-remove-inline-images)
17817 (message "Inline image display turned off"))
17818 (org-display-inline-images include-linked)
17819 (if org-inline-image-overlays
17820 (message "%d images displayed inline"
17821 (length org-inline-image-overlays))
17822 (message "No images to display inline"))))
17824 (defun org-redisplay-inline-images ()
17825 "Refresh the display of inline images."
17826 (interactive)
17827 (if (not org-inline-image-overlays)
17828 (org-toggle-inline-images)
17829 (org-toggle-inline-images)
17830 (org-toggle-inline-images)))
17832 (defun org-display-inline-images (&optional include-linked refresh beg end)
17833 "Display inline images.
17834 Normally only links without a description part are inlined, because this
17835 is how it will work for export. When INCLUDE-LINKED is set, also links
17836 with a description part will be inlined. This can be nice for a quick
17837 look at those images, but it does not reflect what exported files will look
17838 like.
17839 When REFRESH is set, refresh existing images between BEG and END.
17840 This will create new image displays only if necessary.
17841 BEG and END default to the buffer boundaries."
17842 (interactive "P")
17843 (unless refresh
17844 (org-remove-inline-images)
17845 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17846 (save-excursion
17847 (save-restriction
17848 (widen)
17849 (setq beg (or beg (point-min)) end (or end (point-max)))
17850 (goto-char beg)
17851 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17852 (substring (org-image-file-name-regexp) 0 -2)
17853 "\\)\\]" (if include-linked "" "\\]")))
17854 old file ov img)
17855 (while (re-search-forward re end t)
17856 (setq old (get-char-property-and-overlay (match-beginning 1)
17857 'org-image-overlay))
17858 (setq file (expand-file-name
17859 (concat (or (match-string 3) "") (match-string 4))))
17860 (when (file-exists-p file)
17861 (if (and (car-safe old) refresh)
17862 (image-refresh (overlay-get (cdr old) 'display))
17863 (setq img (save-match-data (create-image file)))
17864 (when img
17865 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17866 (overlay-put ov 'display img)
17867 (overlay-put ov 'face 'default)
17868 (overlay-put ov 'org-image-overlay t)
17869 (overlay-put ov 'modification-hooks
17870 (list 'org-display-inline-modification-hook))
17871 (push ov org-inline-image-overlays)))))))))
17873 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17874 "Remove inline-display overlay if a corresponding region is modified."
17875 (let ((inhibit-modification-hooks t))
17876 (when (and ov after)
17877 (delete ov org-inline-image-overlays)
17878 (delete-overlay ov))))
17880 (defun org-remove-inline-images ()
17881 "Remove inline display of images."
17882 (interactive)
17883 (mapc 'delete-overlay org-inline-image-overlays)
17884 (setq org-inline-image-overlays nil))
17886 ;;;; Key bindings
17888 ;; Outline functions from `outline-mode-prefix-map'
17889 ;; that can be remapped in Org:
17890 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17891 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17892 (define-key org-mode-map [remap outline-forward-same-level]
17893 'org-forward-heading-same-level)
17894 (define-key org-mode-map [remap outline-backward-same-level]
17895 'org-backward-heading-same-level)
17896 (define-key org-mode-map [remap show-branches]
17897 'org-kill-note-or-show-branches)
17898 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17899 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17900 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17902 ;; Outline functions from `outline-mode-prefix-map' that can not
17903 ;; be remapped in Org:
17905 ;; - the column "key binding" shows whether the Outline function is still
17906 ;; available in Org mode on the same key that it has been bound to in
17907 ;; Outline mode:
17908 ;; - "overridden": key used for a different functionality in Org mode
17909 ;; - else: key still bound to the same Outline function in Org mode
17911 ;; | Outline function | key binding | Org replacement |
17912 ;; |------------------------------------+-------------+-----------------------|
17913 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17914 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17915 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17916 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17917 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17918 ;; | `show-entry' | overridden | no replacement |
17919 ;; | `show-children' | `C-c C-i' | visibility cycling |
17920 ;; | `show-branches' | `C-c C-k' | still same function |
17921 ;; | `show-subtree' | overridden | visibility cycling |
17922 ;; | `show-all' | overridden | no replacement |
17923 ;; | `hide-subtree' | overridden | visibility cycling |
17924 ;; | `hide-body' | overridden | no replacement |
17925 ;; | `hide-entry' | overridden | visibility cycling |
17926 ;; | `hide-leaves' | overridden | no replacement |
17927 ;; | `hide-sublevels' | overridden | no replacement |
17928 ;; | `hide-other' | overridden | no replacement |
17930 ;; Make `C-c C-x' a prefix key
17931 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17933 ;; TAB key with modifiers
17934 (org-defkey org-mode-map "\C-i" 'org-cycle)
17935 (org-defkey org-mode-map [(tab)] 'org-cycle)
17936 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17937 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17938 ;; The following line is necessary under Suse GNU/Linux
17939 (unless (featurep 'xemacs)
17940 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17941 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17942 (define-key org-mode-map [backtab] 'org-shifttab)
17944 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17945 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17946 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17948 ;; Cursor keys with modifiers
17949 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17950 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17951 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17952 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17954 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17955 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17956 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17957 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17959 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17960 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17961 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17962 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17964 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17965 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17966 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17967 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17969 ;; Babel keys
17970 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17971 (mapc (lambda (pair)
17972 (define-key org-babel-map (car pair) (cdr pair)))
17973 org-babel-key-bindings)
17975 ;;; Extra keys for tty access.
17976 ;; We only set them when really needed because otherwise the
17977 ;; menus don't show the simple keys
17979 (when (or org-use-extra-keys
17980 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17981 (not window-system))
17982 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17983 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17984 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17985 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17986 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17987 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17988 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17989 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17990 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17991 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17992 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17993 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17994 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17995 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17996 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17997 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17998 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17999 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18000 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18001 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18002 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18003 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18004 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18005 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18006 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18007 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18008 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18009 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18011 ;; All the other keys
18013 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18014 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18015 (if (boundp 'narrow-map)
18016 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18017 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18018 (if (boundp 'narrow-map)
18019 (org-defkey narrow-map "b" 'org-narrow-to-block)
18020 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18021 (if (boundp 'narrow-map)
18022 (org-defkey narrow-map "e" 'org-narrow-to-element)
18023 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18024 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18025 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18026 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18027 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18028 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18029 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18030 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18031 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18032 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18033 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18034 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18035 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18036 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18037 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18038 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18039 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18040 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18041 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18042 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18043 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18044 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18045 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18046 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18047 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18048 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18049 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18050 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18051 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18052 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18053 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18054 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18055 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18056 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18057 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18058 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18059 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18060 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18061 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18062 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18063 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18064 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18065 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18066 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18067 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18068 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18069 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18070 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18071 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18072 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18073 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18074 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18075 (org-defkey org-mode-map "\C-c^" 'org-sort)
18076 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18077 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18078 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18079 (org-defkey org-mode-map "\C-m" 'org-return)
18080 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18081 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18082 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18083 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18084 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18085 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18086 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18087 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18088 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18089 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18090 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18091 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18092 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18093 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18094 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18095 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18096 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18097 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18098 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18099 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18100 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18101 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18102 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18104 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18105 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18106 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18107 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18109 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18110 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18111 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18112 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18113 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18114 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18115 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18116 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18117 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18118 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18119 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18120 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18121 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18122 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18123 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18124 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18125 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18126 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18127 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18128 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18129 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18130 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18132 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18133 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18134 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18135 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18136 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18138 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18140 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18142 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18143 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18145 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18148 (when (featurep 'xemacs)
18149 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18152 (defconst org-speed-commands-default
18154 ("Outline Navigation")
18155 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18156 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18157 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18158 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18159 ("u" . (org-speed-move-safe 'outline-up-heading))
18160 ("j" . org-goto)
18161 ("g" . (org-refile t))
18162 ("Outline Visibility")
18163 ("c" . org-cycle)
18164 ("C" . org-shifttab)
18165 (" " . org-display-outline-path)
18166 (":" . org-columns)
18167 ("Outline Structure Editing")
18168 ("U" . org-shiftmetaup)
18169 ("D" . org-shiftmetadown)
18170 ("r" . org-metaright)
18171 ("l" . org-metaleft)
18172 ("R" . org-shiftmetaright)
18173 ("L" . org-shiftmetaleft)
18174 ("i" . (progn (forward-char 1) (call-interactively
18175 'org-insert-heading-respect-content)))
18176 ("^" . org-sort)
18177 ("w" . org-refile)
18178 ("a" . org-archive-subtree-default-with-confirmation)
18179 ("." . org-mark-subtree)
18180 ("#" . org-toggle-comment)
18181 ("Clock Commands")
18182 ("I" . org-clock-in)
18183 ("O" . org-clock-out)
18184 ("Meta Data Editing")
18185 ("t" . org-todo)
18186 ("0" . (org-priority ?\ ))
18187 ("1" . (org-priority ?A))
18188 ("2" . (org-priority ?B))
18189 ("3" . (org-priority ?C))
18190 (";" . org-set-tags-command)
18191 ("e" . org-set-effort)
18192 ("E" . org-inc-effort)
18193 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18194 (org-entry-put (point) "APPT_WARNTIME" m)))
18195 ("Agenda Views etc")
18196 ("v" . org-agenda)
18197 ("/" . org-sparse-tree)
18198 ("Misc")
18199 ("o" . org-open-at-point)
18200 ("?" . org-speed-command-help)
18201 ("<" . (org-agenda-set-restriction-lock 'subtree))
18202 (">" . (org-agenda-remove-restriction-lock))
18204 "The default speed commands.")
18206 (defun org-print-speed-command (e)
18207 (if (> (length (car e)) 1)
18208 (progn
18209 (princ "\n")
18210 (princ (car e))
18211 (princ "\n")
18212 (princ (make-string (length (car e)) ?-))
18213 (princ "\n"))
18214 (princ (car e))
18215 (princ " ")
18216 (if (symbolp (cdr e))
18217 (princ (symbol-name (cdr e)))
18218 (prin1 (cdr e)))
18219 (princ "\n")))
18221 (defun org-speed-command-help ()
18222 "Show the available speed commands."
18223 (interactive)
18224 (if (not org-use-speed-commands)
18225 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18226 (with-output-to-temp-buffer "*Help*"
18227 (princ "User-defined Speed commands\n===========================\n")
18228 (mapc 'org-print-speed-command org-speed-commands-user)
18229 (princ "\n")
18230 (princ "Built-in Speed commands\n=======================\n")
18231 (mapc 'org-print-speed-command org-speed-commands-default))
18232 (with-current-buffer "*Help*"
18233 (setq truncate-lines t))))
18235 (defun org-speed-move-safe (cmd)
18236 "Execute CMD, but make sure that the cursor always ends up in a headline.
18237 If not, return to the original position and throw an error."
18238 (interactive)
18239 (let ((pos (point)))
18240 (call-interactively cmd)
18241 (unless (and (bolp) (org-at-heading-p))
18242 (goto-char pos)
18243 (error "Boundary reached while executing %s" cmd))))
18245 (defvar org-self-insert-command-undo-counter 0)
18247 (defvar org-table-auto-blank-field) ; defined in org-table.el
18248 (defvar org-speed-command nil)
18250 (defun org-speed-command-default-hook (keys)
18251 "Hook for activating single-letter speed commands.
18252 `org-speed-commands-default' specifies a minimal command set.
18253 Use `org-speed-commands-user' for further customization."
18254 (when (or (and (bolp) (looking-at org-outline-regexp))
18255 (and (functionp org-use-speed-commands)
18256 (funcall org-use-speed-commands)))
18257 (cdr (assoc keys (append org-speed-commands-user
18258 org-speed-commands-default)))))
18260 (defun org-babel-speed-command-hook (keys)
18261 "Hook for activating single-letter code block commands."
18262 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18263 (cdr (assoc keys org-babel-key-bindings))))
18265 (defcustom org-speed-command-hook
18266 '(org-speed-command-default-hook org-babel-speed-command-hook)
18267 "Hook for activating speed commands at strategic locations.
18268 Hook functions are called in sequence until a valid handler is
18269 found.
18271 Each hook takes a single argument, a user-pressed command key
18272 which is also a `self-insert-command' from the global map.
18274 Within the hook, examine the cursor position and the command key
18275 and return nil or a valid handler as appropriate. Handler could
18276 be one of an interactive command, a function, or a form.
18278 Set `org-use-speed-commands' to non-nil value to enable this
18279 hook. The default setting is `org-speed-command-default-hook'."
18280 :group 'org-structure
18281 :version "24.1"
18282 :type 'hook)
18284 (defun org-self-insert-command (N)
18285 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18286 If the cursor is in a table looking at whitespace, the whitespace is
18287 overwritten, and the table is not marked as requiring realignment."
18288 (interactive "p")
18289 (org-check-before-invisible-edit 'insert)
18290 (cond
18291 ((and org-use-speed-commands
18292 (setq org-speed-command
18293 (run-hook-with-args-until-success
18294 'org-speed-command-hook (this-command-keys))))
18295 (cond
18296 ((commandp org-speed-command)
18297 (setq this-command org-speed-command)
18298 (call-interactively org-speed-command))
18299 ((functionp org-speed-command)
18300 (funcall org-speed-command))
18301 ((and org-speed-command (listp org-speed-command))
18302 (eval org-speed-command))
18303 (t (let (org-use-speed-commands)
18304 (call-interactively 'org-self-insert-command)))))
18305 ((and
18306 (org-table-p)
18307 (progn
18308 ;; check if we blank the field, and if that triggers align
18309 (and (featurep 'org-table) org-table-auto-blank-field
18310 (member last-command
18311 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18312 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18313 ;; got extra space, this field does not determine column width
18314 (let (org-table-may-need-update) (org-table-blank-field))
18315 ;; no extra space, this field may determine column width
18316 (org-table-blank-field)))
18318 (eq N 1)
18319 (looking-at "[^|\n]* |"))
18320 (let (org-table-may-need-update)
18321 (goto-char (1- (match-end 0)))
18322 (backward-delete-char 1)
18323 (goto-char (match-beginning 0))
18324 (self-insert-command N)))
18326 (setq org-table-may-need-update t)
18327 (self-insert-command N)
18328 (org-fix-tags-on-the-fly)
18329 (if org-self-insert-cluster-for-undo
18330 (if (not (eq last-command 'org-self-insert-command))
18331 (setq org-self-insert-command-undo-counter 1)
18332 (if (>= org-self-insert-command-undo-counter 20)
18333 (setq org-self-insert-command-undo-counter 1)
18334 (and (> org-self-insert-command-undo-counter 0)
18335 buffer-undo-list (listp buffer-undo-list)
18336 (not (cadr buffer-undo-list)) ; remove nil entry
18337 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18338 (setq org-self-insert-command-undo-counter
18339 (1+ org-self-insert-command-undo-counter))))))))
18341 (defun org-check-before-invisible-edit (kind)
18342 "Check is editing if kind KIND would be dangerous with invisible text around.
18343 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18344 ;; First, try to get out of here as quickly as possible, to reduce overhead
18345 (if (and org-catch-invisible-edits
18346 (or (not (boundp 'visible-mode)) (not visible-mode))
18347 (or (get-char-property (point) 'invisible)
18348 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18349 ;; OK, we need to take a closer look
18350 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18351 (invisible-before-point (if (bobp) nil (get-char-property
18352 (1- (point)) 'invisible)))
18353 (border-and-ok-direction
18355 ;; Check if we are acting predictably before invisible text
18356 (and invisible-at-point (not invisible-before-point)
18357 (memq kind '(insert delete-backward)))
18358 ;; Check if we are acting predictably after invisible text
18359 ;; This works not well, and I have turned it off. It seems
18360 ;; better to always show and stop after invisible text.
18361 ;; (and (not invisible-at-point) invisible-before-point
18362 ;; (memq kind '(insert delete)))
18364 (when (or (memq invisible-at-point '(outline org-hide-block t))
18365 (memq invisible-before-point '(outline org-hide-block t)))
18366 (if (eq org-catch-invisible-edits 'error)
18367 (error "Editing in invisible areas is prohibited - make visible first"))
18368 (if (and org-custom-properties-overlays
18369 (y-or-n-p "Display invisible properties in this buffer? "))
18370 (org-toggle-custom-properties-visibility)
18371 ;; Make the area visible
18372 (save-excursion
18373 (if invisible-before-point
18374 (goto-char (previous-single-char-property-change
18375 (point) 'invisible)))
18376 (org-cycle))
18377 (cond
18378 ((eq org-catch-invisible-edits 'show)
18379 ;; That's it, we do the edit after showing
18380 (message
18381 "Unfolding invisible region around point before editing")
18382 (sit-for 1))
18383 ((and (eq org-catch-invisible-edits 'smart)
18384 border-and-ok-direction)
18385 (message "Unfolding invisible region around point before editing"))
18387 ;; Don't do the edit, make the user repeat it in full visibility
18388 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18390 (defun org-fix-tags-on-the-fly ()
18391 (when (and (equal (char-after (point-at-bol)) ?*)
18392 (org-at-heading-p))
18393 (org-align-tags-here org-tags-column)))
18395 (defun org-delete-backward-char (N)
18396 "Like `delete-backward-char', insert whitespace at field end in tables.
18397 When deleting backwards, in tables this function will insert whitespace in
18398 front of the next \"|\" separator, to keep the table aligned. The table will
18399 still be marked for re-alignment if the field did fill the entire column,
18400 because, in this case the deletion might narrow the column."
18401 (interactive "p")
18402 (org-check-before-invisible-edit 'delete-backward)
18403 (if (and (org-table-p)
18404 (eq N 1)
18405 (string-match "|" (buffer-substring (point-at-bol) (point)))
18406 (looking-at ".*?|"))
18407 (let ((pos (point))
18408 (noalign (looking-at "[^|\n\r]* |"))
18409 (c org-table-may-need-update))
18410 (backward-delete-char N)
18411 (if (not overwrite-mode)
18412 (progn
18413 (skip-chars-forward "^|")
18414 (insert " ")
18415 (goto-char (1- pos))))
18416 ;; noalign: if there were two spaces at the end, this field
18417 ;; does not determine the width of the column.
18418 (if noalign (setq org-table-may-need-update c)))
18419 (backward-delete-char N)
18420 (org-fix-tags-on-the-fly)))
18422 (defun org-delete-char (N)
18423 "Like `delete-char', but insert whitespace at field end in tables.
18424 When deleting characters, in tables this function will insert whitespace in
18425 front of the next \"|\" separator, to keep the table aligned. The table will
18426 still be marked for re-alignment if the field did fill the entire column,
18427 because, in this case the deletion might narrow the column."
18428 (interactive "p")
18429 (org-check-before-invisible-edit 'delete)
18430 (if (and (org-table-p)
18431 (not (bolp))
18432 (not (= (char-after) ?|))
18433 (eq N 1))
18434 (if (looking-at ".*?|")
18435 (let ((pos (point))
18436 (noalign (looking-at "[^|\n\r]* |"))
18437 (c org-table-may-need-update))
18438 (replace-match (concat
18439 (substring (match-string 0) 1 -1)
18440 " |"))
18441 (goto-char pos)
18442 ;; noalign: if there were two spaces at the end, this field
18443 ;; does not determine the width of the column.
18444 (if noalign (setq org-table-may-need-update c)))
18445 (delete-char N))
18446 (delete-char N)
18447 (org-fix-tags-on-the-fly)))
18449 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18450 (put 'org-self-insert-command 'delete-selection t)
18451 (put 'orgtbl-self-insert-command 'delete-selection t)
18452 (put 'org-delete-char 'delete-selection 'supersede)
18453 (put 'org-delete-backward-char 'delete-selection 'supersede)
18454 (put 'org-yank 'delete-selection 'yank)
18456 ;; Make `flyspell-mode' delay after some commands
18457 (put 'org-self-insert-command 'flyspell-delayed t)
18458 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18459 (put 'org-delete-char 'flyspell-delayed t)
18460 (put 'org-delete-backward-char 'flyspell-delayed t)
18462 ;; Make pabbrev-mode expand after org-mode commands
18463 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18464 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18466 ;; How to do this: Measure non-white length of current string
18467 ;; If equal to column width, we should realign.
18469 (defun org-remap (map &rest commands)
18470 "In MAP, remap the functions given in COMMANDS.
18471 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18472 (let (new old)
18473 (while commands
18474 (setq old (pop commands) new (pop commands))
18475 (if (fboundp 'command-remapping)
18476 (org-defkey map (vector 'remap old) new)
18477 (substitute-key-definition old new map global-map)))))
18479 (when (eq org-enable-table-editor 'optimized)
18480 ;; If the user wants maximum table support, we need to hijack
18481 ;; some standard editing functions
18482 (org-remap org-mode-map
18483 'self-insert-command 'org-self-insert-command
18484 'delete-char 'org-delete-char
18485 'delete-backward-char 'org-delete-backward-char)
18486 (org-defkey org-mode-map "|" 'org-force-self-insert))
18488 (defvar org-ctrl-c-ctrl-c-hook nil
18489 "Hook for functions attaching themselves to `C-c C-c'.
18491 This can be used to add additional functionality to the C-c C-c
18492 key which executes context-dependent commands. This hook is run
18493 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18494 run after the last test.
18496 Each function will be called with no arguments. The function
18497 must check if the context is appropriate for it to act. If yes,
18498 it should do its thing and then return a non-nil value. If the
18499 context is wrong, just do nothing and return nil.")
18501 (defvar org-ctrl-c-ctrl-c-final-hook nil
18502 "Hook for functions attaching themselves to `C-c C-c'.
18504 This can be used to add additional functionality to the C-c C-c
18505 key which executes context-dependent commands. This hook is run
18506 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18507 before the first test.
18509 Each function will be called with no arguments. The function
18510 must check if the context is appropriate for it to act. If yes,
18511 it should do its thing and then return a non-nil value. If the
18512 context is wrong, just do nothing and return nil.")
18514 (defvar org-tab-first-hook nil
18515 "Hook for functions to attach themselves to TAB.
18516 See `org-ctrl-c-ctrl-c-hook' for more information.
18517 This hook runs as the first action when TAB is pressed, even before
18518 `org-cycle' messes around with the `outline-regexp' to cater for
18519 inline tasks and plain list item folding.
18520 If any function in this hook returns t, any other actions that
18521 would have been caused by TAB (such as table field motion or visibility
18522 cycling) will not occur.")
18524 (defvar org-tab-after-check-for-table-hook nil
18525 "Hook for functions to attach themselves to TAB.
18526 See `org-ctrl-c-ctrl-c-hook' for more information.
18527 This hook runs after it has been established that the cursor is not in a
18528 table, but before checking if the cursor is in a headline or if global cycling
18529 should be done.
18530 If any function in this hook returns t, not other actions like visibility
18531 cycling will be done.")
18533 (defvar org-tab-after-check-for-cycling-hook nil
18534 "Hook for functions to attach themselves to TAB.
18535 See `org-ctrl-c-ctrl-c-hook' for more information.
18536 This hook runs after it has been established that not table field motion and
18537 not visibility should be done because of current context. This is probably
18538 the place where a package like yasnippets can hook in.")
18540 (defvar org-tab-before-tab-emulation-hook nil
18541 "Hook for functions to attach themselves to TAB.
18542 See `org-ctrl-c-ctrl-c-hook' for more information.
18543 This hook runs after every other options for TAB have been exhausted, but
18544 before indentation and \t insertion takes place.")
18546 (defvar org-metaleft-hook nil
18547 "Hook for functions attaching themselves to `M-left'.
18548 See `org-ctrl-c-ctrl-c-hook' for more information.")
18549 (defvar org-metaright-hook nil
18550 "Hook for functions attaching themselves to `M-right'.
18551 See `org-ctrl-c-ctrl-c-hook' for more information.")
18552 (defvar org-metaup-hook nil
18553 "Hook for functions attaching themselves to `M-up'.
18554 See `org-ctrl-c-ctrl-c-hook' for more information.")
18555 (defvar org-metadown-hook nil
18556 "Hook for functions attaching themselves to `M-down'.
18557 See `org-ctrl-c-ctrl-c-hook' for more information.")
18558 (defvar org-shiftmetaleft-hook nil
18559 "Hook for functions attaching themselves to `M-S-left'.
18560 See `org-ctrl-c-ctrl-c-hook' for more information.")
18561 (defvar org-shiftmetaright-hook nil
18562 "Hook for functions attaching themselves to `M-S-right'.
18563 See `org-ctrl-c-ctrl-c-hook' for more information.")
18564 (defvar org-shiftmetaup-hook nil
18565 "Hook for functions attaching themselves to `M-S-up'.
18566 See `org-ctrl-c-ctrl-c-hook' for more information.")
18567 (defvar org-shiftmetadown-hook nil
18568 "Hook for functions attaching themselves to `M-S-down'.
18569 See `org-ctrl-c-ctrl-c-hook' for more information.")
18570 (defvar org-metareturn-hook nil
18571 "Hook for functions attaching themselves to `M-RET'.
18572 See `org-ctrl-c-ctrl-c-hook' for more information.")
18573 (defvar org-shiftup-hook nil
18574 "Hook for functions attaching themselves to `S-up'.
18575 See `org-ctrl-c-ctrl-c-hook' for more information.")
18576 (defvar org-shiftup-final-hook nil
18577 "Hook for functions attaching themselves to `S-up'.
18578 This one runs after all other options except shift-select have been excluded.
18579 See `org-ctrl-c-ctrl-c-hook' for more information.")
18580 (defvar org-shiftdown-hook nil
18581 "Hook for functions attaching themselves to `S-down'.
18582 See `org-ctrl-c-ctrl-c-hook' for more information.")
18583 (defvar org-shiftdown-final-hook nil
18584 "Hook for functions attaching themselves to `S-down'.
18585 This one runs after all other options except shift-select have been excluded.
18586 See `org-ctrl-c-ctrl-c-hook' for more information.")
18587 (defvar org-shiftleft-hook nil
18588 "Hook for functions attaching themselves to `S-left'.
18589 See `org-ctrl-c-ctrl-c-hook' for more information.")
18590 (defvar org-shiftleft-final-hook nil
18591 "Hook for functions attaching themselves to `S-left'.
18592 This one runs after all other options except shift-select have been excluded.
18593 See `org-ctrl-c-ctrl-c-hook' for more information.")
18594 (defvar org-shiftright-hook nil
18595 "Hook for functions attaching themselves to `S-right'.
18596 See `org-ctrl-c-ctrl-c-hook' for more information.")
18597 (defvar org-shiftright-final-hook nil
18598 "Hook for functions attaching themselves to `S-right'.
18599 This one runs after all other options except shift-select have been excluded.
18600 See `org-ctrl-c-ctrl-c-hook' for more information.")
18602 (defun org-modifier-cursor-error ()
18603 "Throw an error, a modified cursor command was applied in wrong context."
18604 (error "This command is active in special context like tables, headlines or items"))
18606 (defun org-shiftselect-error ()
18607 "Throw an error because Shift-Cursor command was applied in wrong context."
18608 (if (and (boundp 'shift-select-mode) shift-select-mode)
18609 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18610 (error "This command works only in special context like headlines or timestamps")))
18612 (defun org-call-for-shift-select (cmd)
18613 (let ((this-command-keys-shift-translated t))
18614 (call-interactively cmd)))
18616 (defun org-shifttab (&optional arg)
18617 "Global visibility cycling or move to previous table field.
18618 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18619 on context.
18620 See the individual commands for more information."
18621 (interactive "P")
18622 (cond
18623 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18624 ((integerp arg)
18625 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18626 (message "Content view to level: %d" arg)
18627 (org-content (prefix-numeric-value arg2))
18628 (setq org-cycle-global-status 'overview)))
18629 (t (call-interactively 'org-global-cycle))))
18631 (defun org-shiftmetaleft ()
18632 "Promote subtree or delete table column.
18633 Calls `org-promote-subtree', `org-outdent-item-tree', or
18634 `org-table-delete-column', depending on context. See the
18635 individual commands for more information."
18636 (interactive)
18637 (cond
18638 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18639 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18640 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18641 ((if (not (org-region-active-p)) (org-at-item-p)
18642 (save-excursion (goto-char (region-beginning))
18643 (org-at-item-p)))
18644 (call-interactively 'org-outdent-item-tree))
18645 (t (org-modifier-cursor-error))))
18647 (defun org-shiftmetaright ()
18648 "Demote subtree or insert table column.
18649 Calls `org-demote-subtree', `org-indent-item-tree', or
18650 `org-table-insert-column', depending on context. See the
18651 individual commands for more information."
18652 (interactive)
18653 (cond
18654 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18655 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18656 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18657 ((if (not (org-region-active-p)) (org-at-item-p)
18658 (save-excursion (goto-char (region-beginning))
18659 (org-at-item-p)))
18660 (call-interactively 'org-indent-item-tree))
18661 (t (org-modifier-cursor-error))))
18663 (defun org-shiftmetaup (&optional arg)
18664 "Move subtree up or kill table row.
18665 Calls `org-move-subtree-up' or `org-table-kill-row' or
18666 `org-move-item-up' or `org-timestamp-up', depending on context.
18667 See the individual commands for more information."
18668 (interactive "P")
18669 (cond
18670 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18671 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18672 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18673 ((org-at-item-p) (call-interactively 'org-move-item-up))
18674 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18675 (call-interactively 'org-timestamp-up)))
18676 (t (org-modifier-cursor-error))))
18678 (defun org-shiftmetadown (&optional arg)
18679 "Move subtree down or insert table row.
18680 Calls `org-move-subtree-down' or `org-table-insert-row' or
18681 `org-move-item-down' or `org-timestamp-up', depending on context.
18682 See the individual commands for more information."
18683 (interactive "P")
18684 (cond
18685 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18686 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18687 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18688 ((org-at-item-p) (call-interactively 'org-move-item-down))
18689 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18690 (call-interactively 'org-timestamp-down)))
18691 (t (org-modifier-cursor-error))))
18693 (defsubst org-hidden-tree-error ()
18694 (error
18695 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18697 (defun org-metaleft (&optional arg)
18698 "Promote heading or move table column to left.
18699 Calls `org-do-promote' or `org-table-move-column', depending on context.
18700 With no specific context, calls the Emacs default `backward-word'.
18701 See the individual commands for more information."
18702 (interactive "P")
18703 (cond
18704 ((run-hook-with-args-until-success 'org-metaleft-hook))
18705 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18706 ((org-with-limited-levels
18707 (or (org-at-heading-p)
18708 (and (org-region-active-p)
18709 (save-excursion
18710 (goto-char (region-beginning))
18711 (org-at-heading-p)))))
18712 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18713 (call-interactively 'org-do-promote))
18714 ;; At an inline task.
18715 ((org-at-heading-p)
18716 (call-interactively 'org-inlinetask-promote))
18717 ((or (org-at-item-p)
18718 (and (org-region-active-p)
18719 (save-excursion
18720 (goto-char (region-beginning))
18721 (org-at-item-p))))
18722 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18723 (call-interactively 'org-outdent-item))
18724 (t (call-interactively 'backward-word))))
18726 (defun org-metaright (&optional arg)
18727 "Demote a subtree, a list item or move table column to right.
18728 In front of a drawer or a block keyword, indent it correctly.
18729 With no specific context, calls the Emacs default `forward-word'.
18730 See the individual commands for more information."
18731 (interactive "P")
18732 (cond
18733 ((run-hook-with-args-until-success 'org-metaright-hook))
18734 ((org-at-table-p) (call-interactively 'org-table-move-column))
18735 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18736 ((org-at-block-p) (call-interactively 'org-indent-block))
18737 ((org-with-limited-levels
18738 (or (org-at-heading-p)
18739 (and (org-region-active-p)
18740 (save-excursion
18741 (goto-char (region-beginning))
18742 (org-at-heading-p)))))
18743 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18744 (call-interactively 'org-do-demote))
18745 ;; At an inline task.
18746 ((org-at-heading-p)
18747 (call-interactively 'org-inlinetask-demote))
18748 ((or (org-at-item-p)
18749 (and (org-region-active-p)
18750 (save-excursion
18751 (goto-char (region-beginning))
18752 (org-at-item-p))))
18753 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18754 (call-interactively 'org-indent-item))
18755 (t (call-interactively 'forward-word))))
18757 (defun org-check-for-hidden (what)
18758 "Check if there are hidden headlines/items in the current visual line.
18759 WHAT can be either `headlines' or `items'. If the current line is
18760 an outline or item heading and it has a folded subtree below it,
18761 this function returns t, nil otherwise."
18762 (let ((re (cond
18763 ((eq what 'headlines) org-outline-regexp-bol)
18764 ((eq what 'items) (org-item-beginning-re))
18765 (t (error "This should not happen"))))
18766 beg end)
18767 (save-excursion
18768 (catch 'exit
18769 (unless (org-region-active-p)
18770 (setq beg (point-at-bol))
18771 (beginning-of-line 2)
18772 (while (and (not (eobp)) ;; this is like `next-line'
18773 (get-char-property (1- (point)) 'invisible))
18774 (beginning-of-line 2))
18775 (setq end (point))
18776 (goto-char beg)
18777 (goto-char (point-at-eol))
18778 (setq end (max end (point)))
18779 (while (re-search-forward re end t)
18780 (if (get-char-property (match-beginning 0) 'invisible)
18781 (throw 'exit t))))
18782 nil))))
18784 (autoload 'org-element-at-point "org-element")
18786 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18787 (declare-function org-element-type "org-element" (element))
18788 (declare-function org-element-contents "org-element" (element))
18789 (declare-function org-element-property "org-element" (property element))
18790 (declare-function org-element-paragraph-parser "org-element" (limit))
18791 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18792 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18793 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18794 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18795 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18797 (defun org-metaup (&optional arg)
18798 "Move subtree up or move table row up.
18799 Calls `org-move-subtree-up' or `org-table-move-row' or
18800 `org-move-item-up', depending on context. See the individual commands
18801 for more information."
18802 (interactive "P")
18803 (cond
18804 ((run-hook-with-args-until-success 'org-metaup-hook))
18805 ((org-region-active-p)
18806 (let* ((a (min (region-beginning) (region-end)))
18807 (b (1- (max (region-beginning) (region-end))))
18808 (c (save-excursion (goto-char a)
18809 (move-beginning-of-line 0)))
18810 (d (save-excursion (goto-char a)
18811 (move-end-of-line 0) (point))))
18812 (transpose-regions a b c d)
18813 (goto-char c)))
18814 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18815 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18816 ((org-at-item-p) (call-interactively 'org-move-item-up))
18817 (t (org-drag-element-backward))))
18819 (defun org-metadown (&optional arg)
18820 "Move subtree down or move table row down.
18821 Calls `org-move-subtree-down' or `org-table-move-row' or
18822 `org-move-item-down', depending on context. See the individual
18823 commands for more information."
18824 (interactive "P")
18825 (cond
18826 ((run-hook-with-args-until-success 'org-metadown-hook))
18827 ((org-region-active-p)
18828 (let* ((a (min (region-beginning) (region-end)))
18829 (b (max (region-beginning) (region-end)))
18830 (c (save-excursion (goto-char b)
18831 (move-beginning-of-line 1)))
18832 (d (save-excursion (goto-char b)
18833 (move-end-of-line 1) (1+ (point)))))
18834 (transpose-regions a b c d)
18835 (goto-char d)))
18836 ((org-at-table-p) (call-interactively 'org-table-move-row))
18837 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18838 ((org-at-item-p) (call-interactively 'org-move-item-down))
18839 (t (org-drag-element-forward))))
18841 (defun org-shiftup (&optional arg)
18842 "Increase item in timestamp or increase priority of current headline.
18843 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18844 depending on context. See the individual commands for more information."
18845 (interactive "P")
18846 (cond
18847 ((run-hook-with-args-until-success 'org-shiftup-hook))
18848 ((and org-support-shift-select (org-region-active-p))
18849 (org-call-for-shift-select 'previous-line))
18850 ((org-at-timestamp-p t)
18851 (call-interactively (if org-edit-timestamp-down-means-later
18852 'org-timestamp-down 'org-timestamp-up)))
18853 ((and (not (eq org-support-shift-select 'always))
18854 org-enable-priority-commands
18855 (org-at-heading-p))
18856 (call-interactively 'org-priority-up))
18857 ((and (not org-support-shift-select) (org-at-item-p))
18858 (call-interactively 'org-previous-item))
18859 ((org-clocktable-try-shift 'up arg))
18860 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18861 (org-support-shift-select
18862 (org-call-for-shift-select 'previous-line))
18863 (t (org-shiftselect-error))))
18865 (defun org-shiftdown (&optional arg)
18866 "Decrease item in timestamp or decrease priority of current headline.
18867 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18868 depending on context. See the individual commands for more information."
18869 (interactive "P")
18870 (cond
18871 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18872 ((and org-support-shift-select (org-region-active-p))
18873 (org-call-for-shift-select 'next-line))
18874 ((org-at-timestamp-p t)
18875 (call-interactively (if org-edit-timestamp-down-means-later
18876 'org-timestamp-up 'org-timestamp-down)))
18877 ((and (not (eq org-support-shift-select 'always))
18878 org-enable-priority-commands
18879 (org-at-heading-p))
18880 (call-interactively 'org-priority-down))
18881 ((and (not org-support-shift-select) (org-at-item-p))
18882 (call-interactively 'org-next-item))
18883 ((org-clocktable-try-shift 'down arg))
18884 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18885 (org-support-shift-select
18886 (org-call-for-shift-select 'next-line))
18887 (t (org-shiftselect-error))))
18889 (defun org-shiftright (&optional arg)
18890 "Cycle the thing at point or in the current line, depending on context.
18891 Depending on context, this does one of the following:
18893 - switch a timestamp at point one day into the future
18894 - on a headline, switch to the next TODO keyword.
18895 - on an item, switch entire list to the next bullet type
18896 - on a property line, switch to the next allowed value
18897 - on a clocktable definition line, move time block into the future"
18898 (interactive "P")
18899 (cond
18900 ((run-hook-with-args-until-success 'org-shiftright-hook))
18901 ((and org-support-shift-select (org-region-active-p))
18902 (org-call-for-shift-select 'forward-char))
18903 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18904 ((and (not (eq org-support-shift-select 'always))
18905 (org-at-heading-p))
18906 (let ((org-inhibit-logging
18907 (not org-treat-S-cursor-todo-selection-as-state-change))
18908 (org-inhibit-blocking
18909 (not org-treat-S-cursor-todo-selection-as-state-change)))
18910 (org-call-with-arg 'org-todo 'right)))
18911 ((or (and org-support-shift-select
18912 (not (eq org-support-shift-select 'always))
18913 (org-at-item-bullet-p))
18914 (and (not org-support-shift-select) (org-at-item-p)))
18915 (org-call-with-arg 'org-cycle-list-bullet nil))
18916 ((and (not (eq org-support-shift-select 'always))
18917 (org-at-property-p))
18918 (call-interactively 'org-property-next-allowed-value))
18919 ((org-clocktable-try-shift 'right arg))
18920 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18921 (org-support-shift-select
18922 (org-call-for-shift-select 'forward-char))
18923 (t (org-shiftselect-error))))
18925 (defun org-shiftleft (&optional arg)
18926 "Cycle the thing at point or in the current line, depending on context.
18927 Depending on context, this does one of the following:
18929 - switch a timestamp at point one day into the past
18930 - on a headline, switch to the previous TODO keyword.
18931 - on an item, switch entire list to the previous bullet type
18932 - on a property line, switch to the previous allowed value
18933 - on a clocktable definition line, move time block into the past"
18934 (interactive "P")
18935 (cond
18936 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18937 ((and org-support-shift-select (org-region-active-p))
18938 (org-call-for-shift-select 'backward-char))
18939 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18940 ((and (not (eq org-support-shift-select 'always))
18941 (org-at-heading-p))
18942 (let ((org-inhibit-logging
18943 (not org-treat-S-cursor-todo-selection-as-state-change))
18944 (org-inhibit-blocking
18945 (not org-treat-S-cursor-todo-selection-as-state-change)))
18946 (org-call-with-arg 'org-todo 'left)))
18947 ((or (and org-support-shift-select
18948 (not (eq org-support-shift-select 'always))
18949 (org-at-item-bullet-p))
18950 (and (not org-support-shift-select) (org-at-item-p)))
18951 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18952 ((and (not (eq org-support-shift-select 'always))
18953 (org-at-property-p))
18954 (call-interactively 'org-property-previous-allowed-value))
18955 ((org-clocktable-try-shift 'left arg))
18956 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18957 (org-support-shift-select
18958 (org-call-for-shift-select 'backward-char))
18959 (t (org-shiftselect-error))))
18961 (defun org-shiftcontrolright ()
18962 "Switch to next TODO set."
18963 (interactive)
18964 (cond
18965 ((and org-support-shift-select (org-region-active-p))
18966 (org-call-for-shift-select 'forward-word))
18967 ((and (not (eq org-support-shift-select 'always))
18968 (org-at-heading-p))
18969 (org-call-with-arg 'org-todo 'nextset))
18970 (org-support-shift-select
18971 (org-call-for-shift-select 'forward-word))
18972 (t (org-shiftselect-error))))
18974 (defun org-shiftcontrolleft ()
18975 "Switch to previous TODO set."
18976 (interactive)
18977 (cond
18978 ((and org-support-shift-select (org-region-active-p))
18979 (org-call-for-shift-select 'backward-word))
18980 ((and (not (eq org-support-shift-select 'always))
18981 (org-at-heading-p))
18982 (org-call-with-arg 'org-todo 'previousset))
18983 (org-support-shift-select
18984 (org-call-for-shift-select 'backward-word))
18985 (t (org-shiftselect-error))))
18987 (defun org-shiftcontrolup ()
18988 "Change timestamps synchronously up in CLOCK log lines."
18989 (interactive)
18990 (cond ((and (not org-support-shift-select)
18991 (org-at-clock-log-p)
18992 (org-at-timestamp-p t))
18993 (org-clock-timestamps-up))
18994 (t (org-shiftselect-error))))
18996 (defun org-shiftcontroldown ()
18997 "Change timestamps synchronously down in CLOCK log lines."
18998 (interactive)
18999 (cond ((and (not org-support-shift-select)
19000 (org-at-clock-log-p)
19001 (org-at-timestamp-p t))
19002 (org-clock-timestamps-down))
19003 (t (org-shiftselect-error))))
19005 (defun org-ctrl-c-ret ()
19006 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19007 (interactive)
19008 (cond
19009 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19010 (t (call-interactively 'org-insert-heading))))
19012 (defun org-find-visible ()
19013 (let ((s (point)))
19014 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19015 (get-char-property s 'invisible)))
19017 (defun org-find-invisible ()
19018 (let ((s (point)))
19019 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19020 (not (get-char-property s 'invisible))))
19023 (defun org-copy-visible (beg end)
19024 "Copy the visible parts of the region."
19025 (interactive "r")
19026 (let (snippets s)
19027 (save-excursion
19028 (save-restriction
19029 (narrow-to-region beg end)
19030 (setq s (goto-char (point-min)))
19031 (while (not (= (point) (point-max)))
19032 (goto-char (org-find-invisible))
19033 (push (buffer-substring s (point)) snippets)
19034 (setq s (goto-char (org-find-visible))))))
19035 (kill-new (apply 'concat (nreverse snippets)))))
19037 (defun org-copy-special ()
19038 "Copy region in table or copy current subtree.
19039 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19040 See the individual commands for more information."
19041 (interactive)
19042 (call-interactively
19043 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19045 (defun org-cut-special ()
19046 "Cut region in table or cut current subtree.
19047 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19048 See the individual commands for more information."
19049 (interactive)
19050 (call-interactively
19051 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19053 (defun org-paste-special (arg)
19054 "Paste rectangular region into table, or past subtree relative to level.
19055 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19056 See the individual commands for more information."
19057 (interactive "P")
19058 (if (org-at-table-p)
19059 (org-table-paste-rectangle)
19060 (org-paste-subtree arg)))
19062 (defun org-edit-special (&optional arg)
19063 "Call a special editor for the stuff at point.
19064 When at a table, call the formula editor with `org-table-edit-formulas'.
19065 When at the first line of an src example, call `org-edit-src-code'.
19066 When in an #+include line, visit the include file. Otherwise call
19067 `ffap' to visit the file at point."
19068 (interactive)
19069 ;; possibly prep session before editing source
19070 (when arg
19071 (let* ((info (org-babel-get-src-block-info))
19072 (lang (nth 0 info))
19073 (params (nth 2 info))
19074 (session (cdr (assoc :session params))))
19075 (when (and info session) ;; we are in a source-code block with a session
19076 (funcall
19077 (intern (concat "org-babel-prep-session:" lang)) session params))))
19078 (cond ;; proceed with `org-edit-special'
19079 ((save-excursion
19080 (beginning-of-line 1)
19081 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19082 (find-file (org-trim (match-string 1))))
19083 ((org-edit-src-code))
19084 ((org-edit-fixed-width-region))
19085 ((org-at-table.el-p)
19086 (org-edit-src-code))
19087 ((or (org-at-table-p)
19088 (save-excursion
19089 (beginning-of-line 1)
19090 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19091 (call-interactively 'org-table-edit-formulas))
19092 (t (call-interactively 'ffap))))
19094 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19095 (defun org-ctrl-c-ctrl-c (&optional arg)
19096 "Set tags in headline, or update according to changed information at point.
19098 This command does many different things, depending on context:
19100 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19101 this is what we do.
19103 - If the cursor is on a statistics cookie, update it.
19105 - If the cursor is in a headline, prompt for tags and insert them
19106 into the current line, aligned to `org-tags-column'. When called
19107 with prefix arg, realign all tags in the current buffer.
19109 - If the cursor is in one of the special #+KEYWORD lines, this
19110 triggers scanning the buffer for these lines and updating the
19111 information.
19113 - If the cursor is inside a table, realign the table. This command
19114 works even if the automatic table editor has been turned off.
19116 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19117 the entire table.
19119 - If the cursor is at a footnote reference or definition, jump to
19120 the corresponding definition or references, respectively.
19122 - If the cursor is a the beginning of a dynamic block, update it.
19124 - If the current buffer is a capture buffer, close note and file it.
19126 - If the cursor is on a <<<target>>>, update radio targets and
19127 corresponding links in this buffer.
19129 - If the cursor is on a numbered item in a plain list, renumber the
19130 ordered list.
19132 - If the cursor is on a checkbox, toggle it.
19134 - If the cursor is on a code block, evaluate it. The variable
19135 `org-confirm-babel-evaluate' can be used to control prompting
19136 before code block evaluation, by default every code block
19137 evaluation requires confirmation. Code block evaluation can be
19138 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19139 (interactive "P")
19140 (let ((org-enable-table-editor t))
19141 (cond
19142 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19143 org-occur-highlights
19144 org-latex-fragment-image-overlays)
19145 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19146 (org-remove-occur-highlights)
19147 (org-remove-latex-fragment-image-overlays)
19148 (message "Temporary highlights/overlays removed from current buffer"))
19149 ((and (local-variable-p 'org-finish-function (current-buffer))
19150 (fboundp org-finish-function))
19151 (funcall org-finish-function))
19152 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19153 ((org-in-regexp org-ts-regexp-both)
19154 (org-timestamp-change 0 'day))
19155 ((or (looking-at org-property-start-re)
19156 (org-at-property-p))
19157 (call-interactively 'org-property-action))
19158 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19159 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19160 (or (org-at-heading-p) (org-at-item-p)))
19161 (call-interactively 'org-update-statistics-cookies))
19162 ((org-at-heading-p) (call-interactively 'org-set-tags))
19163 ((org-at-table.el-p)
19164 (message "Use C-c ' to edit table.el tables"))
19165 ((org-at-table-p)
19166 (org-table-maybe-eval-formula)
19167 (if arg
19168 (call-interactively 'org-table-recalculate)
19169 (org-table-maybe-recalculate-line))
19170 (call-interactively 'org-table-align)
19171 (orgtbl-send-table 'maybe))
19172 ((or (org-footnote-at-reference-p)
19173 (org-footnote-at-definition-p))
19174 (call-interactively 'org-footnote-action))
19175 ((org-at-item-checkbox-p)
19176 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19177 ;; list only if at top item.
19178 (let* ((cbox (match-string 1))
19179 (struct (org-list-struct))
19180 (old-struct (copy-tree struct))
19181 (parents (org-list-parents-alist struct))
19182 (orderedp (org-entry-get nil "ORDERED"))
19183 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19184 block-item)
19185 ;; Use a light version of `org-toggle-checkbox' to avoid
19186 ;; computing list structure twice.
19187 (let ((new-box (cond
19188 ((equal arg '(16)) "[-]")
19189 ((equal arg '(4)) nil)
19190 ((equal "[X]" cbox) "[ ]")
19191 (t "[X]"))))
19192 (if (and firstp arg)
19193 ;; If at first item of sub-list, remove check-box from
19194 ;; every item at the same level.
19195 (mapc
19196 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19197 (org-list-get-all-items
19198 (point-at-bol) struct (org-list-prevs-alist struct)))
19199 (org-list-set-checkbox (point-at-bol) struct new-box)))
19200 ;; Replicate `org-list-write-struct', while grabbing a return
19201 ;; value from `org-list-struct-fix-box'.
19202 (org-list-struct-fix-ind struct parents 2)
19203 (org-list-struct-fix-item-end struct)
19204 (let ((prevs (org-list-prevs-alist struct)))
19205 (org-list-struct-fix-bul struct prevs)
19206 (org-list-struct-fix-ind struct parents)
19207 (setq block-item
19208 (org-list-struct-fix-box struct parents prevs orderedp)))
19209 (org-list-struct-apply-struct struct old-struct)
19210 (org-update-checkbox-count-maybe)
19211 (when block-item
19212 (message
19213 "Checkboxes were removed due to unchecked box at line %d"
19214 (org-current-line block-item)))
19215 (when firstp (org-list-send-list 'maybe))))
19216 ((org-at-item-p)
19217 ;; Cursor at an item: repair list. Do checkbox related actions
19218 ;; only if function was called with an argument. Send list only
19219 ;; if at top item.
19220 (let* ((struct (org-list-struct))
19221 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19222 old-struct)
19223 (when arg
19224 (setq old-struct (copy-tree struct))
19225 (if firstp
19226 ;; If at first item of sub-list, add check-box to every
19227 ;; item at the same level.
19228 (mapc
19229 (lambda (pos)
19230 (unless (org-list-get-checkbox pos struct)
19231 (org-list-set-checkbox pos struct "[ ]")))
19232 (org-list-get-all-items
19233 (point-at-bol) struct (org-list-prevs-alist struct)))
19234 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19235 (org-list-write-struct
19236 struct (org-list-parents-alist struct) old-struct)
19237 (when arg (org-update-checkbox-count-maybe))
19238 (when firstp (org-list-send-list 'maybe))))
19239 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19240 ;; Dynamic block
19241 (beginning-of-line 1)
19242 (save-excursion (org-update-dblock)))
19243 ((save-excursion
19244 (let ((case-fold-search t))
19245 (beginning-of-line 1)
19246 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19247 (cond
19248 ((or (equal (match-string 1) "TBLFM")
19249 (equal (match-string 1) "tblfm"))
19250 ;; Recalculate the table before this line
19251 (save-excursion
19252 (beginning-of-line 1)
19253 (skip-chars-backward " \r\n\t")
19254 (if (org-at-table-p)
19255 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19257 (let ((org-inhibit-startup-visibility-stuff t)
19258 (org-startup-align-all-tables nil))
19259 (when (boundp 'org-table-coordinate-overlays)
19260 (mapc 'delete-overlay org-table-coordinate-overlays)
19261 (setq org-table-coordinate-overlays nil))
19262 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19263 (message "Local setup has been refreshed"))))
19264 ((org-clock-update-time-maybe))
19266 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19267 (error "C-c C-c can do nothing useful at this location"))))))
19269 (defun org-mode-restart ()
19270 "Restart Org-mode, to scan again for special lines.
19271 Also updates the keyword regular expressions."
19272 (interactive)
19273 (org-mode)
19274 (message "Org-mode restarted"))
19276 (defun org-kill-note-or-show-branches ()
19277 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19278 (interactive)
19279 (if (not org-finish-function)
19280 (progn
19281 (hide-subtree)
19282 (call-interactively 'show-branches))
19283 (let ((org-note-abort t))
19284 (funcall org-finish-function))))
19286 (defun org-return (&optional indent)
19287 "Goto next table row or insert a newline.
19288 Calls `org-table-next-row' or `newline', depending on context.
19289 See the individual commands for more information."
19290 (interactive)
19291 (let (org-ts-what)
19292 (cond
19293 ((or (bobp) (org-in-src-block-p))
19294 (if indent (newline-and-indent) (newline)))
19295 ((org-at-table-p)
19296 (org-table-justify-field-maybe)
19297 (call-interactively 'org-table-next-row))
19298 ;; when `newline-and-indent' is called within a list, make sure
19299 ;; text moved stays inside the item.
19300 ((and (org-in-item-p) indent)
19301 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19302 (progn
19303 (save-match-data (newline))
19304 (org-indent-line-to (length (match-string 0))))
19305 (let ((ind (org-get-indentation)))
19306 (newline)
19307 (if (org-looking-back org-list-end-re)
19308 (org-indent-line)
19309 (org-indent-line-to ind)))))
19310 ((and org-return-follows-link
19311 (org-at-timestamp-p t)
19312 (not (eq org-ts-what 'after)))
19313 (org-follow-timestamp-link))
19314 ((and org-return-follows-link
19315 (let ((tprop (get-text-property (point) 'face)))
19316 (or (eq tprop 'org-link)
19317 (and (listp tprop) (memq 'org-link tprop)))))
19318 (call-interactively 'org-open-at-point))
19319 ((and (org-at-heading-p)
19320 (looking-at
19321 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19322 (org-show-entry)
19323 (end-of-line 1)
19324 (newline))
19325 (t (if indent (newline-and-indent) (newline))))))
19327 (defun org-return-indent ()
19328 "Goto next table row or insert a newline and indent.
19329 Calls `org-table-next-row' or `newline-and-indent', depending on
19330 context. See the individual commands for more information."
19331 (interactive)
19332 (org-return t))
19334 (defun org-ctrl-c-star ()
19335 "Compute table, or change heading status of lines.
19336 Calls `org-table-recalculate' or `org-toggle-heading',
19337 depending on context."
19338 (interactive)
19339 (cond
19340 ((org-at-table-p)
19341 (call-interactively 'org-table-recalculate))
19343 ;; Convert all lines in region to list items
19344 (call-interactively 'org-toggle-heading))))
19346 (defun org-ctrl-c-minus ()
19347 "Insert separator line in table or modify bullet status of line.
19348 Also turns a plain line or a region of lines into list items.
19349 Calls `org-table-insert-hline', `org-toggle-item', or
19350 `org-cycle-list-bullet', depending on context."
19351 (interactive)
19352 (cond
19353 ((org-at-table-p)
19354 (call-interactively 'org-table-insert-hline))
19355 ((org-region-active-p)
19356 (call-interactively 'org-toggle-item))
19357 ((org-in-item-p)
19358 (call-interactively 'org-cycle-list-bullet))
19360 (call-interactively 'org-toggle-item))))
19362 (defun org-toggle-item (arg)
19363 "Convert headings or normal lines to items, items to normal lines.
19364 If there is no active region, only the current line is considered.
19366 If the first non blank line in the region is an headline, convert
19367 all headlines to items, shifting text accordingly.
19369 If it is an item, convert all items to normal lines.
19371 If it is normal text, change region into an item. With a prefix
19372 argument ARG, change each line in region into an item."
19373 (interactive "P")
19374 (let ((shift-text
19375 (function
19376 ;; Shift text in current section to IND, from point to END.
19377 ;; The function leaves point to END line.
19378 (lambda (ind end)
19379 (let ((min-i 1000) (end (copy-marker end)))
19380 ;; First determine the minimum indentation (MIN-I) of
19381 ;; the text.
19382 (save-excursion
19383 (catch 'exit
19384 (while (< (point) end)
19385 (let ((i (org-get-indentation)))
19386 (cond
19387 ;; Skip blank lines and inline tasks.
19388 ((looking-at "^[ \t]*$"))
19389 ((looking-at org-outline-regexp-bol))
19390 ;; We can't find less than 0 indentation.
19391 ((zerop i) (throw 'exit (setq min-i 0)))
19392 ((< i min-i) (setq min-i i))))
19393 (forward-line))))
19394 ;; Then indent each line so that a line indented to
19395 ;; MIN-I becomes indented to IND. Ignore blank lines
19396 ;; and inline tasks in the process.
19397 (let ((delta (- ind min-i)))
19398 (while (< (point) end)
19399 (unless (or (looking-at "^[ \t]*$")
19400 (looking-at org-outline-regexp-bol))
19401 (org-indent-line-to (+ (org-get-indentation) delta)))
19402 (forward-line)))))))
19403 (skip-blanks
19404 (function
19405 ;; Return beginning of first non-blank line, starting from
19406 ;; line at POS.
19407 (lambda (pos)
19408 (save-excursion
19409 (goto-char pos)
19410 (skip-chars-forward " \r\t\n")
19411 (point-at-bol)))))
19412 beg end)
19413 ;; Determine boundaries of changes.
19414 (if (org-region-active-p)
19415 (setq beg (funcall skip-blanks (region-beginning))
19416 end (copy-marker (region-end)))
19417 (setq beg (funcall skip-blanks (point-at-bol))
19418 end (copy-marker (point-at-eol))))
19419 ;; Depending on the starting line, choose an action on the text
19420 ;; between BEG and END.
19421 (org-with-limited-levels
19422 (save-excursion
19423 (goto-char beg)
19424 (cond
19425 ;; Case 1. Start at an item: de-itemize. Note that it only
19426 ;; happens when a region is active: `org-ctrl-c-minus'
19427 ;; would call `org-cycle-list-bullet' otherwise.
19428 ((org-at-item-p)
19429 (while (< (point) end)
19430 (when (org-at-item-p)
19431 (skip-chars-forward " \t")
19432 (delete-region (point) (match-end 0)))
19433 (forward-line)))
19434 ;; Case 2. Start at an heading: convert to items.
19435 ((org-at-heading-p)
19436 (let* ((bul (org-list-bullet-string "-"))
19437 (bul-len (length bul))
19438 ;; Indentation of the first heading. It should be
19439 ;; relative to the indentation of its parent, if any.
19440 (start-ind (save-excursion
19441 (cond
19442 ((not org-adapt-indentation) 0)
19443 ((not (outline-previous-heading)) 0)
19444 (t (length (match-string 0))))))
19445 ;; Level of first heading. Further headings will be
19446 ;; compared to it to determine hierarchy in the list.
19447 (ref-level (org-reduced-level (org-outline-level))))
19448 (while (< (point) end)
19449 (let* ((level (org-reduced-level (org-outline-level)))
19450 (delta (max 0 (- level ref-level))))
19451 ;; If current headline is less indented than the first
19452 ;; one, set it as reference, in order to preserve
19453 ;; subtrees.
19454 (when (< level ref-level) (setq ref-level level))
19455 (replace-match bul t t)
19456 (org-indent-line-to (+ start-ind (* delta bul-len)))
19457 ;; Ensure all text down to END (or SECTION-END) belongs
19458 ;; to the newly created item.
19459 (let ((section-end (save-excursion
19460 (or (outline-next-heading) (point)))))
19461 (forward-line)
19462 (funcall shift-text
19463 (+ start-ind (* (1+ delta) bul-len))
19464 (min end section-end)))))))
19465 ;; Case 3. Normal line with ARG: turn each non-item line into
19466 ;; an item.
19467 (arg
19468 (while (< (point) end)
19469 (unless (or (org-at-heading-p) (org-at-item-p))
19470 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19471 (replace-match
19472 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19473 (forward-line)))
19474 ;; Case 4. Normal line without ARG: make the first line of
19475 ;; region an item, and shift indentation of others
19476 ;; lines to set them as item's body.
19477 (t (let* ((bul (org-list-bullet-string "-"))
19478 (bul-len (length bul))
19479 (ref-ind (org-get-indentation)))
19480 (skip-chars-forward " \t")
19481 (insert bul)
19482 (forward-line)
19483 (while (< (point) end)
19484 ;; Ensure that lines less indented than first one
19485 ;; still get included in item body.
19486 (funcall shift-text
19487 (+ ref-ind bul-len)
19488 (min end (save-excursion (or (outline-next-heading)
19489 (point)))))
19490 (forward-line)))))))))
19492 (defun org-toggle-heading (&optional nstars)
19493 "Convert headings to normal text, or items or text to headings.
19494 If there is no active region, only the current line is considered.
19496 With a \\[universal-argument] prefix, convert the whole list at
19497 point into heading.
19499 In a region:
19501 - If the first non blank line is an headline, remove the stars
19502 from all headlines in the region.
19504 - If it is a normal line turn each and every normal line (i.e. not an
19505 heading or an item) in the region into a heading.
19507 - If it is a plain list item, turn all plain list items into headings.
19509 When converting a line into a heading, the number of stars is chosen
19510 such that the lines become children of the current entry. However,
19511 when a prefix argument is given, its value determines the number of
19512 stars to add."
19513 (interactive "P")
19514 (let ((skip-blanks
19515 (function
19516 ;; Return beginning of first non-blank line, starting from
19517 ;; line at POS.
19518 (lambda (pos)
19519 (save-excursion
19520 (goto-char pos)
19521 (while (org-at-comment-p) (forward-line))
19522 (skip-chars-forward " \r\t\n")
19523 (point-at-bol)))))
19524 beg end toggled)
19525 ;; Determine boundaries of changes. If a universal prefix has
19526 ;; been given, put the list in a region. If region ends at a bol,
19527 ;; do not consider the last line to be in the region.
19529 (when (and current-prefix-arg (org-at-item-p))
19530 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19531 (org-mark-element))
19533 (if (org-region-active-p)
19534 (setq beg (funcall skip-blanks (region-beginning))
19535 end (copy-marker (save-excursion
19536 (goto-char (region-end))
19537 (if (bolp) (point) (point-at-eol)))))
19538 (setq beg (funcall skip-blanks (point-at-bol))
19539 end (copy-marker (point-at-eol))))
19540 ;; Ensure inline tasks don't count as headings.
19541 (org-with-limited-levels
19542 (save-excursion
19543 (goto-char beg)
19544 (cond
19545 ;; Case 1. Started at an heading: de-star headings.
19546 ((org-at-heading-p)
19547 (while (< (point) end)
19548 (when (org-at-heading-p t)
19549 (looking-at org-outline-regexp) (replace-match "")
19550 (setq toggled t))
19551 (forward-line)))
19552 ;; Case 2. Started at an item: change items into headlines.
19553 ;; One star will be added by `org-list-to-subtree'.
19554 ((org-at-item-p)
19555 (let* ((stars (make-string
19556 (if nstars
19557 ;; subtract the star that will be added again by
19558 ;; `org-list-to-subtree'
19559 (1- (prefix-numeric-value current-prefix-arg))
19560 (or (org-current-level) 0))
19561 ?*))
19562 (add-stars
19563 (cond (nstars "") ; stars from prefix only
19564 ((equal stars "") "") ; before first heading
19565 (org-odd-levels-only "*") ; inside heading, odd
19566 (t "")))) ; inside heading, oddeven
19567 (while (< (point) end)
19568 (when (org-at-item-p)
19569 ;; Pay attention to cases when region ends before list.
19570 (let* ((struct (org-list-struct))
19571 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19572 (save-restriction
19573 (narrow-to-region (point) list-end)
19574 (insert
19575 (org-list-to-subtree
19576 (org-list-parse-list t)
19577 '(:istart (concat stars add-stars (funcall get-stars depth))
19578 :icount (concat stars add-stars (funcall get-stars depth)))))))
19579 (setq toggled t))
19580 (forward-line))))
19581 ;; Case 3. Started at normal text: make every line an heading,
19582 ;; skipping headlines and items.
19583 (t (let* ((stars (make-string
19584 (if nstars
19585 (prefix-numeric-value current-prefix-arg)
19586 (or (org-current-level) 0))
19587 ?*))
19588 (add-stars
19589 (cond (nstars "") ; stars from prefix only
19590 ((equal stars "") "*") ; before first heading
19591 (org-odd-levels-only "**") ; inside heading, odd
19592 (t "*"))) ; inside heading, oddeven
19593 (rpl (concat stars add-stars " ")))
19594 (while (< (point) end)
19595 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19596 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19597 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19598 (forward-line)))))))
19599 (unless toggled (message "Cannot toggle heading from here"))))
19601 (defun org-meta-return (&optional arg)
19602 "Insert a new heading or wrap a region in a table.
19603 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19604 See the individual commands for more information."
19605 (interactive "P")
19606 (cond
19607 ((run-hook-with-args-until-success 'org-metareturn-hook))
19608 ((or (org-at-drawer-p) (org-at-property-p))
19609 (newline-and-indent))
19610 ((org-at-table-p)
19611 (call-interactively 'org-table-wrap-region))
19612 (t (call-interactively 'org-insert-heading))))
19614 ;;; Menu entries
19616 ;; Define the Org-mode menus
19617 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19618 '("Tbl"
19619 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19620 ["Next Field" org-cycle (org-at-table-p)]
19621 ["Previous Field" org-shifttab (org-at-table-p)]
19622 ["Next Row" org-return (org-at-table-p)]
19623 "--"
19624 ["Blank Field" org-table-blank-field (org-at-table-p)]
19625 ["Edit Field" org-table-edit-field (org-at-table-p)]
19626 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19627 "--"
19628 ("Column"
19629 ["Move Column Left" org-metaleft (org-at-table-p)]
19630 ["Move Column Right" org-metaright (org-at-table-p)]
19631 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19632 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19633 ("Row"
19634 ["Move Row Up" org-metaup (org-at-table-p)]
19635 ["Move Row Down" org-metadown (org-at-table-p)]
19636 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19637 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19638 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19639 "--"
19640 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19641 ("Rectangle"
19642 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19643 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19644 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19645 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19646 "--"
19647 ("Calculate"
19648 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19649 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19650 ["Edit Formulas" org-edit-special (org-at-table-p)]
19651 "--"
19652 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19653 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19654 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19655 "--"
19656 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19657 "--"
19658 ["Sum Column/Rectangle" org-table-sum
19659 (or (org-at-table-p) (org-region-active-p))]
19660 ["Which Column?" org-table-current-column (org-at-table-p)])
19661 ["Debug Formulas"
19662 org-table-toggle-formula-debugger
19663 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19664 ["Show Col/Row Numbers"
19665 org-table-toggle-coordinate-overlays
19666 :style toggle
19667 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19668 "--"
19669 ["Create" org-table-create (and (not (org-at-table-p))
19670 org-enable-table-editor)]
19671 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19672 ["Import from File" org-table-import (not (org-at-table-p))]
19673 ["Export to File" org-table-export (org-at-table-p)]
19674 "--"
19675 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19677 (easy-menu-define org-org-menu org-mode-map "Org menu"
19678 '("Org"
19679 ("Show/Hide"
19680 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19681 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19682 ["Sparse Tree..." org-sparse-tree t]
19683 ["Reveal Context" org-reveal t]
19684 ["Show All" show-all t]
19685 "--"
19686 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19687 "--"
19688 ["New Heading" org-insert-heading t]
19689 ("Navigate Headings"
19690 ["Up" outline-up-heading t]
19691 ["Next" outline-next-visible-heading t]
19692 ["Previous" outline-previous-visible-heading t]
19693 ["Next Same Level" outline-forward-same-level t]
19694 ["Previous Same Level" outline-backward-same-level t]
19695 "--"
19696 ["Jump" org-goto t])
19697 ("Edit Structure"
19698 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19699 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19700 "--"
19701 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19702 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19703 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19704 "--"
19705 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19706 "--"
19707 ["Copy visible text" org-copy-visible t]
19708 "--"
19709 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19710 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19711 ["Demote Heading" org-metaright (not (org-at-table-p))]
19712 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19713 "--"
19714 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19715 "--"
19716 ["Convert to odd levels" org-convert-to-odd-levels t]
19717 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19718 ("Editing"
19719 ["Emphasis..." org-emphasize t]
19720 ["Edit Source Example" org-edit-special t]
19721 "--"
19722 ["Footnote new/jump" org-footnote-action t]
19723 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19724 ("Archive"
19725 ["Archive (default method)" org-archive-subtree-default t]
19726 "--"
19727 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19728 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19729 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19731 "--"
19732 ("Hyperlinks"
19733 ["Store Link (Global)" org-store-link t]
19734 ["Find existing link to here" org-occur-link-in-agenda-files t]
19735 ["Insert Link" org-insert-link t]
19736 ["Follow Link" org-open-at-point t]
19737 "--"
19738 ["Next link" org-next-link t]
19739 ["Previous link" org-previous-link t]
19740 "--"
19741 ["Descriptive Links"
19742 org-toggle-link-display
19743 :style radio
19744 :selected org-descriptive-links
19746 ["Literal Links"
19747 org-toggle-link-display
19748 :style radio
19749 :selected (not org-descriptive-links)])
19750 "--"
19751 ("TODO Lists"
19752 ["TODO/DONE/-" org-todo t]
19753 ("Select keyword"
19754 ["Next keyword" org-shiftright (org-at-heading-p)]
19755 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19756 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19757 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19758 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19759 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19760 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19761 "--"
19762 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19763 :selected org-enforce-todo-dependencies :style toggle :active t]
19764 "Settings for tree at point"
19765 ["Do Children sequentially" org-toggle-ordered-property :style radio
19766 :selected (org-entry-get nil "ORDERED")
19767 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19768 ["Do Children parallel" org-toggle-ordered-property :style radio
19769 :selected (not (org-entry-get nil "ORDERED"))
19770 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19771 "--"
19772 ["Set Priority" org-priority t]
19773 ["Priority Up" org-shiftup t]
19774 ["Priority Down" org-shiftdown t]
19775 "--"
19776 ["Get news from all feeds" org-feed-update-all t]
19777 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19778 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19779 ("TAGS and Properties"
19780 ["Set Tags" org-set-tags-command t]
19781 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19782 "--"
19783 ["Set property" org-set-property t]
19784 ["Column view of properties" org-columns t]
19785 ["Insert Column View DBlock" org-insert-columns-dblock t])
19786 ("Dates and Scheduling"
19787 ["Timestamp" org-time-stamp t]
19788 ["Timestamp (inactive)" org-time-stamp-inactive t]
19789 ("Change Date"
19790 ["1 Day Later" org-shiftright t]
19791 ["1 Day Earlier" org-shiftleft t]
19792 ["1 ... Later" org-shiftup t]
19793 ["1 ... Earlier" org-shiftdown t])
19794 ["Compute Time Range" org-evaluate-time-range t]
19795 ["Schedule Item" org-schedule t]
19796 ["Deadline" org-deadline t]
19797 "--"
19798 ["Custom time format" org-toggle-time-stamp-overlays
19799 :style radio :selected org-display-custom-times]
19800 "--"
19801 ["Goto Calendar" org-goto-calendar t]
19802 ["Date from Calendar" org-date-from-calendar t]
19803 "--"
19804 ["Start/Restart Timer" org-timer-start t]
19805 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19806 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19807 ["Insert Timer String" org-timer t]
19808 ["Insert Timer Item" org-timer-item t])
19809 ("Logging work"
19810 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19811 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19812 ["Clock out" org-clock-out t]
19813 ["Clock cancel" org-clock-cancel t]
19814 "--"
19815 ["Mark as default task" org-clock-mark-default-task t]
19816 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19817 ["Goto running clock" org-clock-goto t]
19818 "--"
19819 ["Display times" org-clock-display t]
19820 ["Create clock table" org-clock-report t]
19821 "--"
19822 ["Record DONE time"
19823 (progn (setq org-log-done (not org-log-done))
19824 (message "Switching to %s will %s record a timestamp"
19825 (car org-done-keywords)
19826 (if org-log-done "automatically" "not")))
19827 :style toggle :selected org-log-done])
19828 "--"
19829 ["Agenda Command..." org-agenda t]
19830 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19831 ("File List for Agenda")
19832 ("Special views current file"
19833 ["TODO Tree" org-show-todo-tree t]
19834 ["Check Deadlines" org-check-deadlines t]
19835 ["Timeline" org-timeline t]
19836 ["Tags/Property tree" org-match-sparse-tree t])
19837 "--"
19838 ["Export/Publish..." org-export t]
19839 ("LaTeX"
19840 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19841 :selected org-cdlatex-mode]
19842 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19843 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19844 ["Modify math symbol" org-cdlatex-math-modify
19845 (org-inside-LaTeX-fragment-p)]
19846 ["Insert citation" org-reftex-citation t]
19847 "--"
19848 ["Template for BEAMER" (progn (require 'org-beamer)
19849 (org-insert-beamer-options-template)) t])
19850 "--"
19851 ("MobileOrg"
19852 ["Push Files and Views" org-mobile-push t]
19853 ["Get Captured and Flagged" org-mobile-pull t]
19854 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19855 "--"
19856 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19857 "--"
19858 ("Documentation"
19859 ["Show Version" org-version t]
19860 ["Info Documentation" org-info t])
19861 ("Customize"
19862 ["Browse Org Group" org-customize t]
19863 "--"
19864 ["Expand This Menu" org-create-customize-menu
19865 (fboundp 'customize-menu-create)])
19866 ["Send bug report" org-submit-bug-report t]
19867 "--"
19868 ("Refresh/Reload"
19869 ["Refresh setup current buffer" org-mode-restart t]
19870 ["Reload Org (after update)" org-reload t]
19871 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19874 (defun org-info (&optional node)
19875 "Read documentation for Org-mode in the info system.
19876 With optional NODE, go directly to that node."
19877 (interactive)
19878 (info (format "(org)%s" (or node ""))))
19880 ;;;###autoload
19881 (defun org-submit-bug-report ()
19882 "Submit a bug report on Org-mode via mail.
19884 Don't hesitate to report any problems or inaccurate documentation.
19886 If you don't have setup sending mail from (X)Emacs, please copy the
19887 output buffer into your mail program, as it gives us important
19888 information about your Org-mode version and configuration."
19889 (interactive)
19890 (require 'reporter)
19891 (org-load-modules-maybe)
19892 (org-require-autoloaded-modules)
19893 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19894 (reporter-submit-bug-report
19895 "emacs-orgmode@gnu.org"
19896 (org-version nil 'full)
19897 (let (list)
19898 (save-window-excursion
19899 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19900 (delete-other-windows)
19901 (erase-buffer)
19902 (insert "You are about to submit a bug report to the Org-mode mailing list.
19904 We would like to add your full Org-mode and Outline configuration to the
19905 bug report. This greatly simplifies the work of the maintainer and
19906 other experts on the mailing list.
19908 HOWEVER, some variables you have customized may contain private
19909 information. The names of customers, colleagues, or friends, might
19910 appear in the form of file names, tags, todo states, or search strings.
19911 If you answer yes to the prompt, you might want to check and remove
19912 such private information before sending the email.")
19913 (add-text-properties (point-min) (point-max) '(face org-warning))
19914 (when (yes-or-no-p "Include your Org-mode configuration ")
19915 (mapatoms
19916 (lambda (v)
19917 (and (boundp v)
19918 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19919 (or (and (symbol-value v)
19920 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19921 (and
19922 (get v 'custom-type) (get v 'standard-value)
19923 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19924 (push v list)))))
19925 (kill-buffer (get-buffer "*Warn about privacy*"))
19926 list))
19927 nil nil
19928 "Remember to cover the basics, that is, what you expected to happen and
19929 what in fact did happen. You don't know how to make a good report? See
19931 http://orgmode.org/manual/Feedback.html#Feedback
19933 Your bug report will be posted to the Org-mode mailing list.
19934 ------------------------------------------------------------------------")
19935 (save-excursion
19936 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19937 (replace-match "\\1Bug: \\3 [\\2]")))))
19940 (defun org-install-agenda-files-menu ()
19941 (let ((bl (buffer-list)))
19942 (save-excursion
19943 (while bl
19944 (set-buffer (pop bl))
19945 (if (derived-mode-p 'org-mode) (setq bl nil)))
19946 (when (derived-mode-p 'org-mode)
19947 (easy-menu-change
19948 '("Org") "File List for Agenda"
19949 (append
19950 (list
19951 ["Edit File List" (org-edit-agenda-file-list) t]
19952 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19953 ["Remove Current File from List" org-remove-file t]
19954 ["Cycle through agenda files" org-cycle-agenda-files t]
19955 ["Occur in all agenda files" org-occur-in-agenda-files t]
19956 "--")
19957 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19959 ;;;; Documentation
19961 ;;;###autoload
19962 (defun org-require-autoloaded-modules ()
19963 (interactive)
19964 (mapc 'require
19965 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19966 org-docbook org-exp org-html org-icalendar
19967 org-id org-latex
19968 org-publish org-remember org-table
19969 org-timer org-xoxo)))
19971 ;;;###autoload
19972 (defun org-reload (&optional uncompiled)
19973 "Reload all org lisp files.
19974 With prefix arg UNCOMPILED, load the uncompiled versions."
19975 (interactive "P")
19976 (require 'find-func)
19977 (let* ((file-re "^org\\(-.*\\)?\\.el")
19978 (dir-org (file-name-directory (org-find-library-dir "org")))
19979 (dir-org-contrib (ignore-errors
19980 (file-name-directory
19981 (org-find-library-dir "org-contribdir"))))
19982 (babel-files
19983 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19984 (append (list nil "comint" "eval" "exp" "keys"
19985 "lob" "ref" "table" "tangle")
19986 (delq nil
19987 (mapcar
19988 (lambda (lang)
19989 (when (cdr lang) (symbol-name (car lang))))
19990 org-babel-load-languages)))))
19991 (files
19992 (append babel-files
19993 (and dir-org-contrib
19994 (directory-files dir-org-contrib t file-re))
19995 (directory-files dir-org t file-re)))
19996 (remove-re (concat (if (featurep 'xemacs)
19997 "org-colview" "org-colview-xemacs")
19998 "\\'")))
19999 (setq files (mapcar 'file-name-sans-extension files))
20000 (setq files (mapcar
20001 (lambda (x) (if (string-match remove-re x) nil x))
20002 files))
20003 (setq files (delq nil files))
20004 (mapc
20005 (lambda (f)
20006 (when (featurep (intern (file-name-nondirectory f)))
20007 (if (and (not uncompiled)
20008 (file-exists-p (concat f ".elc")))
20009 (load (concat f ".elc") nil nil 'nosuffix)
20010 (load (concat f ".el") nil nil 'nosuffix))))
20011 files)
20012 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20013 (org-version nil 'full 'message))
20015 ;;;###autoload
20016 (defun org-customize ()
20017 "Call the customize function with org as argument."
20018 (interactive)
20019 (org-load-modules-maybe)
20020 (org-require-autoloaded-modules)
20021 (customize-browse 'org))
20023 (defun org-create-customize-menu ()
20024 "Create a full customization menu for Org-mode, insert it into the menu."
20025 (interactive)
20026 (org-load-modules-maybe)
20027 (org-require-autoloaded-modules)
20028 (if (fboundp 'customize-menu-create)
20029 (progn
20030 (easy-menu-change
20031 '("Org") "Customize"
20032 `(["Browse Org group" org-customize t]
20033 "--"
20034 ,(customize-menu-create 'org)
20035 ["Set" Custom-set t]
20036 ["Save" Custom-save t]
20037 ["Reset to Current" Custom-reset-current t]
20038 ["Reset to Saved" Custom-reset-saved t]
20039 ["Reset to Standard Settings" Custom-reset-standard t]))
20040 (message "\"Org\"-menu now contains full customization menu"))
20041 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20043 ;;;; Miscellaneous stuff
20045 ;;; Generally useful functions
20047 (defun org-get-at-bol (property)
20048 "Get text property PROPERTY at beginning of line."
20049 (get-text-property (point-at-bol) property))
20051 (defun org-find-text-property-in-string (prop s)
20052 "Return the first non-nil value of property PROP in string S."
20053 (or (get-text-property 0 prop s)
20054 (get-text-property (or (next-single-property-change 0 prop s) 0)
20055 prop s)))
20057 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20058 "Display the given MESSAGE as a warning."
20059 (if (fboundp 'display-warning)
20060 (display-warning 'org message
20061 (if (featurep 'xemacs) 'warning :warning))
20062 (let ((buf (get-buffer-create "*Org warnings*")))
20063 (with-current-buffer buf
20064 (goto-char (point-max))
20065 (insert "Warning (Org): " message)
20066 (unless (bolp)
20067 (newline)))
20068 (display-buffer buf)
20069 (sit-for 0))))
20071 (defun org-eval (form)
20072 "Eval FORM and return result."
20073 (condition-case error
20074 (eval form)
20075 (error (format "%%![Error: %s]" error))))
20077 (defun org-in-clocktable-p ()
20078 "Check if the cursor is in a clocktable."
20079 (let ((pos (point)) start)
20080 (save-excursion
20081 (end-of-line 1)
20082 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20083 (setq start (match-beginning 0))
20084 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20085 (>= (match-end 0) pos)
20086 start))))
20088 (defun org-in-commented-line ()
20089 "Is point in a line starting with `#'?"
20090 (equal (char-after (point-at-bol)) ?#))
20092 (defun org-in-indented-comment-line ()
20093 "Is point in a line starting with `#' after some white space?"
20094 (save-excursion
20095 (save-match-data
20096 (goto-char (point-at-bol))
20097 (looking-at "[ \t]*#"))))
20099 (defun org-in-verbatim-emphasis ()
20100 (save-match-data
20101 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20103 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20104 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20105 (if (and marker (marker-buffer marker)
20106 (buffer-live-p (marker-buffer marker)))
20107 (progn
20108 (org-pop-to-buffer-same-window (marker-buffer marker))
20109 (if (or (> marker (point-max)) (< marker (point-min)))
20110 (widen))
20111 (goto-char marker)
20112 (org-show-context 'org-goto))
20113 (if bookmark
20114 (bookmark-jump bookmark)
20115 (error "Cannot find location"))))
20117 (defun org-quote-csv-field (s)
20118 "Quote field for inclusion in CSV material."
20119 (if (string-match "[\",]" s)
20120 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20123 (defun org-force-self-insert (N)
20124 "Needed to enforce self-insert under remapping."
20125 (interactive "p")
20126 (self-insert-command N))
20128 (defun org-string-width (s)
20129 "Compute width of string, ignoring invisible characters.
20130 This ignores character with invisibility property `org-link', and also
20131 characters with property `org-cwidth', because these will become invisible
20132 upon the next fontification round."
20133 (let (b l)
20134 (when (or (eq t buffer-invisibility-spec)
20135 (assq 'org-link buffer-invisibility-spec))
20136 (while (setq b (text-property-any 0 (length s)
20137 'invisible 'org-link s))
20138 (setq s (concat (substring s 0 b)
20139 (substring s (or (next-single-property-change
20140 b 'invisible s) (length s)))))))
20141 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20142 (setq s (concat (substring s 0 b)
20143 (substring s (or (next-single-property-change
20144 b 'org-cwidth s) (length s))))))
20145 (setq l (string-width s) b -1)
20146 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20147 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20150 (defun org-shorten-string (s maxlength)
20151 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20152 If the string is shorter or has length MAXLENGTH, just return the
20153 original string. If it is longer, the functions finds a space in the
20154 string, breaks this string off at that locations and adds three dots
20155 as ellipsis. Including the ellipsis, the string will not be longer
20156 than MAXLENGTH. If finding a good breaking point in the string does
20157 not work, the string is just chopped off in the middle of a word
20158 if necessary."
20159 (if (<= (length s) maxlength)
20161 (let* ((n (max (- maxlength 4) 1))
20162 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20163 (if (string-match re s)
20164 (concat (match-string 1 s) "...")
20165 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20167 (defun org-get-indentation (&optional line)
20168 "Get the indentation of the current line, interpreting tabs.
20169 When LINE is given, assume it represents a line and compute its indentation."
20170 (if line
20171 (if (string-match "^ *" (org-remove-tabs line))
20172 (match-end 0))
20173 (save-excursion
20174 (beginning-of-line 1)
20175 (skip-chars-forward " \t")
20176 (current-column))))
20178 (defun org-get-string-indentation (s)
20179 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20180 (let ((n -1) (i 0) (w tab-width) c)
20181 (catch 'exit
20182 (while (< (setq n (1+ n)) (length s))
20183 (setq c (aref s n))
20184 (cond ((= c ?\ ) (setq i (1+ i)))
20185 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20186 (t (throw 'exit t)))))
20189 (defun org-remove-tabs (s &optional width)
20190 "Replace tabulators in S with spaces.
20191 Assumes that s is a single line, starting in column 0."
20192 (setq width (or width tab-width))
20193 (while (string-match "\t" s)
20194 (setq s (replace-match
20195 (make-string
20196 (- (* width (/ (+ (match-beginning 0) width) width))
20197 (match-beginning 0)) ?\ )
20198 t t s)))
20201 (defun org-fix-indentation (line ind)
20202 "Fix indentation in LINE.
20203 IND is a cons cell with target and minimum indentation.
20204 If the current indentation in LINE is smaller than the minimum,
20205 leave it alone. If it is larger than ind, set it to the target."
20206 (let* ((l (org-remove-tabs line))
20207 (i (org-get-indentation l))
20208 (i1 (car ind)) (i2 (cdr ind)))
20209 (if (>= i i2) (setq l (substring line i2)))
20210 (if (> i1 0)
20211 (concat (make-string i1 ?\ ) l)
20212 l)))
20214 (defun org-remove-indentation (code &optional n)
20215 "Remove the maximum common indentation from the lines in CODE.
20216 N may optionally be the number of spaces to remove."
20217 (with-temp-buffer
20218 (insert code)
20219 (org-do-remove-indentation n)
20220 (buffer-string)))
20222 (defun org-do-remove-indentation (&optional n)
20223 "Remove the maximum common indentation from the buffer."
20224 (untabify (point-min) (point-max))
20225 (let ((min 10000) re)
20226 (if n
20227 (setq min n)
20228 (goto-char (point-min))
20229 (while (re-search-forward "^ *[^ \n]" nil t)
20230 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20231 (unless (or (= min 0) (= min 10000))
20232 (setq re (format "^ \\{%d\\}" min))
20233 (goto-char (point-min))
20234 (while (re-search-forward re nil t)
20235 (replace-match "")
20236 (end-of-line 1))
20237 min)))
20239 (defun org-fill-template (template alist)
20240 "Find each %key of ALIST in TEMPLATE and replace it."
20241 (let ((case-fold-search nil)
20242 entry key value)
20243 (setq alist (sort (copy-sequence alist)
20244 (lambda (a b) (< (length (car a)) (length (car b))))))
20245 (while (setq entry (pop alist))
20246 (setq template
20247 (replace-regexp-in-string
20248 (concat "%" (regexp-quote (car entry)))
20249 (or (cdr entry) "") template t t)))
20250 template))
20252 (defun org-base-buffer (buffer)
20253 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20254 (if (not buffer)
20255 buffer
20256 (or (buffer-base-buffer buffer)
20257 buffer)))
20259 (defun org-trim (s)
20260 "Remove whitespace at beginning and end of string."
20261 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20262 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20265 (defun org-wrap (string &optional width lines)
20266 "Wrap string to either a number of lines, or a width in characters.
20267 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20268 that costs. If there is a word longer than WIDTH, the text is actually
20269 wrapped to the length of that word.
20270 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20271 many lines, whatever width that takes.
20272 The return value is a list of lines, without newlines at the end."
20273 (let* ((words (org-split-string string "[ \t\n]+"))
20274 (maxword (apply 'max (mapcar 'org-string-width words)))
20275 w ll)
20276 (cond (width
20277 (org-do-wrap words (max maxword width)))
20278 (lines
20279 (setq w maxword)
20280 (setq ll (org-do-wrap words maxword))
20281 (if (<= (length ll) lines)
20283 (setq ll words)
20284 (while (> (length ll) lines)
20285 (setq w (1+ w))
20286 (setq ll (org-do-wrap words w)))
20287 ll))
20288 (t (error "Cannot wrap this")))))
20290 (defun org-do-wrap (words width)
20291 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20292 (let (lines line)
20293 (while words
20294 (setq line (pop words))
20295 (while (and words (< (+ (length line) (length (car words))) width))
20296 (setq line (concat line " " (pop words))))
20297 (setq lines (push line lines)))
20298 (nreverse lines)))
20300 (defun org-split-string (string &optional separators)
20301 "Splits STRING into substrings at SEPARATORS.
20302 No empty strings are returned if there are matches at the beginning
20303 and end of string."
20304 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20305 (start 0)
20306 notfirst
20307 (list nil))
20308 (while (and (string-match rexp string
20309 (if (and notfirst
20310 (= start (match-beginning 0))
20311 (< start (length string)))
20312 (1+ start) start))
20313 (< (match-beginning 0) (length string)))
20314 (setq notfirst t)
20315 (or (eq (match-beginning 0) 0)
20316 (and (eq (match-beginning 0) (match-end 0))
20317 (eq (match-beginning 0) start))
20318 (setq list
20319 (cons (substring string start (match-beginning 0))
20320 list)))
20321 (setq start (match-end 0)))
20322 (or (eq start (length string))
20323 (setq list
20324 (cons (substring string start)
20325 list)))
20326 (nreverse list)))
20328 (defun org-quote-vert (s)
20329 "Replace \"|\" with \"\\vert\"."
20330 (while (string-match "|" s)
20331 (setq s (replace-match "\\vert" t t s)))
20334 (defun org-uuidgen-p (s)
20335 "Is S an ID created by UUIDGEN?"
20336 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20338 (defun org-in-src-block-p nil
20339 "Whether point is in a code source block."
20340 (let (ov)
20341 (when (setq ov (overlays-at (point)))
20342 (memq 'org-block-background
20343 (overlay-properties
20344 (car ov))))))
20346 (defun org-context ()
20347 "Return a list of contexts of the current cursor position.
20348 If several contexts apply, all are returned.
20349 Each context entry is a list with a symbol naming the context, and
20350 two positions indicating start and end of the context. Possible
20351 contexts are:
20353 :headline anywhere in a headline
20354 :headline-stars on the leading stars in a headline
20355 :todo-keyword on a TODO keyword (including DONE) in a headline
20356 :tags on the TAGS in a headline
20357 :priority on the priority cookie in a headline
20358 :item on the first line of a plain list item
20359 :item-bullet on the bullet/number of a plain list item
20360 :checkbox on the checkbox in a plain list item
20361 :table in an org-mode table
20362 :table-special on a special filed in a table
20363 :table-table in a table.el table
20364 :clocktable in a clocktable
20365 :src-block in a source block
20366 :link on a hyperlink
20367 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20368 :target on a <<target>>
20369 :radio-target on a <<<radio-target>>>
20370 :latex-fragment on a LaTeX fragment
20371 :latex-preview on a LaTeX fragment with overlaid preview image
20373 This function expects the position to be visible because it uses font-lock
20374 faces as a help to recognize the following contexts: :table-special, :link,
20375 and :keyword."
20376 (let* ((f (get-text-property (point) 'face))
20377 (faces (if (listp f) f (list f)))
20378 (case-fold-search t)
20379 (p (point)) clist o)
20380 ;; First the large context
20381 (cond
20382 ((org-at-heading-p t)
20383 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20384 (when (progn
20385 (beginning-of-line 1)
20386 (looking-at org-todo-line-tags-regexp))
20387 (push (org-point-in-group p 1 :headline-stars) clist)
20388 (push (org-point-in-group p 2 :todo-keyword) clist)
20389 (push (org-point-in-group p 4 :tags) clist))
20390 (goto-char p)
20391 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20392 (if (looking-at "\\[#[A-Z0-9]\\]")
20393 (push (org-point-in-group p 0 :priority) clist)))
20395 ((org-at-item-p)
20396 (push (org-point-in-group p 2 :item-bullet) clist)
20397 (push (list :item (point-at-bol)
20398 (save-excursion (org-end-of-item) (point)))
20399 clist)
20400 (and (org-at-item-checkbox-p)
20401 (push (org-point-in-group p 0 :checkbox) clist)))
20403 ((org-at-table-p)
20404 (push (list :table (org-table-begin) (org-table-end)) clist)
20405 (if (memq 'org-formula faces)
20406 (push (list :table-special
20407 (previous-single-property-change p 'face)
20408 (next-single-property-change p 'face)) clist)))
20409 ((org-at-table-p 'any)
20410 (push (list :table-table) clist)))
20411 (goto-char p)
20413 (let ((case-fold-search t))
20414 ;; New the "medium" contexts: clocktables, source blocks
20415 (cond ((org-in-clocktable-p)
20416 (push (list :clocktable
20417 (and (or (looking-at "#\\+BEGIN: clocktable")
20418 (search-backward "#+BEGIN: clocktable" nil t))
20419 (match-beginning 0))
20420 (and (re-search-forward "#\\+END:?" nil t)
20421 (match-end 0))) clist))
20422 ((org-in-src-block-p)
20423 (push (list :src-block
20424 (and (or (looking-at "#\\+BEGIN_SRC")
20425 (search-backward "#+BEGIN_SRC" nil t))
20426 (match-beginning 0))
20427 (and (search-forward "#+END_SRC" nil t)
20428 (match-beginning 0))) clist))))
20429 (goto-char p)
20431 ;; Now the small context
20432 (cond
20433 ((org-at-timestamp-p)
20434 (push (org-point-in-group p 0 :timestamp) clist))
20435 ((memq 'org-link faces)
20436 (push (list :link
20437 (previous-single-property-change p 'face)
20438 (next-single-property-change p 'face)) clist))
20439 ((memq 'org-special-keyword faces)
20440 (push (list :keyword
20441 (previous-single-property-change p 'face)
20442 (next-single-property-change p 'face)) clist))
20443 ((org-at-target-p)
20444 (push (org-point-in-group p 0 :target) clist)
20445 (goto-char (1- (match-beginning 0)))
20446 (if (looking-at org-radio-target-regexp)
20447 (push (org-point-in-group p 0 :radio-target) clist))
20448 (goto-char p))
20449 ((setq o (car (delq nil
20450 (mapcar
20451 (lambda (x)
20452 (if (memq x org-latex-fragment-image-overlays) x))
20453 (overlays-at (point))))))
20454 (push (list :latex-fragment
20455 (overlay-start o) (overlay-end o)) clist)
20456 (push (list :latex-preview
20457 (overlay-start o) (overlay-end o)) clist))
20458 ((org-inside-LaTeX-fragment-p)
20459 ;; FIXME: positions wrong.
20460 (push (list :latex-fragment (point) (point)) clist)))
20462 (setq clist (nreverse (delq nil clist)))
20463 clist))
20465 ;; FIXME: Compare with at-regexp-p Do we need both?
20466 (defun org-in-regexp (re &optional nlines visually)
20467 "Check if point is inside a match of regexp.
20468 Normally only the current line is checked, but you can include NLINES extra
20469 lines both before and after point into the search.
20470 If VISUALLY is set, require that the cursor is not after the match but
20471 really on, so that the block visually is on the match."
20472 (catch 'exit
20473 (let ((pos (point))
20474 (eol (point-at-eol (+ 1 (or nlines 0))))
20475 (inc (if visually 1 0)))
20476 (save-excursion
20477 (beginning-of-line (- 1 (or nlines 0)))
20478 (while (re-search-forward re eol t)
20479 (if (and (<= (match-beginning 0) pos)
20480 (>= (+ inc (match-end 0)) pos))
20481 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20483 (defun org-at-regexp-p (regexp)
20484 "Is point inside a match of REGEXP in the current line?"
20485 (catch 'exit
20486 (save-excursion
20487 (let ((pos (point)) (end (point-at-eol)))
20488 (beginning-of-line 1)
20489 (while (re-search-forward regexp end t)
20490 (if (and (<= (match-beginning 0) pos)
20491 (>= (match-end 0) pos))
20492 (throw 'exit t)))
20493 nil))))
20495 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20496 "Non-nil when point is between matches of START-RE and END-RE.
20498 Also return a non-nil value when point is on one of the matches.
20500 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20501 buffer positions. Default values are the positions of headlines
20502 surrounding the point.
20504 The functions returns a cons cell whose car (resp. cdr) is the
20505 position before START-RE (resp. after END-RE)."
20506 (save-match-data
20507 (let ((pos (point))
20508 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20509 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20510 beg end)
20511 (save-excursion
20512 ;; Point is on a block when on START-RE or if START-RE can be
20513 ;; found before it...
20514 (and (or (org-at-regexp-p start-re)
20515 (re-search-backward start-re limit-up t))
20516 (setq beg (match-beginning 0))
20517 ;; ... and END-RE after it...
20518 (goto-char (match-end 0))
20519 (re-search-forward end-re limit-down t)
20520 (> (setq end (match-end 0)) pos)
20521 ;; ... without another START-RE in-between.
20522 (goto-char (match-beginning 0))
20523 (not (re-search-backward start-re (1+ beg) t))
20524 ;; Return value.
20525 (cons beg end))))))
20527 (defun org-in-block-p (names)
20528 "Non-nil when point belongs to a block whose name belongs to NAMES.
20530 NAMES is a list of strings containing names of blocks.
20532 Return first block name matched, or nil. Beware that in case of
20533 nested blocks, the returned name may not belong to the closest
20534 block from point."
20535 (save-match-data
20536 (catch 'exit
20537 (let ((case-fold-search t)
20538 (lim-up (save-excursion (outline-previous-heading)))
20539 (lim-down (save-excursion (outline-next-heading))))
20540 (mapc (lambda (name)
20541 (let ((n (regexp-quote name)))
20542 (when (org-between-regexps-p
20543 (concat "^[ \t]*#\\+begin_" n)
20544 (concat "^[ \t]*#\\+end_" n)
20545 lim-up lim-down)
20546 (throw 'exit n))))
20547 names))
20548 nil)))
20550 (defun org-occur-in-agenda-files (regexp &optional nlines)
20551 "Call `multi-occur' with buffers for all agenda files."
20552 (interactive "sOrg-files matching: \np")
20553 (let* ((files (org-agenda-files))
20554 (tnames (mapcar 'file-truename files))
20555 (extra org-agenda-text-search-extra-files)
20557 (when (eq (car extra) 'agenda-archives)
20558 (setq extra (cdr extra))
20559 (setq files (org-add-archive-files files)))
20560 (while (setq f (pop extra))
20561 (unless (member (file-truename f) tnames)
20562 (add-to-list 'files f 'append)
20563 (add-to-list 'tnames (file-truename f) 'append)))
20564 (multi-occur
20565 (mapcar (lambda (x)
20566 (with-current-buffer
20567 (or (get-file-buffer x) (find-file-noselect x))
20568 (widen)
20569 (current-buffer)))
20570 files)
20571 regexp)))
20573 (if (boundp 'occur-mode-find-occurrence-hook)
20574 ;; Emacs 23
20575 (add-hook 'occur-mode-find-occurrence-hook
20576 (lambda ()
20577 (when (derived-mode-p 'org-mode)
20578 (org-reveal))))
20579 ;; Emacs 22
20580 (defadvice occur-mode-goto-occurrence
20581 (after org-occur-reveal activate)
20582 (and (derived-mode-p 'org-mode) (org-reveal)))
20583 (defadvice occur-mode-goto-occurrence-other-window
20584 (after org-occur-reveal activate)
20585 (and (derived-mode-p 'org-mode) (org-reveal)))
20586 (defadvice occur-mode-display-occurrence
20587 (after org-occur-reveal activate)
20588 (when (derived-mode-p 'org-mode)
20589 (let ((pos (occur-mode-find-occurrence)))
20590 (with-current-buffer (marker-buffer pos)
20591 (save-excursion
20592 (goto-char pos)
20593 (org-reveal)))))))
20595 (defun org-occur-link-in-agenda-files ()
20596 "Create a link and search for it in the agendas.
20597 The link is not stored in `org-stored-links', it is just created
20598 for the search purpose."
20599 (interactive)
20600 (let ((link (condition-case nil
20601 (org-store-link nil)
20602 (error "Unable to create a link to here"))))
20603 (org-occur-in-agenda-files (regexp-quote link))))
20605 (defun org-uniquify (list)
20606 "Remove duplicate elements from LIST."
20607 (let (res)
20608 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20609 res))
20611 (defun org-delete-all (elts list)
20612 "Remove all elements in ELTS from LIST."
20613 (while elts
20614 (setq list (delete (pop elts) list)))
20615 list)
20617 (defun org-count (cl-item cl-seq)
20618 "Count the number of occurrences of ITEM in SEQ.
20619 Taken from `count' in cl-seq.el with all keyword arguments removed."
20620 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20621 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20622 (while (< cl-start cl-end)
20623 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20624 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20625 (setq cl-start (1+ cl-start)))
20626 cl-count))
20628 (defun org-remove-if (predicate seq)
20629 "Remove everything from SEQ that fulfills PREDICATE."
20630 (let (res e)
20631 (while seq
20632 (setq e (pop seq))
20633 (if (not (funcall predicate e)) (push e res)))
20634 (nreverse res)))
20636 (defun org-remove-if-not (predicate seq)
20637 "Remove everything from SEQ that does not fulfill PREDICATE."
20638 (let (res e)
20639 (while seq
20640 (setq e (pop seq))
20641 (if (funcall predicate e) (push e res)))
20642 (nreverse res)))
20644 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20645 "Reduce two-argument FUNCTION across SEQ.
20646 Taken from `reduce' in cl-seq.el with all keyword arguments but
20647 \":initial-value\" removed."
20648 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20649 (cadr (memq :initial-value cl-keys)))
20650 (cl-seq (pop cl-seq))
20651 (t (funcall cl-func)))))
20652 (while cl-seq
20653 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20654 cl-accum))
20656 (defun org-back-over-empty-lines ()
20657 "Move backwards over whitespace, to the beginning of the first empty line.
20658 Returns the number of empty lines passed."
20659 (let ((pos (point)))
20660 (if (cdr (assoc 'heading org-blank-before-new-entry))
20661 (skip-chars-backward " \t\n\r")
20662 (unless (eobp)
20663 (forward-line -1)))
20664 (beginning-of-line 2)
20665 (goto-char (min (point) pos))
20666 (count-lines (point) pos)))
20668 (defun org-skip-whitespace ()
20669 (skip-chars-forward " \t\n\r"))
20671 (defun org-point-in-group (point group &optional context)
20672 "Check if POINT is in match-group GROUP.
20673 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20674 match. If the match group does not exist or point is not inside it,
20675 return nil."
20676 (and (match-beginning group)
20677 (>= point (match-beginning group))
20678 (<= point (match-end group))
20679 (if context
20680 (list context (match-beginning group) (match-end group))
20681 t)))
20683 (defun org-switch-to-buffer-other-window (&rest args)
20684 "Switch to buffer in a second window on the current frame.
20685 In particular, do not allow pop-up frames.
20686 Returns the newly created buffer."
20687 (let (pop-up-frames special-display-buffer-names special-display-regexps
20688 special-display-function)
20689 (apply 'switch-to-buffer-other-window args)))
20691 (defun org-combine-plists (&rest plists)
20692 "Create a single property list from all plists in PLISTS.
20693 The process starts by copying the first list, and then setting properties
20694 from the other lists. Settings in the last list are the most significant
20695 ones and overrule settings in the other lists."
20696 (let ((rtn (copy-sequence (pop plists)))
20697 p v ls)
20698 (while plists
20699 (setq ls (pop plists))
20700 (while ls
20701 (setq p (pop ls) v (pop ls))
20702 (setq rtn (plist-put rtn p v))))
20703 rtn))
20705 (defun org-replace-escapes (string table)
20706 "Replace %-escapes in STRING with values in TABLE.
20707 TABLE is an association list with keys like \"%a\" and string values.
20708 The sequences in STRING may contain normal field width and padding information,
20709 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20710 so values can contain further %-escapes if they are define later in TABLE."
20711 (let ((tbl (copy-alist table))
20712 (case-fold-search nil)
20713 (pchg 0)
20714 e re rpl)
20715 (while (setq e (pop tbl))
20716 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20717 (when (and (cdr e) (string-match re (cdr e)))
20718 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20719 (safe "SREF"))
20720 (add-text-properties 0 3 (list 'sref sref) safe)
20721 (setcdr e (replace-match safe t t (cdr e)))))
20722 (while (string-match re string)
20723 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20724 (cdr e)))
20725 (setq string (replace-match rpl t t string))))
20726 (while (setq pchg (next-property-change pchg string))
20727 (let ((sref (get-text-property pchg 'sref string)))
20728 (when (and sref (string-match "SREF" string pchg))
20729 (setq string (replace-match sref t t string)))))
20730 string))
20732 (defun org-sublist (list start end)
20733 "Return a section of LIST, from START to END.
20734 Counting starts at 1."
20735 (let (rtn (c start))
20736 (setq list (nthcdr (1- start) list))
20737 (while (and list (<= c end))
20738 (push (pop list) rtn)
20739 (setq c (1+ c)))
20740 (nreverse rtn)))
20742 (defun org-find-base-buffer-visiting (file)
20743 "Like `find-buffer-visiting' but always return the base buffer and
20744 not an indirect buffer."
20745 (let ((buf (or (get-file-buffer file)
20746 (find-buffer-visiting file))))
20747 (if buf
20748 (or (buffer-base-buffer buf) buf)
20749 nil)))
20751 (defun org-image-file-name-regexp (&optional extensions)
20752 "Return regexp matching the file names of images.
20753 If EXTENSIONS is given, only match these."
20754 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20755 (image-file-name-regexp)
20756 (let ((image-file-name-extensions
20757 (or extensions
20758 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20759 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20760 (concat "\\."
20761 (regexp-opt (nconc (mapcar 'upcase
20762 image-file-name-extensions)
20763 image-file-name-extensions)
20765 "\\'"))))
20767 (defun org-file-image-p (file &optional extensions)
20768 "Return non-nil if FILE is an image."
20769 (save-match-data
20770 (string-match (org-image-file-name-regexp extensions) file)))
20772 (defun org-get-cursor-date ()
20773 "Return the date at cursor in as a time.
20774 This works in the calendar and in the agenda, anywhere else it just
20775 returns the current time."
20776 (let (date day defd)
20777 (cond
20778 ((eq major-mode 'calendar-mode)
20779 (setq date (calendar-cursor-to-date)
20780 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20781 ((eq major-mode 'org-agenda-mode)
20782 (setq day (get-text-property (point) 'day))
20783 (if day
20784 (setq date (calendar-gregorian-from-absolute day)
20785 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20786 (nth 2 date))))))
20787 (or defd (current-time))))
20789 (defvar org-agenda-action-marker (make-marker)
20790 "Marker pointing to the entry for the next agenda action.")
20792 (defun org-mark-entry-for-agenda-action ()
20793 "Mark the current entry as target of an agenda action.
20794 Agenda actions are actions executed from the agenda with the key `k',
20795 which make use of the date at the cursor."
20796 (interactive)
20797 (move-marker org-agenda-action-marker
20798 (save-excursion (org-back-to-heading t) (point))
20799 (current-buffer))
20800 (message
20801 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20803 (defun org-mark-subtree (&optional up)
20804 "Mark the current subtree.
20805 This puts point at the start of the current subtree, and mark at
20806 the end. If a numeric prefix UP is given, move up into the
20807 hierarchy of headlines by UP levels before marking the subtree."
20808 (interactive "P")
20809 (org-with-limited-levels
20810 (cond ((org-at-heading-p) (beginning-of-line))
20811 ((org-before-first-heading-p) (error "Not in a subtree"))
20812 (t (outline-previous-visible-heading 1))))
20813 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20814 (if (org-called-interactively-p 'any)
20815 (call-interactively 'org-mark-element)
20816 (org-mark-element)))
20818 ;;; Indentation
20820 (defun org-indent-line ()
20821 "Indent line depending on context."
20822 (interactive)
20823 (let* ((pos (point))
20824 (itemp (org-at-item-p))
20825 (case-fold-search t)
20826 (org-drawer-regexp (or org-drawer-regexp "\000"))
20827 (inline-task-p (and (featurep 'org-inlinetask)
20828 (org-inlinetask-in-task-p)))
20829 (inline-re (and inline-task-p
20830 (org-inlinetask-outline-regexp)))
20831 column)
20832 (if (and orgstruct-is-++ (eq pos (point)))
20833 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20834 (indent-according-to-mode))
20835 (beginning-of-line 1)
20836 (cond
20837 ;; Headings
20838 ((looking-at org-outline-regexp) (setq column 0))
20839 ;; Included files
20840 ((looking-at "#\\+include:") (setq column 0))
20841 ;; Footnote definition
20842 ((looking-at org-footnote-definition-re) (setq column 0))
20843 ;; Literal examples
20844 ((looking-at "[ \t]*:\\( \\|$\\)")
20845 (setq column (org-get-indentation))) ; do nothing
20846 ;; Lists
20847 ((ignore-errors (goto-char (org-in-item-p)))
20848 (setq column (if itemp
20849 (org-get-indentation)
20850 (org-list-item-body-column (point))))
20851 (goto-char pos))
20852 ;; Drawers
20853 ((and (looking-at "[ \t]*:END:")
20854 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20855 (save-excursion
20856 (goto-char (1- (match-beginning 1)))
20857 (setq column (current-column))))
20858 ;; Special blocks
20859 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20860 (save-excursion
20861 (re-search-backward
20862 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20863 (setq column (org-get-indentation (match-string 0))))
20864 ((and (not (looking-at "[ \t]*#\\+begin_"))
20865 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20866 (save-excursion
20867 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20868 (setq column
20869 (cond ((equal (downcase (match-string 1)) "src")
20870 ;; src blocks: let `org-edit-src-exit' handle them
20871 (org-get-indentation))
20872 ((equal (downcase (match-string 1)) "example")
20873 (max (org-get-indentation)
20874 (org-get-indentation (match-string 0))))
20876 (org-get-indentation (match-string 0))))))
20877 ;; This line has nothing special, look at the previous relevant
20878 ;; line to compute indentation
20880 (beginning-of-line 0)
20881 (while (and (not (bobp))
20882 (not (looking-at org-drawer-regexp))
20883 ;; When point started in an inline task, do not move
20884 ;; above task starting line.
20885 (not (and inline-task-p (looking-at inline-re)))
20886 ;; Skip drawers, blocks, empty lines, verbatim,
20887 ;; comments, tables, footnotes definitions, lists,
20888 ;; inline tasks.
20889 (or (and (looking-at "[ \t]*:END:")
20890 (re-search-backward org-drawer-regexp nil t))
20891 (and (looking-at "[ \t]*#\\+end_")
20892 (re-search-backward "[ \t]*#\\+begin_"nil t))
20893 (looking-at "[ \t]*[\n:#|]")
20894 (looking-at org-footnote-definition-re)
20895 (and (ignore-errors (goto-char (org-in-item-p)))
20896 (goto-char
20897 (org-list-get-top-point (org-list-struct))))
20898 (and (not inline-task-p)
20899 (featurep 'org-inlinetask)
20900 (org-inlinetask-in-task-p)
20901 (or (org-inlinetask-goto-beginning) t))))
20902 (beginning-of-line 0))
20903 (cond
20904 ;; There was an heading above.
20905 ((looking-at "\\*+[ \t]+")
20906 (if (not org-adapt-indentation)
20907 (setq column 0)
20908 (goto-char (match-end 0))
20909 (setq column (current-column))))
20910 ;; A drawer had started and is unfinished
20911 ((looking-at org-drawer-regexp)
20912 (goto-char (1- (match-beginning 1)))
20913 (setq column (current-column)))
20914 ;; Else, nothing noticeable found: get indentation and go on.
20915 (t (setq column (org-get-indentation))))))
20916 ;; Now apply indentation and move cursor accordingly
20917 (goto-char pos)
20918 (if (<= (current-column) (current-indentation))
20919 (org-indent-line-to column)
20920 (save-excursion (org-indent-line-to column)))
20921 ;; Special polishing for properties, see `org-property-format'
20922 (setq column (current-column))
20923 (beginning-of-line 1)
20924 (if (looking-at
20925 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20926 (replace-match (concat (match-string 1)
20927 (format org-property-format
20928 (match-string 2) (match-string 3)))
20929 t t))
20930 (org-move-to-column column))))
20932 (defun org-indent-drawer ()
20933 "Indent the drawer at point."
20934 (interactive)
20935 (let ((p (point))
20936 (e (and (save-excursion (re-search-forward ":END:" 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 "Drawer at point indented"))
20952 (defun org-indent-block ()
20953 "Indent the block at point."
20954 (interactive)
20955 (let ((p (point))
20956 (case-fold-search t)
20957 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20958 (match-end 0)))
20959 (folded
20960 (save-excursion
20961 (end-of-line)
20962 (when (overlays-at (point))
20963 (member 'invisible (overlay-properties
20964 (car (overlays-at (point)))))))))
20965 (when folded (org-cycle))
20966 (indent-for-tab-command)
20967 (while (and (move-beginning-of-line 2) (< (point) e))
20968 (indent-for-tab-command))
20969 (goto-char p)
20970 (when folded (org-cycle)))
20971 (message "Block at point indented"))
20973 (defun org-indent-region (start end)
20974 "Indent region."
20975 (interactive "r")
20976 (save-excursion
20977 (let ((line-end (org-current-line end)))
20978 (goto-char start)
20979 (while (< (org-current-line) line-end)
20980 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20981 (t (call-interactively 'org-indent-line)))
20982 (move-beginning-of-line 2)))))
20985 ;;; Filling
20987 ;; We use our own fill-paragraph and auto-fill functions.
20989 ;; `org-fill-paragraph' relies on adaptive filling and context
20990 ;; checking. Appropriate `fill-prefix' is computed with
20991 ;; `org-adaptive-fill-function'.
20993 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20994 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20995 ;; `org-adaptive-fill-function' value. Internally,
20996 ;; `org-comment-line-break-function' breaks the line.
20998 ;; `org-setup-filling' installs filling and auto-filling related
20999 ;; variables during `org-mode' initialization.
21001 (defun org-setup-filling ()
21002 (interactive)
21003 ;; Prevent auto-fill from inserting unwanted new items.
21004 (when (boundp 'fill-nobreak-predicate)
21005 (org-set-local
21006 'fill-nobreak-predicate
21007 (org-uniquify
21008 (append fill-nobreak-predicate
21009 '(org-fill-paragraph-separate-nobreak-p
21010 org-fill-line-break-nobreak-p)))))
21011 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21012 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21013 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21014 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21016 (defvar org-element-paragraph-separate) ; org-element.el
21017 (defun org-fill-paragraph-separate-nobreak-p ()
21018 "Non-nil when a line break at point would insert a new item."
21019 (looking-at (substring org-element-paragraph-separate 1)))
21021 (defun org-fill-line-break-nobreak-p ()
21022 "Non-nil when a line break at point would create an Org line break."
21023 (save-excursion
21024 (skip-chars-backward "[ \t]")
21025 (skip-chars-backward "\\\\")
21026 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21028 (declare-function message-in-body-p "message" ())
21029 (defvar org-element--affiliated-re) ; From org-element.el
21030 (defun org-adaptive-fill-function ()
21031 "Compute a fill prefix for the current line.
21032 Return fill prefix, as a string, or nil if current line isn't
21033 meant to be filled."
21034 (org-with-wide-buffer
21035 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21036 ;; FIXME: This is really the job of orgstruct++-mode
21037 (let* ((p (line-beginning-position))
21038 (element (save-excursion (beginning-of-line)
21039 (org-element-at-point)))
21040 (type (org-element-type element))
21041 (post-affiliated
21042 (save-excursion
21043 (goto-char (org-element-property :begin element))
21044 (while (looking-at org-element--affiliated-re) (forward-line))
21045 (point))))
21046 (unless (< p post-affiliated)
21047 (case type
21048 (comment (looking-at "[ \t]*# ?") (match-string 0))
21049 (footnote-definition "")
21050 ((item plain-list)
21051 (make-string (org-list-item-body-column post-affiliated) ? ))
21052 (paragraph
21053 ;; Fill prefix is usually the same as the current line,
21054 ;; except if the paragraph is at the beginning of an item.
21055 (let ((parent (org-element-property :parent element)))
21056 (cond ((eq (org-element-type parent) 'item)
21057 (make-string (org-list-item-body-column
21058 (org-element-property :begin parent))
21059 ? ))
21060 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21061 (match-string 0))
21062 (t ""))))
21063 (comment-block
21064 ;; Only fill contents if P is within block boundaries.
21065 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21066 (forward-line)
21067 (point)))
21068 (cend (save-excursion
21069 (goto-char (org-element-property :end element))
21070 (skip-chars-backward " \r\t\n")
21071 (line-beginning-position))))
21072 (when (and (>= p cbeg) (< p cend))
21073 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21074 (match-string 0)
21075 ""))))))))))
21077 (declare-function message-goto-body "message" ())
21078 (defvar message-cite-prefix-regexp) ; From message.el
21079 (defvar org-element-all-objects) ; From org-element.el
21080 (defun org-fill-paragraph (&optional justify)
21081 "Fill element at point, when applicable.
21083 This function only applies to comment blocks, comments, example
21084 blocks and paragraphs. Also, as a special case, re-align table
21085 when point is at one.
21087 If JUSTIFY is non-nil (interactively, with prefix argument),
21088 justify as well. If `sentence-end-double-space' is non-nil, then
21089 period followed by one space does not end a sentence, so don't
21090 break a line there. The variable `fill-column' controls the
21091 width for filling.
21093 For convenience, when point is at a plain list, an item or
21094 a footnote definition, try to fill the first paragraph within."
21095 ;; Falls back on message-fill-paragraph when necessary
21096 (interactive)
21097 (if (and (derived-mode-p 'message-mode)
21098 (or (not (message-in-body-p))
21099 (save-excursion (move-beginning-of-line 1)
21100 (looking-at message-cite-prefix-regexp))))
21101 (let ((fill-paragraph-function
21102 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21103 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21104 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21105 (paragraph-separate
21106 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21107 (fill-paragraph nil))
21108 (save-excursion
21109 ;; Move to end of line in order to get the first paragraph
21110 ;; within a plain list or a footnote definition.
21111 (end-of-line)
21112 (let ((element (org-element-at-point)))
21113 ;; First check if point is in a blank line at the beginning of
21114 ;; the buffer. In that case, ignore filling.
21115 (if (< (point) (org-element-property :begin element)) t
21116 (case (org-element-type element)
21117 ;; Align Org tables, leave table.el tables as-is.
21118 (table-row (org-table-align) t)
21119 (table
21120 (when (eq (org-element-property :type element) 'org)
21121 (org-table-align))
21123 (paragraph
21124 ;; Paragraphs may contain `line-break' type objects.
21125 (let ((beg (max (point-min)
21126 (org-element-property :contents-begin element)))
21127 (end (min (point-max)
21128 (org-element-property :contents-end element))))
21129 ;; Do nothing if point is at an affiliated keyword.
21130 (if (< (point) beg) t
21131 (when (derived-mode-p 'message-mode)
21132 ;; In `message-mode', do not fill following
21133 ;; citation in current paragraph nor text before
21134 ;; message body.
21135 (let ((body-start (save-excursion (message-goto-body))))
21136 (when body-start (setq beg (max body-start beg))))
21137 (when (save-excursion
21138 (re-search-forward
21139 (concat "^" message-cite-prefix-regexp) end t))
21140 (setq end (match-beginning 0))))
21141 ;; Fill paragraph, taking line breaks into
21142 ;; consideration. For that, slice the paragraph
21143 ;; using line breaks as separators, and fill the
21144 ;; parts in reverse order to avoid messing with
21145 ;; markers.
21146 (save-excursion
21147 (goto-char end)
21148 (mapc
21149 (lambda (pos)
21150 (fill-region-as-paragraph pos (point) justify)
21151 (goto-char pos))
21152 ;; Find the list of ending positions for line
21153 ;; breaks in the current paragraph. Add paragraph
21154 ;; beginning to include first slice.
21155 (nreverse
21156 (cons
21158 (org-element-map
21159 (org-element--parse-objects
21160 beg end nil org-element-all-objects)
21161 'line-break
21162 (lambda (lb) (org-element-property :end lb)))))))
21163 t)))
21164 ;; Contents of `comment-block' type elements should be
21165 ;; filled as plain text, but only if point is within block
21166 ;; markers.
21167 (comment-block
21168 (let* ((case-fold-search t)
21169 (beg (save-excursion
21170 (goto-char (org-element-property :begin element))
21171 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21172 (forward-line)
21173 (point)))
21174 (end (save-excursion
21175 (goto-char (org-element-property :end element))
21176 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21177 (line-beginning-position))))
21178 (when (and (>= (point) beg) (< (point) end))
21179 (fill-region-as-paragraph
21180 (save-excursion
21181 (end-of-line)
21182 (re-search-backward "^[ \t]*$" beg 'move)
21183 (line-beginning-position))
21184 (save-excursion
21185 (beginning-of-line)
21186 (re-search-forward "^[ \t]*$" end 'move)
21187 (line-beginning-position))
21188 justify)))
21190 ;; Fill comments.
21191 (comment (fill-comment-paragraph justify))
21192 ;; Ignore every other element.
21193 (otherwise t)))))))
21195 (defun org-auto-fill-function ()
21196 "Auto-fill function."
21197 ;; Check if auto-filling is meaningful.
21198 (let ((fc (current-fill-column)))
21199 (when (and fc (> (current-column) fc))
21200 (let ((fill-prefix (org-adaptive-fill-function)))
21201 (when fill-prefix (do-auto-fill))))))
21203 (defun org-comment-line-break-function (&optional soft)
21204 "Break line at point and indent, continuing comment if within one.
21205 The inserted newline is marked hard if variable
21206 `use-hard-newlines' is true, unless optional argument SOFT is
21207 non-nil."
21208 (if soft (insert-and-inherit ?\n) (newline 1))
21209 (save-excursion (forward-char -1) (delete-horizontal-space))
21210 (delete-horizontal-space)
21211 (indent-to-left-margin)
21212 (insert-before-markers-and-inherit fill-prefix))
21215 ;;; Comments
21217 ;; Org comments syntax is quite complex. It requires the entire line
21218 ;; to be just a comment. Also, even with the right syntax at the
21219 ;; beginning of line, some some elements (i.e. verse-block or
21220 ;; example-block) don't accept comments. Usual Emacs comment commands
21221 ;; cannot cope with those requirements. Therefore, Org replaces them.
21223 ;; Org still relies on `comment-dwim', but cannot trust
21224 ;; `comment-only-p'. So, `comment-region-function' and
21225 ;; `uncomment-region-function' both point
21226 ;; to`org-comment-or-uncomment-region'. Eventually,
21227 ;; `org-insert-comment' takes care of insertion of comments at the
21228 ;; beginning of line.
21230 ;; `org-setup-comments-handling' install comments related variables
21231 ;; during `org-mode' initialization.
21233 (defun org-setup-comments-handling ()
21234 (interactive)
21235 (org-set-local 'comment-use-syntax nil)
21236 (org-set-local 'comment-start "# ")
21237 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21238 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21239 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21240 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21242 (defun org-insert-comment ()
21243 "Insert an empty comment above current line.
21244 If the line is empty, insert comment at its beginning."
21245 (beginning-of-line)
21246 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21247 (org-indent-line)
21248 (insert "# "))
21250 (defvar comment-empty-lines) ; From newcomment.el.
21251 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21252 "Comment or uncomment each non-blank line in the region.
21253 Uncomment each non-blank line between BEG and END if it only
21254 contains commented lines. Otherwise, comment them."
21255 (save-restriction
21256 ;; Restrict region
21257 (narrow-to-region (save-excursion (goto-char beg)
21258 (skip-chars-forward " \r\t\n" end)
21259 (line-beginning-position))
21260 (save-excursion (goto-char end)
21261 (skip-chars-backward " \r\t\n" beg)
21262 (line-end-position)))
21263 (let ((uncommentp
21264 ;; UNCOMMENTP is non-nil when every non blank line between
21265 ;; BEG and END is a comment.
21266 (save-excursion
21267 (goto-char (point-min))
21268 (while (and (not (eobp))
21269 (let ((element (org-element-at-point)))
21270 (and (eq (org-element-type element) 'comment)
21271 (goto-char (min (point-max)
21272 (org-element-property
21273 :end element)))))))
21274 (eobp))))
21275 (if uncommentp
21276 ;; Only blank lines and comments in region: uncomment it.
21277 (save-excursion
21278 (goto-char (point-min))
21279 (while (not (eobp))
21280 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21281 (replace-match "" nil nil nil 1))
21282 (forward-line)))
21283 ;; Comment each line in region.
21284 (let ((min-indent (point-max)))
21285 ;; First find the minimum indentation across all lines.
21286 (save-excursion
21287 (goto-char (point-min))
21288 (while (and (not (eobp)) (not (zerop min-indent)))
21289 (unless (looking-at "[ \t]*$")
21290 (setq min-indent (min min-indent (current-indentation))))
21291 (forward-line)))
21292 ;; Then loop over all lines.
21293 (save-excursion
21294 (goto-char (point-min))
21295 (while (not (eobp))
21296 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21297 (org-move-to-column min-indent t)
21298 (insert comment-start))
21299 (forward-line))))))))
21302 ;;; Other stuff.
21304 (defun org-toggle-fixed-width-section (arg)
21305 "Toggle the fixed-width export.
21306 If there is no active region, the QUOTE keyword at the current headline is
21307 inserted or removed. When present, it causes the text between this headline
21308 and the next to be exported as fixed-width text, and unmodified.
21309 If there is an active region, this command adds or removes a colon as the
21310 first character of this line. If the first character of a line is a colon,
21311 this line is also exported in fixed-width font."
21312 (interactive "P")
21313 (let* ((cc 0)
21314 (regionp (org-region-active-p))
21315 (beg (if regionp (region-beginning) (point)))
21316 (end (if regionp (region-end)))
21317 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21318 (case-fold-search nil)
21319 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21320 off)
21321 (if regionp
21322 (save-excursion
21323 (goto-char beg)
21324 (setq cc (current-column))
21325 (beginning-of-line 1)
21326 (setq off (looking-at re))
21327 (while (> nlines 0)
21328 (setq nlines (1- nlines))
21329 (beginning-of-line 1)
21330 (cond
21331 (arg
21332 (org-move-to-column cc t)
21333 (insert ": \n")
21334 (forward-line -1))
21335 ((and off (looking-at re))
21336 (replace-match "" t t nil 1))
21337 ((not off) (org-move-to-column cc t) (insert ": ")))
21338 (forward-line 1)))
21339 (save-excursion
21340 (org-back-to-heading)
21341 (cond
21342 ((looking-at (format org-heading-keyword-regexp-format
21343 org-quote-string))
21344 (goto-char (match-end 1))
21345 (looking-at (concat " +" org-quote-string))
21346 (replace-match "" t t)
21347 (when (eolp) (insert " ")))
21348 ((looking-at org-outline-regexp)
21349 (goto-char (match-end 0))
21350 (insert org-quote-string " ")))))))
21352 (defun org-reftex-citation ()
21353 "Use reftex-citation to insert a citation into the buffer.
21354 This looks for a line like
21356 #+BIBLIOGRAPHY: foo plain option:-d
21358 and derives from it that foo.bib is the bibliography file relevant
21359 for this document. It then installs the necessary environment for RefTeX
21360 to work in this buffer and calls `reftex-citation' to insert a citation
21361 into the buffer.
21363 Export of such citations to both LaTeX and HTML is handled by the contributed
21364 package org-exp-bibtex by Taru Karttunen."
21365 (interactive)
21366 (let ((reftex-docstruct-symbol 'rds)
21367 (reftex-cite-format "\\cite{%l}")
21368 rds bib)
21369 (save-excursion
21370 (save-restriction
21371 (widen)
21372 (let ((case-fold-search t)
21373 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21374 (if (not (save-excursion
21375 (or (re-search-forward re nil t)
21376 (re-search-backward re nil t))))
21377 (error "No bibliography defined in file")
21378 (setq bib (concat (match-string 1) ".bib")
21379 rds (list (list 'bib bib)))))))
21380 (call-interactively 'reftex-citation)))
21382 ;;;; Functions extending outline functionality
21384 (defun org-beginning-of-line (&optional arg)
21385 "Go to the beginning of the current line. If that is invisible, continue
21386 to a visible line beginning. This makes the function of C-a more intuitive.
21387 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21388 first attempt, and only move to after the tags when the cursor is already
21389 beyond the end of the headline."
21390 (interactive "P")
21391 (let ((pos (point))
21392 (special (if (consp org-special-ctrl-a/e)
21393 (car org-special-ctrl-a/e)
21394 org-special-ctrl-a/e))
21395 refpos)
21396 (if (org-bound-and-true-p line-move-visual)
21397 (beginning-of-visual-line 1)
21398 (beginning-of-line 1))
21399 (if (and arg (fboundp 'move-beginning-of-line))
21400 (call-interactively 'move-beginning-of-line)
21401 (if (bobp)
21403 (backward-char 1)
21404 (if (org-truely-invisible-p)
21405 (while (and (not (bobp)) (org-truely-invisible-p))
21406 (backward-char 1)
21407 (beginning-of-line 1))
21408 (forward-char 1))))
21409 (when special
21410 (cond
21411 ((and (looking-at org-complex-heading-regexp)
21412 (= (char-after (match-end 1)) ?\ ))
21413 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21414 (point-at-eol)))
21415 (goto-char
21416 (if (eq special t)
21417 (cond ((> pos refpos) refpos)
21418 ((= pos (point)) refpos)
21419 (t (point)))
21420 (cond ((> pos (point)) (point))
21421 ((not (eq last-command this-command)) (point))
21422 (t refpos)))))
21423 ((org-at-item-p)
21424 ;; Being at an item and not looking at an the item means point
21425 ;; was previously moved to beginning of a visual line, which
21426 ;; doesn't contain the item. Therefore, do nothing special,
21427 ;; just stay here.
21428 (when (looking-at org-list-full-item-re)
21429 ;; Set special position at first white space character after
21430 ;; bullet, and check-box, if any.
21431 (let ((after-bullet
21432 (let ((box (match-end 3)))
21433 (if (not box) (match-end 1)
21434 (let ((after (char-after box)))
21435 (if (and after (= after ? )) (1+ box) box))))))
21436 ;; Special case: Move point to special position when
21437 ;; currently after it or at beginning of line.
21438 (if (eq special t)
21439 (when (or (> pos after-bullet) (= (point) pos))
21440 (goto-char after-bullet))
21441 ;; Reversed case: Move point to special position when
21442 ;; point was already at beginning of line and command is
21443 ;; repeated.
21444 (when (and (= (point) pos) (eq last-command this-command))
21445 (goto-char after-bullet))))))))
21446 (org-no-warnings
21447 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21449 (defun org-end-of-line (&optional arg)
21450 "Go to the end of the line.
21451 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21452 first attempt, and only move to after the tags when the cursor is already
21453 beyond the end of the headline."
21454 (interactive "P")
21455 (let ((special (if (consp org-special-ctrl-a/e)
21456 (cdr org-special-ctrl-a/e)
21457 org-special-ctrl-a/e)))
21458 (cond
21459 ((or (not special) arg
21460 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21461 (call-interactively
21462 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21463 ((fboundp 'move-end-of-line) 'move-end-of-line)
21464 (t 'end-of-line))))
21465 ((org-at-heading-p)
21466 (let ((pos (point)))
21467 (beginning-of-line 1)
21468 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21469 (if (eq special t)
21470 (if (or (< pos (match-beginning 1))
21471 (= pos (match-end 0)))
21472 (goto-char (match-beginning 1))
21473 (goto-char (match-end 0)))
21474 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21475 (goto-char (match-end 0))
21476 (goto-char (match-beginning 1))))
21477 (call-interactively (if (fboundp 'move-end-of-line)
21478 'move-end-of-line
21479 'end-of-line)))))
21480 ((org-at-drawer-p)
21481 (move-end-of-line 1)
21482 (when (overlays-at (1- (point))) (backward-char 1)))
21483 ;; At an item: Move before any hidden text.
21484 (t (call-interactively
21485 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21486 ((fboundp 'move-end-of-line) 'move-end-of-line)
21487 (t 'end-of-line)))))
21488 (org-no-warnings
21489 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21491 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21492 (define-key org-mode-map "\C-e" 'org-end-of-line)
21494 (defun org-backward-sentence (&optional arg)
21495 "Go to beginning of sentence, or beginning of table field.
21496 This will call `backward-sentence' or `org-table-beginning-of-field',
21497 depending on context."
21498 (interactive "P")
21499 (cond
21500 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21501 (t (call-interactively 'backward-sentence))))
21503 (defun org-forward-sentence (&optional arg)
21504 "Go to end of sentence, or end of table field.
21505 This will call `forward-sentence' or `org-table-end-of-field',
21506 depending on context."
21507 (interactive "P")
21508 (cond
21509 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21510 (t (call-interactively 'forward-sentence))))
21512 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21513 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21515 (defun org-kill-line (&optional arg)
21516 "Kill line, to tags or end of line."
21517 (interactive "P")
21518 (cond
21519 ((or (not org-special-ctrl-k)
21520 (bolp)
21521 (not (org-at-heading-p)))
21522 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21523 org-ctrl-k-protect-subtree)
21524 (if (or (eq org-ctrl-k-protect-subtree 'error)
21525 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21526 (error "C-k aborted - would kill hidden subtree")))
21527 (call-interactively
21528 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21529 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21530 (kill-region (point) (match-beginning 1))
21531 (org-set-tags nil t))
21532 (t (kill-region (point) (point-at-eol)))))
21534 (define-key org-mode-map "\C-k" 'org-kill-line)
21536 (defun org-yank (&optional arg)
21537 "Yank. If the kill is a subtree, treat it specially.
21538 This command will look at the current kill and check if is a single
21539 subtree, or a series of subtrees[1]. If it passes the test, and if the
21540 cursor is at the beginning of a line or after the stars of a currently
21541 empty headline, then the yank is handled specially. How exactly depends
21542 on the value of the following variables, both set by default.
21544 org-yank-folded-subtrees
21545 When set, the subtree(s) will be folded after insertion, but only
21546 if doing so would now swallow text after the yanked text.
21548 org-yank-adjusted-subtrees
21549 When set, the subtree will be promoted or demoted in order to
21550 fit into the local outline tree structure, which means that the level
21551 will be adjusted so that it becomes the smaller one of the two
21552 *visible* surrounding headings.
21554 Any prefix to this command will cause `yank' to be called directly with
21555 no special treatment. In particular, a simple \\[universal-argument] prefix \
21556 will just
21557 plainly yank the text as it is.
21559 \[1] The test checks if the first non-white line is a heading
21560 and if there are no other headings with fewer stars."
21561 (interactive "P")
21562 (org-yank-generic 'yank arg))
21564 (defun org-yank-generic (command arg)
21565 "Perform some yank-like command.
21567 This function implements the behavior described in the `org-yank'
21568 documentation. However, it has been generalized to work for any
21569 interactive command with similar behavior."
21571 ;; pretend to be command COMMAND
21572 (setq this-command command)
21574 (if arg
21575 (call-interactively command)
21577 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21578 (and (org-kill-is-subtree-p)
21579 (or (bolp)
21580 (and (looking-at "[ \t]*$")
21581 (string-match
21582 "\\`\\*+\\'"
21583 (buffer-substring (point-at-bol) (point)))))))
21584 swallowp)
21585 (cond
21586 ((and subtreep org-yank-folded-subtrees)
21587 (let ((beg (point))
21588 end)
21589 (if (and subtreep org-yank-adjusted-subtrees)
21590 (org-paste-subtree nil nil 'for-yank)
21591 (call-interactively command))
21593 (setq end (point))
21594 (goto-char beg)
21595 (when (and (bolp) subtreep
21596 (not (setq swallowp
21597 (org-yank-folding-would-swallow-text beg end))))
21598 (org-with-limited-levels
21599 (or (looking-at org-outline-regexp)
21600 (re-search-forward org-outline-regexp-bol end t))
21601 (while (and (< (point) end) (looking-at org-outline-regexp))
21602 (hide-subtree)
21603 (org-cycle-show-empty-lines 'folded)
21604 (condition-case nil
21605 (outline-forward-same-level 1)
21606 (error (goto-char end))))))
21607 (when swallowp
21608 (message
21609 "Inserted text not folded because that would swallow text"))
21611 (goto-char end)
21612 (skip-chars-forward " \t\n\r")
21613 (beginning-of-line 1)
21614 (push-mark beg 'nomsg)))
21615 ((and subtreep org-yank-adjusted-subtrees)
21616 (let ((beg (point-at-bol)))
21617 (org-paste-subtree nil nil 'for-yank)
21618 (push-mark beg 'nomsg)))
21620 (call-interactively command))))))
21622 (defun org-yank-folding-would-swallow-text (beg end)
21623 "Would hide-subtree at BEG swallow any text after END?"
21624 (let (level)
21625 (org-with-limited-levels
21626 (save-excursion
21627 (goto-char beg)
21628 (when (or (looking-at org-outline-regexp)
21629 (re-search-forward org-outline-regexp-bol end t))
21630 (setq level (org-outline-level)))
21631 (goto-char end)
21632 (skip-chars-forward " \t\r\n\v\f")
21633 (if (or (eobp)
21634 (and (bolp) (looking-at org-outline-regexp)
21635 (<= (org-outline-level) level)))
21636 nil ; Nothing would be swallowed
21637 t))))) ; something would swallow
21639 (define-key org-mode-map "\C-y" 'org-yank)
21641 (defun org-truely-invisible-p ()
21642 "Check if point is at a character currently not visible.
21643 This version does not only check the character property, but also
21644 `visible-mode'."
21645 ;; Early versions of noutline don't have `outline-invisible-p'.
21646 (if (org-bound-and-true-p visible-mode)
21648 (outline-invisible-p)))
21650 (defun org-invisible-p2 ()
21651 "Check if point is at a character currently not visible."
21652 (save-excursion
21653 (if (and (eolp) (not (bobp))) (backward-char 1))
21654 ;; Early versions of noutline don't have `outline-invisible-p'.
21655 (outline-invisible-p)))
21657 (defun org-back-to-heading (&optional invisible-ok)
21658 "Call `outline-back-to-heading', but provide a better error message."
21659 (condition-case nil
21660 (outline-back-to-heading invisible-ok)
21661 (error (error "Before first headline at position %d in buffer %s"
21662 (point) (current-buffer)))))
21664 (defun org-before-first-heading-p ()
21665 "Before first heading?"
21666 (save-excursion
21667 (end-of-line)
21668 (null (re-search-backward org-outline-regexp-bol nil t))))
21670 (defun org-at-heading-p (&optional ignored)
21671 (outline-on-heading-p t))
21672 ;; Compatibility alias with Org versions < 7.8.03
21673 (defalias 'org-on-heading-p 'org-at-heading-p)
21675 (defun org-at-comment-p nil
21676 "Is cursor in a line starting with a # character?"
21677 (save-excursion
21678 (beginning-of-line)
21679 (looking-at "^#")))
21681 (defun org-at-drawer-p nil
21682 "Is cursor at a drawer keyword?"
21683 (save-excursion
21684 (move-beginning-of-line 1)
21685 (looking-at org-drawer-regexp)))
21687 (defun org-at-block-p nil
21688 "Is cursor at a block keyword?"
21689 (save-excursion
21690 (move-beginning-of-line 1)
21691 (looking-at org-block-regexp)))
21693 (defun org-point-at-end-of-empty-headline ()
21694 "If point is at the end of an empty headline, return t, else nil.
21695 If the heading only contains a TODO keyword, it is still still considered
21696 empty."
21697 (and (looking-at "[ \t]*$")
21698 (when org-todo-line-regexp
21699 (save-excursion
21700 (beginning-of-line 1)
21701 (let ((case-fold-search nil))
21702 (looking-at org-todo-line-regexp)
21703 (string= (match-string 3) ""))))))
21705 (defun org-at-heading-or-item-p ()
21706 (or (org-at-heading-p) (org-at-item-p)))
21708 (defun org-at-target-p ()
21709 (or (org-in-regexp org-radio-target-regexp)
21710 (org-in-regexp org-target-regexp)))
21711 ;; Compatibility alias with Org versions < 7.8.03
21712 (defalias 'org-on-target-p 'org-at-target-p)
21714 (defun org-up-heading-all (arg)
21715 "Move to the heading line of which the present line is a subheading.
21716 This function considers both visible and invisible heading lines.
21717 With argument, move up ARG levels."
21718 (if (fboundp 'outline-up-heading-all)
21719 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21720 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21722 (defun org-up-heading-safe ()
21723 "Move to the heading line of which the present line is a subheading.
21724 This version will not throw an error. It will return the level of the
21725 headline found, or nil if no higher level is found.
21727 Also, this function will be a lot faster than `outline-up-heading',
21728 because it relies on stars being the outline starters. This can really
21729 make a significant difference in outlines with very many siblings."
21730 (let (start-level re)
21731 (org-back-to-heading t)
21732 (setq start-level (funcall outline-level))
21733 (if (equal start-level 1)
21735 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21736 (if (re-search-backward re nil t)
21737 (funcall outline-level)))))
21739 (defun org-first-sibling-p ()
21740 "Is this heading the first child of its parents?"
21741 (interactive)
21742 (let ((re org-outline-regexp-bol)
21743 level l)
21744 (unless (org-at-heading-p t)
21745 (error "Not at a heading"))
21746 (setq level (funcall outline-level))
21747 (save-excursion
21748 (if (not (re-search-backward re nil t))
21750 (setq l (funcall outline-level))
21751 (< l level)))))
21753 (defun org-goto-sibling (&optional previous)
21754 "Goto the next sibling, even if it is invisible.
21755 When PREVIOUS is set, go to the previous sibling instead. Returns t
21756 when a sibling was found. When none is found, return nil and don't
21757 move point."
21758 (let ((fun (if previous 're-search-backward 're-search-forward))
21759 (pos (point))
21760 (re org-outline-regexp-bol)
21761 level l)
21762 (when (condition-case nil (org-back-to-heading t) (error nil))
21763 (setq level (funcall outline-level))
21764 (catch 'exit
21765 (or previous (forward-char 1))
21766 (while (funcall fun re nil t)
21767 (setq l (funcall outline-level))
21768 (when (< l level) (goto-char pos) (throw 'exit nil))
21769 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21770 (goto-char pos)
21771 nil))))
21773 (defun org-show-siblings ()
21774 "Show all siblings of the current headline."
21775 (save-excursion
21776 (while (org-goto-sibling) (org-flag-heading nil)))
21777 (save-excursion
21778 (while (org-goto-sibling 'previous)
21779 (org-flag-heading nil))))
21781 (defun org-goto-first-child ()
21782 "Goto the first child, even if it is invisible.
21783 Return t when a child was found. Otherwise don't move point and
21784 return nil."
21785 (let (level (pos (point)) (re org-outline-regexp-bol))
21786 (when (condition-case nil (org-back-to-heading t) (error nil))
21787 (setq level (outline-level))
21788 (forward-char 1)
21789 (if (and (re-search-forward re nil t) (> (outline-level) level))
21790 (progn (goto-char (match-beginning 0)) t)
21791 (goto-char pos) nil))))
21793 (defun org-show-hidden-entry ()
21794 "Show an entry where even the heading is hidden."
21795 (save-excursion
21796 (org-show-entry)))
21798 (defun org-flag-heading (flag &optional entry)
21799 "Flag the current heading. FLAG non-nil means make invisible.
21800 When ENTRY is non-nil, show the entire entry."
21801 (save-excursion
21802 (org-back-to-heading t)
21803 ;; Check if we should show the entire entry
21804 (if entry
21805 (progn
21806 (org-show-entry)
21807 (save-excursion
21808 (and (outline-next-heading)
21809 (org-flag-heading nil))))
21810 (outline-flag-region (max (point-min) (1- (point)))
21811 (save-excursion (outline-end-of-heading) (point))
21812 flag))))
21814 (defun org-get-next-sibling ()
21815 "Move to next heading of the same level, and return point.
21816 If there is no such heading, return nil.
21817 This is like outline-next-sibling, but invisible headings are ok."
21818 (let ((level (funcall outline-level)))
21819 (outline-next-heading)
21820 (while (and (not (eobp)) (> (funcall outline-level) level))
21821 (outline-next-heading))
21822 (if (or (eobp) (< (funcall outline-level) level))
21824 (point))))
21826 (defun org-get-last-sibling ()
21827 "Move to previous heading of the same level, and return point.
21828 If there is no such heading, return nil."
21829 (let ((opoint (point))
21830 (level (funcall outline-level)))
21831 (outline-previous-heading)
21832 (when (and (/= (point) opoint) (outline-on-heading-p t))
21833 (while (and (> (funcall outline-level) level)
21834 (not (bobp)))
21835 (outline-previous-heading))
21836 (if (< (funcall outline-level) level)
21838 (point)))))
21840 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21841 ;; This contains an exact copy of the original function, but it uses
21842 ;; `org-back-to-heading', to make it work also in invisible
21843 ;; trees. And is uses an invisible-OK argument.
21844 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21845 ;; Furthermore, when used inside Org, finding the end of a large subtree
21846 ;; with many children and grandchildren etc, this can be much faster
21847 ;; than the outline version.
21848 (org-back-to-heading invisible-OK)
21849 (let ((first t)
21850 (level (funcall outline-level)))
21851 (if (and (derived-mode-p 'org-mode) (< level 1000))
21852 ;; A true heading (not a plain list item), in Org-mode
21853 ;; This means we can easily find the end by looking
21854 ;; only for the right number of stars. Using a regexp to do
21855 ;; this is so much faster than using a Lisp loop.
21856 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21857 (forward-char 1)
21858 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21859 ;; something else, do it the slow way
21860 (while (and (not (eobp))
21861 (or first (> (funcall outline-level) level)))
21862 (setq first nil)
21863 (outline-next-heading)))
21864 (unless to-heading
21865 (if (memq (preceding-char) '(?\n ?\^M))
21866 (progn
21867 ;; Go to end of line before heading
21868 (forward-char -1)
21869 (if (memq (preceding-char) '(?\n ?\^M))
21870 ;; leave blank line before heading
21871 (forward-char -1))))))
21872 (point))
21874 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21875 "Use Org version in org-mode, for dramatic speed-up."
21876 (if (derived-mode-p 'org-mode)
21877 (progn
21878 (org-end-of-subtree nil t)
21879 (unless (eobp) (backward-char 1)))
21880 ad-do-it))
21882 (defun org-end-of-meta-data-and-drawers ()
21883 "Jump to the first text after meta data and drawers in the current entry.
21884 This will move over empty lines, lines with planning time stamps,
21885 clocking lines, and drawers."
21886 (org-back-to-heading t)
21887 (let ((end (save-excursion (outline-next-heading) (point)))
21888 (re (concat "\\(" org-drawer-regexp "\\)"
21889 "\\|" "[ \t]*" org-keyword-time-regexp)))
21890 (forward-line 1)
21891 (while (re-search-forward re end t)
21892 (if (not (match-end 1))
21893 ;; empty or planning line
21894 (forward-line 1)
21895 ;; a drawer, find the end
21896 (re-search-forward "^[ \t]*:END:" end 'move)
21897 (forward-line 1)))
21898 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21899 (point)))
21901 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21902 "Move forward to the arg'th subheading at same level as this one.
21903 Stop at the first and last subheadings of a superior heading.
21904 Normally this only looks at visible headings, but when INVISIBLE-OK is
21905 non-nil it will also look at invisible ones."
21906 (interactive "p")
21907 (org-back-to-heading invisible-ok)
21908 (org-at-heading-p)
21909 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21910 (re (format "^\\*\\{1,%d\\} " level))
21912 (forward-char 1)
21913 (while (> arg 0)
21914 (while (and (re-search-forward re nil 'move)
21915 (setq l (- (match-end 0) (match-beginning 0) 1))
21916 (= l level)
21917 (not invisible-ok)
21918 (progn (backward-char 1) (outline-invisible-p)))
21919 (if (< l level) (setq arg 1)))
21920 (setq arg (1- arg)))
21921 (beginning-of-line 1)))
21923 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21924 "Move backward to the arg'th subheading at same level as this one.
21925 Stop at the first and last subheadings of a superior heading."
21926 (interactive "p")
21927 (org-back-to-heading)
21928 (org-at-heading-p)
21929 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21930 (re (format "^\\*\\{1,%d\\} " level))
21932 (while (> arg 0)
21933 (while (and (re-search-backward re nil 'move)
21934 (setq l (- (match-end 0) (match-beginning 0) 1))
21935 (= l level)
21936 (not invisible-ok)
21937 (outline-invisible-p))
21938 (if (< l level) (setq arg 1)))
21939 (setq arg (1- arg)))))
21941 ;;;###autoload
21942 (defun org-forward-element ()
21943 "Move forward by one element.
21944 Move to the next element at the same level, when possible."
21945 (interactive)
21946 (cond ((eobp) (error "Cannot move further down"))
21947 ((org-with-limited-levels (org-at-heading-p))
21948 (let ((origin (point)))
21949 (org-forward-heading-same-level 1)
21950 (unless (org-with-limited-levels (org-at-heading-p))
21951 (goto-char origin)
21952 (error "Cannot move further down"))))
21954 (let* ((elem (org-element-at-point))
21955 (end (org-element-property :end elem))
21956 (parent (org-element-property :parent elem)))
21957 (if (and parent (= (org-element-property :contents-end parent) end))
21958 (goto-char (org-element-property :end parent))
21959 (goto-char end))))))
21961 ;;;###autoload
21962 (defun org-backward-element ()
21963 "Move backward by one element.
21964 Move to the previous element at the same level, when possible."
21965 (interactive)
21966 (cond ((bobp) (error "Cannot move further up"))
21967 ((org-with-limited-levels (org-at-heading-p))
21968 ;; At an headline, move to the previous one, if any, or stay
21969 ;; here.
21970 (let ((origin (point)))
21971 (org-backward-heading-same-level 1)
21972 (unless (org-with-limited-levels (org-at-heading-p))
21973 (goto-char origin)
21974 (error "Cannot move further up"))))
21976 (let* ((trail (org-element-at-point 'keep-trail))
21977 (elem (car trail))
21978 (prev-elem (nth 1 trail))
21979 (beg (org-element-property :begin elem)))
21980 (cond
21981 ;; Move to beginning of current element if point isn't
21982 ;; there already.
21983 ((/= (point) beg) (goto-char beg))
21984 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21985 ((org-before-first-heading-p) (goto-char (point-min)))
21986 (t (org-back-to-heading)))))))
21988 ;;;###autoload
21989 (defun org-up-element ()
21990 "Move to upper element."
21991 (interactive)
21992 (if (org-with-limited-levels (org-at-heading-p))
21993 (unless (org-up-heading-safe) (error "No surrounding element"))
21994 (let* ((elem (org-element-at-point))
21995 (parent (org-element-property :parent elem)))
21996 (if parent (goto-char (org-element-property :begin parent))
21997 (if (org-with-limited-levels (org-before-first-heading-p))
21998 (error "No surrounding element")
21999 (org-with-limited-levels (org-back-to-heading)))))))
22001 ;;;###autoload
22002 (defvar org-element-greater-elements)
22003 (defun org-down-element ()
22004 "Move to inner element."
22005 (interactive)
22006 (let ((element (org-element-at-point)))
22007 (cond
22008 ((memq (org-element-type element) '(plain-list table))
22009 (goto-char (org-element-property :contents-begin element))
22010 (forward-char))
22011 ((memq (org-element-type element) org-element-greater-elements)
22012 ;; If contents are hidden, first disclose them.
22013 (when (org-element-property :hiddenp element) (org-cycle))
22014 (goto-char (or (org-element-property :contents-begin element)
22015 (error "No content for this element"))))
22016 (t (error "No inner element")))))
22018 ;;;###autoload
22019 (defun org-drag-element-backward ()
22020 "Move backward element at point."
22021 (interactive)
22022 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22023 (let* ((trail (org-element-at-point 'keep-trail))
22024 (elem (car trail))
22025 (prev-elem (nth 1 trail)))
22026 ;; Error out if no previous element or previous element is
22027 ;; a parent of the current one.
22028 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22029 (error "Cannot drag element backward")
22030 (let ((pos (point)))
22031 (org-element-swap-A-B prev-elem elem)
22032 (goto-char (+ (org-element-property :begin prev-elem)
22033 (- pos (org-element-property :begin elem)))))))))
22035 ;;;###autoload
22036 (defun org-drag-element-forward ()
22037 "Move forward element at point."
22038 (interactive)
22039 (let* ((pos (point))
22040 (elem (org-element-at-point)))
22041 (when (= (point-max) (org-element-property :end elem))
22042 (error "Cannot drag element forward"))
22043 (goto-char (org-element-property :end elem))
22044 (let ((next-elem (org-element-at-point)))
22045 (when (or (org-element-nested-p elem next-elem)
22046 (and (eq (org-element-type next-elem) 'headline)
22047 (not (eq (org-element-type elem) 'headline))))
22048 (goto-char pos)
22049 (error "Cannot drag element forward"))
22050 ;; Compute new position of point: it's shifted by NEXT-ELEM
22051 ;; body's length (without final blanks) and by the length of
22052 ;; blanks between ELEM and NEXT-ELEM.
22053 (let ((size-next (- (save-excursion
22054 (goto-char (org-element-property :end next-elem))
22055 (skip-chars-backward " \r\t\n")
22056 (forward-line)
22057 ;; Small correction if buffer doesn't end
22058 ;; with a newline character.
22059 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22060 (org-element-property :begin next-elem)))
22061 (size-blank (- (org-element-property :end elem)
22062 (save-excursion
22063 (goto-char (org-element-property :end elem))
22064 (skip-chars-backward " \r\t\n")
22065 (forward-line)
22066 (point)))))
22067 (org-element-swap-A-B elem next-elem)
22068 (goto-char (+ pos size-next size-blank))))))
22070 ;;;###autoload
22071 (defun org-mark-element ()
22072 "Put point at beginning of this element, mark at end.
22074 Interactively, if this command is repeated or (in Transient Mark
22075 mode) if the mark is active, it marks the next element after the
22076 ones already marked."
22077 (interactive)
22078 (let (deactivate-mark)
22079 (if (and (org-called-interactively-p 'any)
22080 (or (and (eq last-command this-command) (mark t))
22081 (and transient-mark-mode mark-active)))
22082 (set-mark
22083 (save-excursion
22084 (goto-char (mark))
22085 (goto-char (org-element-property :end (org-element-at-point)))))
22086 (let ((element (org-element-at-point)))
22087 (end-of-line)
22088 (push-mark (org-element-property :end element) t t)
22089 (goto-char (org-element-property :begin element))))))
22091 ;;;###autoload
22092 (defun org-narrow-to-element ()
22093 "Narrow buffer to current element."
22094 (interactive)
22095 (let ((elem (org-element-at-point)))
22096 (cond
22097 ((eq (car elem) 'headline)
22098 (narrow-to-region
22099 (org-element-property :begin elem)
22100 (org-element-property :end elem)))
22101 ((memq (car elem) org-element-greater-elements)
22102 (narrow-to-region
22103 (org-element-property :contents-begin elem)
22104 (org-element-property :contents-end elem)))
22106 (narrow-to-region
22107 (org-element-property :begin elem)
22108 (org-element-property :end elem))))))
22110 ;;;###autoload
22111 (defun org-transpose-element ()
22112 "Transpose current and previous elements, keeping blank lines between.
22113 Point is moved after both elements."
22114 (interactive)
22115 (org-skip-whitespace)
22116 (let ((end (org-element-property :end (org-element-at-point))))
22117 (org-drag-element-backward)
22118 (goto-char end)))
22120 ;;;###autoload
22121 (defun org-unindent-buffer ()
22122 "Un-indent the visible part of the buffer.
22123 Relative indentation (between items, inside blocks, etc.) isn't
22124 modified."
22125 (interactive)
22126 (unless (eq major-mode 'org-mode)
22127 (error "Cannot un-indent a buffer not in Org mode"))
22128 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22129 unindent-tree ; For byte-compiler.
22130 (unindent-tree
22131 (function
22132 (lambda (contents)
22133 (mapc
22134 (lambda (element)
22135 (if (memq (org-element-type element) '(headline section))
22136 (funcall unindent-tree (org-element-contents element))
22137 (save-excursion
22138 (save-restriction
22139 (narrow-to-region
22140 (org-element-property :begin element)
22141 (org-element-property :end element))
22142 (org-do-remove-indentation)))))
22143 (reverse contents))))))
22144 (funcall unindent-tree (org-element-contents parse-tree))))
22146 (defun org-show-subtree ()
22147 "Show everything after this heading at deeper levels."
22148 (interactive)
22149 (outline-flag-region
22150 (point)
22151 (save-excursion
22152 (org-end-of-subtree t t))
22153 nil))
22155 (defun org-show-entry ()
22156 "Show the body directly following this heading.
22157 Show the heading too, if it is currently invisible."
22158 (interactive)
22159 (save-excursion
22160 (condition-case nil
22161 (progn
22162 (org-back-to-heading t)
22163 (outline-flag-region
22164 (max (point-min) (1- (point)))
22165 (save-excursion
22166 (if (re-search-forward
22167 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22168 (match-beginning 1)
22169 (point-max)))
22170 nil)
22171 (org-cycle-hide-drawers 'children))
22172 (error nil))))
22174 (defun org-make-options-regexp (kwds &optional extra)
22175 "Make a regular expression for keyword lines."
22176 (concat
22177 "^#\\+\\("
22178 (mapconcat 'regexp-quote kwds "\\|")
22179 (if extra (concat "\\|" extra))
22180 "\\):[ \t]*\\(.*\\)"))
22182 ;; Make isearch reveal the necessary context
22183 (defun org-isearch-end ()
22184 "Reveal context after isearch exits."
22185 (when isearch-success ; only if search was successful
22186 (if (featurep 'xemacs)
22187 ;; Under XEmacs, the hook is run in the correct place,
22188 ;; we directly show the context.
22189 (org-show-context 'isearch)
22190 ;; In Emacs the hook runs *before* restoring the overlays.
22191 ;; So we have to use a one-time post-command-hook to do this.
22192 ;; (Emacs 22 has a special variable, see function `org-mode')
22193 (unless (and (boundp 'isearch-mode-end-hook-quit)
22194 isearch-mode-end-hook-quit)
22195 ;; Only when the isearch was not quitted.
22196 (org-add-hook 'post-command-hook 'org-isearch-post-command
22197 'append 'local)))))
22199 (defun org-isearch-post-command ()
22200 "Remove self from hook, and show context."
22201 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22202 (org-show-context 'isearch))
22205 ;;;; Integration with and fixes for other packages
22207 ;;; Imenu support
22209 (defvar org-imenu-markers nil
22210 "All markers currently used by Imenu.")
22211 (make-variable-buffer-local 'org-imenu-markers)
22213 (defun org-imenu-new-marker (&optional pos)
22214 "Return a new marker for use by Imenu, and remember the marker."
22215 (let ((m (make-marker)))
22216 (move-marker m (or pos (point)))
22217 (push m org-imenu-markers)
22220 (defun org-imenu-get-tree ()
22221 "Produce the index for Imenu."
22222 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22223 (setq org-imenu-markers nil)
22224 (let* ((n org-imenu-depth)
22225 (re (concat "^" (org-get-limited-outline-regexp)))
22226 (subs (make-vector (1+ n) nil))
22227 (last-level 0)
22228 m level head)
22229 (save-excursion
22230 (save-restriction
22231 (widen)
22232 (goto-char (point-max))
22233 (while (re-search-backward re nil t)
22234 (setq level (org-reduced-level (funcall outline-level)))
22235 (when (and (<= level n)
22236 (looking-at org-complex-heading-regexp))
22237 (setq head (org-link-display-format
22238 (org-match-string-no-properties 4))
22239 m (org-imenu-new-marker))
22240 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22241 (if (>= level last-level)
22242 (push (cons head m) (aref subs level))
22243 (push (cons head (aref subs (1+ level))) (aref subs level))
22244 (loop for i from (1+ level) to n do (aset subs i nil)))
22245 (setq last-level level)))))
22246 (aref subs 1)))
22248 (eval-after-load "imenu"
22249 '(progn
22250 (add-hook 'imenu-after-jump-hook
22251 (lambda ()
22252 (if (derived-mode-p 'org-mode)
22253 (org-show-context 'org-goto))))))
22255 (defun org-link-display-format (link)
22256 "Replace a link with either the description, or the link target
22257 if no description is present"
22258 (save-match-data
22259 (if (string-match org-bracket-link-analytic-regexp link)
22260 (replace-match (if (match-end 5)
22261 (match-string 5 link)
22262 (concat (match-string 1 link)
22263 (match-string 3 link)))
22264 nil t link)
22265 link)))
22267 (defun org-toggle-link-display ()
22268 "Toggle the literal or descriptive display of links."
22269 (interactive)
22270 (if org-descriptive-links
22271 (progn (org-remove-from-invisibility-spec '(org-link))
22272 (org-restart-font-lock)
22273 (setq org-descriptive-links nil))
22274 (progn (add-to-invisibility-spec '(org-link))
22275 (org-restart-font-lock)
22276 (setq org-descriptive-links t))))
22278 ;; Speedbar support
22280 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22281 "Overlay marking the agenda restriction line in speedbar.")
22282 (overlay-put org-speedbar-restriction-lock-overlay
22283 'face 'org-agenda-restriction-lock)
22284 (overlay-put org-speedbar-restriction-lock-overlay
22285 'help-echo "Agendas are currently limited to this item.")
22286 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22288 (defun org-speedbar-set-agenda-restriction ()
22289 "Restrict future agenda commands to the location at point in speedbar.
22290 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22291 (interactive)
22292 (require 'org-agenda)
22293 (let (p m tp np dir txt)
22294 (cond
22295 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22296 'org-imenu t))
22297 (setq m (get-text-property p 'org-imenu-marker))
22298 (with-current-buffer (marker-buffer m)
22299 (goto-char m)
22300 (org-agenda-set-restriction-lock 'subtree)))
22301 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22302 'speedbar-function 'speedbar-find-file))
22303 (setq tp (previous-single-property-change
22304 (1+ p) 'speedbar-function)
22305 np (next-single-property-change
22306 tp 'speedbar-function)
22307 dir (speedbar-line-directory)
22308 txt (buffer-substring-no-properties (or tp (point-min))
22309 (or np (point-max))))
22310 (with-current-buffer (find-file-noselect
22311 (let ((default-directory dir))
22312 (expand-file-name txt)))
22313 (unless (derived-mode-p 'org-mode)
22314 (error "Cannot restrict to non-Org-mode file"))
22315 (org-agenda-set-restriction-lock 'file)))
22316 (t (error "Don't know how to restrict Org-mode's agenda")))
22317 (move-overlay org-speedbar-restriction-lock-overlay
22318 (point-at-bol) (point-at-eol))
22319 (setq current-prefix-arg nil)
22320 (org-agenda-maybe-redo)))
22322 (eval-after-load "speedbar"
22323 '(progn
22324 (speedbar-add-supported-extension ".org")
22325 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22326 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22327 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22328 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22329 (add-hook 'speedbar-visiting-tag-hook
22330 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22332 ;;; Fixes and Hacks for problems with other packages
22334 ;; Make flyspell not check words in links, to not mess up our keymap
22335 (defun org-mode-flyspell-verify ()
22336 "Don't let flyspell put overlays at active buttons, or on
22337 {todo,all-time,additional-option-like}-keywords."
22338 (let ((pos (max (1- (point)) (point-min)))
22339 (word (thing-at-point 'word)))
22340 (and (not (get-text-property pos 'keymap))
22341 (not (get-text-property pos 'org-no-flyspell))
22342 (not (member word org-todo-keywords-1))
22343 (not (member word org-all-time-keywords))
22344 (not (member word org-options-keywords))
22345 (not (member word (mapcar 'car org-startup-options)))
22346 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22348 (defun org-remove-flyspell-overlays-in (beg end)
22349 "Remove flyspell overlays in region."
22350 (and (org-bound-and-true-p flyspell-mode)
22351 (fboundp 'flyspell-delete-region-overlays)
22352 (flyspell-delete-region-overlays beg end))
22353 (add-text-properties beg end '(org-no-flyspell t)))
22355 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22356 (eval-after-load "bookmark"
22357 '(if (boundp 'bookmark-after-jump-hook)
22358 ;; We can use the hook
22359 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22360 ;; Hook not available, use advice
22361 (defadvice bookmark-jump (after org-make-visible activate)
22362 "Make the position visible."
22363 (org-bookmark-jump-unhide))))
22365 ;; Make sure saveplace shows the location if it was hidden
22366 (eval-after-load "saveplace"
22367 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22368 "Make the position visible."
22369 (org-bookmark-jump-unhide)))
22371 ;; Make sure ecb shows the location if it was hidden
22372 (eval-after-load "ecb"
22373 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22374 "Make hierarchy visible when jumping into location from ECB tree buffer."
22375 (if (derived-mode-p 'org-mode)
22376 (org-show-context))))
22378 (defun org-bookmark-jump-unhide ()
22379 "Unhide the current position, to show the bookmark location."
22380 (and (derived-mode-p 'org-mode)
22381 (or (outline-invisible-p)
22382 (save-excursion (goto-char (max (point-min) (1- (point))))
22383 (outline-invisible-p)))
22384 (org-show-context 'bookmark-jump)))
22386 ;; Make session.el ignore our circular variable
22387 (eval-after-load "session"
22388 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22390 ;;;; Experimental code
22392 (defun org-closed-in-range ()
22393 "Sparse tree of items closed in a certain time range.
22394 Still experimental, may disappear in the future."
22395 (interactive)
22396 ;; Get the time interval from the user.
22397 (let* ((time1 (org-float-time
22398 (org-read-date nil 'to-time nil "Starting date: ")))
22399 (time2 (org-float-time
22400 (org-read-date nil 'to-time nil "End date:")))
22401 ;; callback function
22402 (callback (lambda ()
22403 (let ((time
22404 (org-float-time
22405 (apply 'encode-time
22406 (org-parse-time-string
22407 (match-string 1))))))
22408 ;; check if time in interval
22409 (and (>= time time1) (<= time time2))))))
22410 ;; make tree, check each match with the callback
22411 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22413 ;;;; Finish up
22415 (provide 'org)
22417 (run-hooks 'org-load-hook)
22419 ;;; org.el ends here