org.el (org-cycle-internal-local): Don't run hooks when cycling a plain list before...
[org-mode.git] / lisp / org.el
bloba780fa392dd84576a20cb875cdc5aa4f6ebbab9f
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 (load "org-loaddefs.el" t t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-timestamps-up "org-clock" ())
119 (declare-function org-clock-timestamps-down "org-clock" ())
120 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122 (declare-function orgtbl-mode "org-table" (&optional arg))
123 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
124 (declare-function org-beamer-mode "org-beamer" ())
125 (declare-function org-table-edit-field "org-table" (arg))
126 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
127 (declare-function org-id-get-create "org-id" (&optional force))
128 (declare-function org-id-find-id-file "org-id" (id))
129 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
130 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
131 (declare-function org-table-align "org-table" ())
132 (declare-function org-table-paste-rectangle "org-table" ())
133 (declare-function org-table-maybe-eval-formula "org-table" ())
134 (declare-function org-table-maybe-recalculate-line "org-table" ())
136 ;; load languages based on value of `org-babel-load-languages'
137 (defvar org-babel-load-languages)
139 ;;;###autoload
140 (defun org-babel-do-load-languages (sym value)
141 "Load the languages defined in `org-babel-load-languages'."
142 (set-default sym value)
143 (mapc (lambda (pair)
144 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
145 (if active
146 (progn
147 (require (intern (concat "ob-" lang))))
148 (progn
149 (funcall 'fmakunbound
150 (intern (concat "org-babel-execute:" lang)))
151 (funcall 'fmakunbound
152 (intern (concat "org-babel-expand-body:" lang)))))))
153 org-babel-load-languages))
155 (defcustom org-babel-load-languages '((emacs-lisp . t))
156 "Languages which can be evaluated in Org-mode buffers.
157 This list can be used to load support for any of the languages
158 below, note that each language will depend on a different set of
159 system executables and/or Emacs modes. When a language is
160 \"loaded\", then code blocks in that language can be evaluated
161 with `org-babel-execute-src-block' bound by default to C-c
162 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
163 be set to remove code block evaluation from the C-c C-c
164 keybinding. By default only Emacs Lisp (which has no
165 requirements) is loaded."
166 :group 'org-babel
167 :set 'org-babel-do-load-languages
168 :version "24.1"
169 :type '(alist :tag "Babel Languages"
170 :key-type
171 (choice
172 (const :tag "Awk" awk)
173 (const :tag "C" C)
174 (const :tag "R" R)
175 (const :tag "Asymptote" asymptote)
176 (const :tag "Calc" calc)
177 (const :tag "Clojure" clojure)
178 (const :tag "CSS" css)
179 (const :tag "Ditaa" ditaa)
180 (const :tag "Dot" dot)
181 (const :tag "Emacs Lisp" emacs-lisp)
182 (const :tag "Fortran" fortran)
183 (const :tag "Gnuplot" gnuplot)
184 (const :tag "Haskell" haskell)
185 (const :tag "IO" io)
186 (const :tag "Java" java)
187 (const :tag "Javascript" js)
188 (const :tag "LaTeX" latex)
189 (const :tag "Ledger" ledger)
190 (const :tag "Lilypond" lilypond)
191 (const :tag "Lisp" lisp)
192 (const :tag "Maxima" maxima)
193 (const :tag "Matlab" matlab)
194 (const :tag "Mscgen" mscgen)
195 (const :tag "Ocaml" ocaml)
196 (const :tag "Octave" octave)
197 (const :tag "Org" org)
198 (const :tag "Perl" perl)
199 (const :tag "Pico Lisp" picolisp)
200 (const :tag "PlantUML" plantuml)
201 (const :tag "Python" python)
202 (const :tag "Ruby" ruby)
203 (const :tag "Sass" sass)
204 (const :tag "Scala" scala)
205 (const :tag "Scheme" scheme)
206 (const :tag "Screen" screen)
207 (const :tag "Shell Script" sh)
208 (const :tag "Shen" shen)
209 (const :tag "Sql" sql)
210 (const :tag "Sqlite" sqlite))
211 :value-type (boolean :tag "Activate" :value t)))
213 ;;;; Customization variables
214 (defcustom org-clone-delete-id nil
215 "Remove ID property of clones of a subtree.
216 When non-nil, clones of a subtree don't inherit the ID property.
217 Otherwise they inherit the ID property with a new unique
218 identifier."
219 :type 'boolean
220 :version "24.1"
221 :group 'org-id)
223 ;;; Version
224 (require 'org-compat)
225 (org-check-version)
227 ;;;###autoload
228 (defun org-version (&optional here full message)
229 "Show the org-mode version in the echo area.
230 With prefix argument HERE, insert it at point.
231 When FULL is non-nil, use a verbose version string.
232 When MESSAGE is non-nil, display a message with the version."
233 (interactive "P")
234 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
235 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs.el")))
236 (org-trash (or
237 (and (fboundp 'org-release) (fboundp 'org-git-version))
238 (load (concat org-dir "org-version.el")
239 'noerror 'nomessage 'nosuffix)))
240 (org-version (org-release))
241 (git-version (org-git-version))
242 (version (format "Org-mode version %s (%s @ %s)"
243 org-version
244 git-version
245 (if org-install-dir
246 (if (string= org-dir org-install-dir)
247 org-install-dir
248 (concat "mixed installation! " org-install-dir " and " org-dir))
249 "org-loaddefs.el can not be found!")))
250 (_version (if full version org-version)))
251 (if (org-called-interactively-p 'interactive)
252 (if here
253 (insert version)
254 (message version))
255 (if message (message _version))
256 _version)))
258 (defconst org-version (org-version))
260 ;;; Compatibility constants
262 ;;; The custom variables
264 (defgroup org nil
265 "Outline-based notes management and organizer."
266 :tag "Org"
267 :group 'outlines
268 :group 'calendar)
270 (defcustom org-mode-hook nil
271 "Mode hook for Org-mode, run after the mode was turned on."
272 :group 'org
273 :type 'hook)
275 (defcustom org-load-hook nil
276 "Hook that is run after org.el has been loaded."
277 :group 'org
278 :type 'hook)
280 (defcustom org-log-buffer-setup-hook nil
281 "Hook that is run after an Org log buffer is created."
282 :group 'org
283 :version "24.1"
284 :type 'hook)
286 (defvar org-modules) ; defined below
287 (defvar org-modules-loaded nil
288 "Have the modules been loaded already?")
290 (defun org-load-modules-maybe (&optional force)
291 "Load all extensions listed in `org-modules'."
292 (when (or force (not org-modules-loaded))
293 (mapc (lambda (ext)
294 (condition-case nil (require ext)
295 (error (message "Problems while trying to load feature `%s'" ext))))
296 org-modules)
297 (setq org-modules-loaded t)))
299 (defun org-set-modules (var value)
300 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
301 (set var value)
302 (when (featurep 'org)
303 (org-load-modules-maybe 'force)))
305 (when (org-bound-and-true-p org-modules)
306 (let ((a (member 'org-infojs org-modules)))
307 (and a (setcar a 'org-jsinfo))))
309 (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)
310 "Modules that should always be loaded together with org.el.
311 If a description starts with <C>, the file is not part of Emacs
312 and loading it will require that you have downloaded and properly installed
313 the org-mode distribution.
315 You can also use this system to load external packages (i.e. neither Org
316 core modules, nor modules from the CONTRIB directory). Just add symbols
317 to the end of the list. If the package is called org-xyz.el, then you need
318 to add the symbol `xyz', and the package must have a call to
320 (provide 'org-xyz)"
321 :group 'org
322 :set 'org-set-modules
323 :type
324 '(set :greedy t
325 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
326 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
327 (const :tag " crypt: Encryption of subtrees" org-crypt)
328 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
329 (const :tag " docview: Links to doc-view buffers" org-docview)
330 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
331 (const :tag " id: Global IDs for identifying entries" org-id)
332 (const :tag " info: Links to Info nodes" org-info)
333 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
334 (const :tag " habit: Track your consistency with habits" org-habit)
335 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
336 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
337 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
338 (const :tag " mew Links to Mew folders/messages" org-mew)
339 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
340 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
341 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
342 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
343 (const :tag " vm: Links to VM folders/messages" org-vm)
344 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
345 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
346 (const :tag " mouse: Additional mouse support" org-mouse)
347 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
349 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
350 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
351 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
352 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
353 (const :tag "C collector: Collect properties into tables" org-collector)
354 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
355 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
356 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
357 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
358 (const :tag "C eval: Include command output as text" org-eval)
359 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
360 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
361 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
362 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
363 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
365 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
367 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
368 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
369 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
370 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
371 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
372 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
373 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
374 (const :tag "C mtags: Support for muse-like tags" org-mtags)
375 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
376 (const :tag "C registry: A registry for Org-mode links" org-registry)
377 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
378 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
379 (const :tag "C secretary: Team management with org-mode" org-secretary)
380 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
381 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
382 (const :tag "C track: Keep up with Org-mode development" org-track)
383 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
384 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
385 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
387 (defcustom org-support-shift-select nil
388 "Non-nil means make shift-cursor commands select text when possible.
390 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
391 start selecting a region, or enlarge regions started in this way.
392 In Org-mode, in special contexts, these same keys are used for
393 other purposes, important enough to compete with shift selection.
394 Org tries to balance these needs by supporting `shift-select-mode'
395 outside these special contexts, under control of this variable.
397 The default of this variable is nil, to avoid confusing behavior. Shifted
398 cursor keys will then execute Org commands in the following contexts:
399 - on a headline, changing TODO state (left/right) and priority (up/down)
400 - on a time stamp, changing the time
401 - in a plain list item, changing the bullet type
402 - in a property definition line, switching between allowed values
403 - in the BEGIN line of a clock table (changing the time block).
404 Outside these contexts, the commands will throw an error.
406 When this variable is t and the cursor is not in a special
407 context, Org-mode will support shift-selection for making and
408 enlarging regions. To make this more effective, the bullet
409 cycling will no longer happen anywhere in an item line, but only
410 if the cursor is exactly on the bullet.
412 If you set this variable to the symbol `always', then the keys
413 will not be special in headlines, property lines, and item lines,
414 to make shift selection work there as well. If this is what you
415 want, you can use the following alternative commands: `C-c C-t'
416 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
417 can be used to switch TODO sets, `C-c -' to cycle item bullet
418 types, and properties can be edited by hand or in column view.
420 However, when the cursor is on a timestamp, shift-cursor commands
421 will still edit the time stamp - this is just too good to give up.
423 XEmacs user should have this variable set to nil, because
424 `shift-select-mode' is in Emacs 23 or later only."
425 :group 'org
426 :type '(choice
427 (const :tag "Never" nil)
428 (const :tag "When outside special context" t)
429 (const :tag "Everywhere except timestamps" always)))
431 (defcustom org-loop-over-headlines-in-active-region nil
432 "Shall some commands act upon headlines in the active region?
434 When set to `t', some commands will be performed in all headlines
435 within the active region.
437 When set to `start-level', some commands will be performed in all
438 headlines within the active region, provided that these headlines
439 are of the same level than the first one.
441 When set to a string, those commands will be performed on the
442 matching headlines within the active region. Such string must be
443 a tags/property/todo match as it is used in the agenda tags view.
445 The list of commands is: `org-schedule', `org-deadline',
446 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
447 `org-archive-to-archive-sibling'. The archiving commands skip
448 already archived entries."
449 :type '(choice (const :tag "Don't loop" nil)
450 (const :tag "All headlines in active region" t)
451 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
452 (string :tag "Tags/Property/Todo matcher"))
453 :version "24.1"
454 :group 'org-todo
455 :group 'org-archive)
457 (defgroup org-startup nil
458 "Options concerning startup of Org-mode."
459 :tag "Org Startup"
460 :group 'org)
462 (defcustom org-startup-folded t
463 "Non-nil means entering Org-mode will switch to OVERVIEW.
464 This can also be configured on a per-file basis by adding one of
465 the following lines anywhere in the buffer:
467 #+STARTUP: fold (or `overview', this is equivalent)
468 #+STARTUP: nofold (or `showall', this is equivalent)
469 #+STARTUP: content
470 #+STARTUP: showeverything"
471 :group 'org-startup
472 :type '(choice
473 (const :tag "nofold: show all" nil)
474 (const :tag "fold: overview" t)
475 (const :tag "content: all headlines" content)
476 (const :tag "show everything, even drawers" showeverything)))
478 (defcustom org-startup-truncated t
479 "Non-nil means entering Org-mode will set `truncate-lines'.
480 This is useful since some lines containing links can be very long and
481 uninteresting. Also tables look terrible when wrapped."
482 :group 'org-startup
483 :type 'boolean)
485 (defcustom org-startup-indented nil
486 "Non-nil means turn on `org-indent-mode' on startup.
487 This can also be configured on a per-file basis by adding one of
488 the following lines anywhere in the buffer:
490 #+STARTUP: indent
491 #+STARTUP: noindent"
492 :group 'org-structure
493 :type '(choice
494 (const :tag "Not" nil)
495 (const :tag "Globally (slow on startup in large files)" t)))
497 (defcustom org-use-sub-superscripts t
498 "Non-nil means interpret \"_\" and \"^\" for export.
499 When this option is turned on, you can use TeX-like syntax for sub- and
500 superscripts. Several characters after \"_\" or \"^\" will be
501 considered as a single item - so grouping with {} is normally not
502 needed. For example, the following things will be parsed as single
503 sub- or superscripts.
505 10^24 or 10^tau several digits will be considered 1 item.
506 10^-12 or 10^-tau a leading sign with digits or a word
507 x^2-y^3 will be read as x^2 - y^3, because items are
508 terminated by almost any nonword/nondigit char.
509 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
511 Still, ambiguity is possible - so when in doubt use {} to enclose the
512 sub/superscript. If you set this variable to the symbol `{}',
513 the braces are *required* in order to trigger interpretations as
514 sub/superscript. This can be helpful in documents that need \"_\"
515 frequently in plain text.
517 Not all export backends support this, but HTML does.
519 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
520 :group 'org-startup
521 :group 'org-export-translation
522 :version "24.1"
523 :type '(choice
524 (const :tag "Always interpret" t)
525 (const :tag "Only with braces" {})
526 (const :tag "Never interpret" nil)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
532 (defcustom org-startup-with-beamer-mode nil
533 "Non-nil means turn on `org-beamer-mode' on startup.
534 This can also be configured on a per-file basis by adding one of
535 the following lines anywhere in the buffer:
537 #+STARTUP: beamer"
538 :group 'org-startup
539 :version "24.1"
540 :type 'boolean)
542 (defcustom org-startup-align-all-tables nil
543 "Non-nil means align all tables when visiting a file.
544 This is useful when the column width in tables is forced with <N> cookies
545 in table fields. Such tables will look correct only after the first re-align.
546 This can also be configured on a per-file basis by adding one of
547 the following lines anywhere in the buffer:
548 #+STARTUP: align
549 #+STARTUP: noalign"
550 :group 'org-startup
551 :type 'boolean)
553 (defcustom org-startup-with-inline-images nil
554 "Non-nil means show inline images when loading a new Org file.
555 This can also be configured on a per-file basis by adding one of
556 the following lines anywhere in the buffer:
557 #+STARTUP: inlineimages
558 #+STARTUP: noinlineimages"
559 :group 'org-startup
560 :version "24.1"
561 :type 'boolean)
563 (defcustom org-insert-mode-line-in-empty-file nil
564 "Non-nil means insert the first line setting Org-mode in empty files.
565 When the function `org-mode' is called interactively in an empty file, this
566 normally means that the file name does not automatically trigger Org-mode.
567 To ensure that the file will always be in Org-mode in the future, a
568 line enforcing Org-mode will be inserted into the buffer, if this option
569 has been set."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-replace-disputed-keys nil
574 "Non-nil means use alternative key bindings for some keys.
575 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
576 These keys are also used by other packages like shift-selection-mode'
577 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
578 If you want to use Org-mode together with one of these other modes,
579 or more generally if you would like to move some Org-mode commands to
580 other keys, set this variable and configure the keys with the variable
581 `org-disputed-keys'.
583 This option is only relevant at load-time of Org-mode, and must be set
584 *before* org.el is loaded. Changing it requires a restart of Emacs to
585 become effective."
586 :group 'org-startup
587 :type 'boolean)
589 (defcustom org-use-extra-keys nil
590 "Non-nil means use extra key sequence definitions for certain commands.
591 This happens automatically if you run XEmacs or if `window-system'
592 is nil. This variable lets you do the same manually. You must
593 set it before loading org.
595 Example: on Carbon Emacs 22 running graphically, with an external
596 keyboard on a Powerbook, the default way of setting M-left might
597 not work for either Alt or ESC. Setting this variable will make
598 it work for ESC."
599 :group 'org-startup
600 :type 'boolean)
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
605 (defcustom org-disputed-keys
606 '(([(shift up)] . [(meta p)])
607 ([(shift down)] . [(meta n)])
608 ([(shift left)] . [(meta -)])
609 ([(shift right)] . [(meta +)])
610 ([(control shift right)] . [(meta shift +)])
611 ([(control shift left)] . [(meta shift -)]))
612 "Keys for which Org-mode and other modes compete.
613 This is an alist, cars are the default keys, second element specifies
614 the alternative to use when `org-replace-disputed-keys' is t.
616 Keys can be specified in any syntax supported by `define-key'.
617 The value of this option takes effect only at Org-mode's startup,
618 therefore you'll have to restart Emacs to apply it after changing."
619 :group 'org-startup
620 :type 'alist)
622 (defun org-key (key)
623 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
624 Or return the original if not disputed.
625 Also apply the translations defined in `org-xemacs-key-equivalents'."
626 (when org-replace-disputed-keys
627 (let* ((nkey (key-description key))
628 (x (org-find-if (lambda (x)
629 (equal (key-description (car x)) nkey))
630 org-disputed-keys)))
631 (setq key (if x (cdr x) key))))
632 (when (featurep 'xemacs)
633 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
634 key)
636 (defun org-find-if (predicate seq)
637 (catch 'exit
638 (while seq
639 (if (funcall predicate (car seq))
640 (throw 'exit (car seq))
641 (pop seq)))))
643 (defun org-defkey (keymap key def)
644 "Define a key, possibly translated, as returned by `org-key'."
645 (define-key keymap (org-key key) def))
647 (defcustom org-ellipsis nil
648 "The ellipsis to use in the Org-mode outline.
649 When nil, just use the standard three dots. When a string, use that instead,
650 When a face, use the standard 3 dots, but with the specified face.
651 The change affects only Org-mode (which will then use its own display table).
652 Changing this requires executing `M-x org-mode' in a buffer to become
653 effective."
654 :group 'org-startup
655 :type '(choice (const :tag "Default" nil)
656 (face :tag "Face" :value org-warning)
657 (string :tag "String" :value "...#")))
659 (defvar org-display-table nil
660 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
662 (defgroup org-keywords nil
663 "Keywords in Org-mode."
664 :tag "Org Keywords"
665 :group 'org)
667 (defcustom org-deadline-string "DEADLINE:"
668 "String to mark deadline entries.
669 A deadline is this string, followed by a time stamp. Should be a word,
670 terminated by a colon. You can insert a schedule keyword and
671 a timestamp with \\[org-deadline].
672 Changes become only effective after restarting Emacs."
673 :group 'org-keywords
674 :type 'string)
676 (defcustom org-scheduled-string "SCHEDULED:"
677 "String to mark scheduled TODO entries.
678 A schedule is this string, followed by a time stamp. Should be a word,
679 terminated by a colon. You can insert a schedule keyword and
680 a timestamp with \\[org-schedule].
681 Changes become only effective after restarting Emacs."
682 :group 'org-keywords
683 :type 'string)
685 (defcustom org-closed-string "CLOSED:"
686 "String used as the prefix for timestamps logging closing a TODO entry."
687 :group 'org-keywords
688 :type 'string)
690 (defcustom org-clock-string "CLOCK:"
691 "String used as prefix for timestamps clocking work hours on an item."
692 :group 'org-keywords
693 :type 'string)
695 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
696 org-scheduled-string "\\|"
697 org-deadline-string "\\|"
698 org-closed-string "\\|"
699 org-clock-string "\\)")
700 "Matches a line with planning or clock info.")
702 (defcustom org-comment-string "COMMENT"
703 "Entries starting with this keyword will never be exported.
704 An entry can be toggled between COMMENT and normal with
705 \\[org-toggle-comment].
706 Changes become only effective after restarting Emacs."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-quote-string "QUOTE"
711 "Entries starting with this keyword will be exported in fixed-width font.
712 Quoting applies only to the text in the entry following the headline, and does
713 not extend beyond the next headline, even if that is lower level.
714 An entry can be toggled between QUOTE and normal with
715 \\[org-toggle-fixed-width-section]."
716 :group 'org-keywords
717 :type 'string)
719 (defconst org-repeat-re
720 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
721 "Regular expression for specifying repeated events.
722 After a match, group 1 contains the repeat expression.")
724 (defgroup org-structure nil
725 "Options concerning the general structure of Org-mode files."
726 :tag "Org Structure"
727 :group 'org)
729 (defgroup org-reveal-location nil
730 "Options about how to make context of a location visible."
731 :tag "Org Reveal Location"
732 :group 'org-structure)
734 (defconst org-context-choice
735 '(choice
736 (const :tag "Always" t)
737 (const :tag "Never" nil)
738 (repeat :greedy t :tag "Individual contexts"
739 (cons
740 (choice :tag "Context"
741 (const agenda)
742 (const org-goto)
743 (const occur-tree)
744 (const tags-tree)
745 (const link-search)
746 (const mark-goto)
747 (const bookmark-jump)
748 (const isearch)
749 (const default))
750 (boolean))))
751 "Contexts for the reveal options.")
753 (defcustom org-show-hierarchy-above '((default . t))
754 "Non-nil means show full hierarchy when revealing a location.
755 Org-mode often shows locations in an org-mode file which might have
756 been invisible before. When this is set, the hierarchy of headings
757 above the exposed location is shown.
758 Turning this off for example for sparse trees makes them very compact.
759 Instead of t, this can also be an alist specifying this option for different
760 contexts. Valid contexts are
761 agenda when exposing an entry from the agenda
762 org-goto when using the command `org-goto' on key C-c C-j
763 occur-tree when using the command `org-occur' on key C-c /
764 tags-tree when constructing a sparse tree based on tags matches
765 link-search when exposing search matches associated with a link
766 mark-goto when exposing the jump goal of a mark
767 bookmark-jump when exposing a bookmark location
768 isearch when exiting from an incremental search
769 default default for all contexts not set explicitly"
770 :group 'org-reveal-location
771 :type org-context-choice)
773 (defcustom org-show-following-heading '((default . nil))
774 "Non-nil means show following heading when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the heading following the
777 match is shown.
778 Turning this off for example for sparse trees makes them very compact,
779 but makes it harder to edit the location of the match. In such a case,
780 use the command \\[org-reveal] to show more context.
781 Instead of t, this can also be an alist specifying this option for different
782 contexts. See `org-show-hierarchy-above' for valid contexts."
783 :group 'org-reveal-location
784 :type org-context-choice)
786 (defcustom org-show-siblings '((default . nil) (isearch t))
787 "Non-nil means show all sibling heading when revealing a location.
788 Org-mode often shows locations in an org-mode file which might have
789 been invisible before. When this is set, the sibling of the current entry
790 heading are all made visible. If `org-show-hierarchy-above' is t,
791 the same happens on each level of the hierarchy above the current entry.
793 By default this is on for the isearch context, off for all other contexts.
794 Turning this off for example for sparse trees makes them very compact,
795 but makes it harder to edit the location of the match. In such a case,
796 use the command \\[org-reveal] to show more context.
797 Instead of t, this can also be an alist specifying this option for different
798 contexts. See `org-show-hierarchy-above' for valid contexts."
799 :group 'org-reveal-location
800 :type org-context-choice)
802 (defcustom org-show-entry-below '((default . nil))
803 "Non-nil means show the entry below a headline when revealing a location.
804 Org-mode often shows locations in an org-mode file which might have
805 been invisible before. When this is set, the text below the headline that is
806 exposed is also shown.
808 By default this is off for all contexts.
809 Instead of t, this can also be an alist specifying this option for different
810 contexts. See `org-show-hierarchy-above' for valid contexts."
811 :group 'org-reveal-location
812 :type org-context-choice)
814 (defcustom org-indirect-buffer-display 'other-window
815 "How should indirect tree buffers be displayed?
816 This applies to indirect buffers created with the commands
817 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
818 Valid values are:
819 current-window Display in the current window
820 other-window Just display in another window.
821 dedicated-frame Create one new frame, and re-use it each time.
822 new-frame Make a new frame each time. Note that in this case
823 previously-made indirect buffers are kept, and you need to
824 kill these buffers yourself."
825 :group 'org-structure
826 :group 'org-agenda-windows
827 :type '(choice
828 (const :tag "In current window" current-window)
829 (const :tag "In current frame, other window" other-window)
830 (const :tag "Each time a new frame" new-frame)
831 (const :tag "One dedicated frame" dedicated-frame)))
833 (defcustom org-use-speed-commands nil
834 "Non-nil means activate single letter commands at beginning of a headline.
835 This may also be a function to test for appropriate locations where speed
836 commands should be active."
837 :group 'org-structure
838 :type '(choice
839 (const :tag "Never" nil)
840 (const :tag "At beginning of headline stars" t)
841 (function)))
843 (defcustom org-speed-commands-user nil
844 "Alist of additional speed commands.
845 This list will be checked before `org-speed-commands-default'
846 when the variable `org-use-speed-commands' is non-nil
847 and when the cursor is at the beginning of a headline.
848 The car if each entry is a string with a single letter, which must
849 be assigned to `self-insert-command' in the global map.
850 The cdr is either a command to be called interactively, a function
851 to be called, or a form to be evaluated.
852 An entry that is just a list with a single string will be interpreted
853 as a descriptive headline that will be added when listing the speed
854 commands in the Help buffer using the `?' speed command."
855 :group 'org-structure
856 :type '(repeat :value ("k" . ignore)
857 (choice :value ("k" . ignore)
858 (list :tag "Descriptive Headline" (string :tag "Headline"))
859 (cons :tag "Letter and Command"
860 (string :tag "Command letter")
861 (choice
862 (function)
863 (sexp))))))
865 (defgroup org-cycle nil
866 "Options concerning visibility cycling in Org-mode."
867 :tag "Org Cycle"
868 :group 'org-structure)
870 (defcustom org-cycle-skip-children-state-if-no-children t
871 "Non-nil means skip CHILDREN state in entries that don't have any."
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-max-level nil
876 "Maximum level which should still be subject to visibility cycling.
877 Levels higher than this will, for cycling, be treated as text, not a headline.
878 When `org-odd-levels-only' is set, a value of N in this variable actually
879 means 2N-1 stars as the limiting headline.
880 When nil, cycle all levels.
881 Note that the limiting level of cycling is also influenced by
882 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
883 `org-inlinetask-min-level' is, cycling will be limited to levels one less
884 than its value."
885 :group 'org-cycle
886 :type '(choice
887 (const :tag "No limit" nil)
888 (integer :tag "Maximum level")))
890 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
891 "Names of drawers. Drawers are not opened by cycling on the headline above.
892 Drawers only open with a TAB on the drawer line itself. A drawer looks like
893 this:
894 :DRAWERNAME:
895 .....
896 :END:
897 The drawer \"PROPERTIES\" is special for capturing properties through
898 the property API.
900 Drawers can be defined on the per-file basis with a line like:
902 #+DRAWERS: HIDDEN STATE PROPERTIES"
903 :group 'org-structure
904 :group 'org-cycle
905 :type '(repeat (string :tag "Drawer Name")))
907 (defcustom org-hide-block-startup nil
908 "Non-nil means entering Org-mode will fold all blocks.
909 This can also be set in on a per-file basis with
911 #+STARTUP: hideblocks
912 #+STARTUP: showblocks"
913 :group 'org-startup
914 :group 'org-cycle
915 :type 'boolean)
917 (defcustom org-cycle-global-at-bob nil
918 "Cycle globally if cursor is at beginning of buffer and not at a headline.
919 This makes it possible to do global cycling without having to use S-TAB or
920 \\[universal-argument] TAB. For this special case to work, the first line
921 of the buffer must not be a headline -- it may be empty or some other text.
922 When used in this way, `org-cycle-hook' is disabled temporarily to make
923 sure the cursor stays at the beginning of the buffer. When this option is
924 nil, don't do anything special at the beginning of the buffer."
925 :group 'org-cycle
926 :type 'boolean)
928 (defcustom org-cycle-level-after-item/entry-creation t
929 "Non-nil means cycle entry level or item indentation in new empty entries.
931 When the cursor is at the end of an empty headline, i.e with only stars
932 and maybe a TODO keyword, TAB will then switch the entry to become a child,
933 and then all possible ancestor states, before returning to the original state.
934 This makes data entry extremely fast: M-RET to create a new headline,
935 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
937 When the cursor is at the end of an empty plain list item, one TAB will
938 make it a subitem, two or more tabs will back up to make this an item
939 higher up in the item hierarchy."
940 :group 'org-cycle
941 :type 'boolean)
943 (defcustom org-cycle-emulate-tab t
944 "Where should `org-cycle' emulate TAB.
945 nil Never
946 white Only in completely white lines
947 whitestart Only at the beginning of lines, before the first non-white char
948 t Everywhere except in headlines
949 exc-hl-bol Everywhere except at the start of a headline
950 If TAB is used in a place where it does not emulate TAB, the current subtree
951 visibility is cycled."
952 :group 'org-cycle
953 :type '(choice (const :tag "Never" nil)
954 (const :tag "Only in completely white lines" white)
955 (const :tag "Before first char in a line" whitestart)
956 (const :tag "Everywhere except in headlines" t)
957 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
960 (defcustom org-cycle-separator-lines 2
961 "Number of empty lines needed to keep an empty line between collapsed trees.
962 If you leave an empty line between the end of a subtree and the following
963 headline, this empty line is hidden when the subtree is folded.
964 Org-mode will leave (exactly) one empty line visible if the number of
965 empty lines is equal or larger to the number given in this variable.
966 So the default 2 means at least 2 empty lines after the end of a subtree
967 are needed to produce free space between a collapsed subtree and the
968 following headline.
970 If the number is negative, and the number of empty lines is at least -N,
971 all empty lines are shown.
973 Special case: when 0, never leave empty lines in collapsed view."
974 :group 'org-cycle
975 :type 'integer)
976 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
978 (defcustom org-pre-cycle-hook nil
979 "Hook that is run before visibility cycling is happening.
980 The function(s) in this hook must accept a single argument which indicates
981 the new state that will be set right after running this hook. The
982 argument is a symbol. Before a global state change, it can have the values
983 `overview', `content', or `all'. Before a local state change, it can have
984 the values `folded', `children', or `subtree'."
985 :group 'org-cycle
986 :type 'hook)
988 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
989 org-cycle-hide-drawers
990 org-cycle-show-empty-lines
991 org-optimize-window-after-visibility-change)
992 "Hook that is run after `org-cycle' has changed the buffer visibility.
993 The function(s) in this hook must accept a single argument which indicates
994 the new state that was set by the most recent `org-cycle' command. The
995 argument is a symbol. After a global state change, it can have the values
996 `overview', `contents', or `all'. After a local state change, it can have
997 the values `folded', `children', or `subtree'."
998 :group 'org-cycle
999 :type 'hook)
1001 (defgroup org-edit-structure nil
1002 "Options concerning structure editing in Org-mode."
1003 :tag "Org Edit Structure"
1004 :group 'org-structure)
1006 (defcustom org-odd-levels-only nil
1007 "Non-nil means skip even levels and only use odd levels for the outline.
1008 This has the effect that two stars are being added/taken away in
1009 promotion/demotion commands. It also influences how levels are
1010 handled by the exporters.
1011 Changing it requires restart of `font-lock-mode' to become effective
1012 for fontification also in regions already fontified.
1013 You may also set this on a per-file basis by adding one of the following
1014 lines to the buffer:
1016 #+STARTUP: odd
1017 #+STARTUP: oddeven"
1018 :group 'org-edit-structure
1019 :group 'org-appearance
1020 :type 'boolean)
1022 (defcustom org-adapt-indentation t
1023 "Non-nil means adapt indentation to outline node level.
1025 When this variable is set, Org assumes that you write outlines by
1026 indenting text in each node to align with the headline (after the stars).
1027 The following issues are influenced by this variable:
1029 - When this is set and the *entire* text in an entry is indented, the
1030 indentation is increased by one space in a demotion command, and
1031 decreased by one in a promotion command. If any line in the entry
1032 body starts with text at column 0, indentation is not changed at all.
1034 - Property drawers and planning information is inserted indented when
1035 this variable s set. When nil, they will not be indented.
1037 - TAB indents a line relative to context. The lines below a headline
1038 will be indented when this variable is set.
1040 Note that this is all about true indentation, by adding and removing
1041 space characters. See also `org-indent.el' which does level-dependent
1042 indentation in a virtual way, i.e. at display time in Emacs."
1043 :group 'org-edit-structure
1044 :type 'boolean)
1046 (defcustom org-special-ctrl-a/e nil
1047 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1049 When t, `C-a' will bring back the cursor to the beginning of the
1050 headline text, i.e. after the stars and after a possible TODO
1051 keyword. In an item, this will be the position after bullet and
1052 check-box, if any. When the cursor is already at that position,
1053 another `C-a' will bring it to the beginning of the line.
1055 `C-e' will jump to the end of the headline, ignoring the presence
1056 of tags in the headline. A second `C-e' will then jump to the
1057 true end of the line, after any tags. This also means that, when
1058 this variable is non-nil, `C-e' also will never jump beyond the
1059 end of the heading of a folded section, i.e. not after the
1060 ellipses.
1062 When set to the symbol `reversed', the first `C-a' or `C-e' works
1063 normally, going to the true line boundary first. Only a directly
1064 following, identical keypress will bring the cursor to the
1065 special positions.
1067 This may also be a cons cell where the behavior for `C-a' and
1068 `C-e' is set separately."
1069 :group 'org-edit-structure
1070 :type '(choice
1071 (const :tag "off" nil)
1072 (const :tag "on: after stars/bullet and before tags first" t)
1073 (const :tag "reversed: true line boundary first" reversed)
1074 (cons :tag "Set C-a and C-e separately"
1075 (choice :tag "Special C-a"
1076 (const :tag "off" nil)
1077 (const :tag "on: after stars/bullet first" t)
1078 (const :tag "reversed: before stars/bullet first" reversed))
1079 (choice :tag "Special C-e"
1080 (const :tag "off" nil)
1081 (const :tag "on: before tags first" t)
1082 (const :tag "reversed: after tags first" reversed)))))
1083 (if (fboundp 'defvaralias)
1084 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1086 (defcustom org-special-ctrl-k nil
1087 "Non-nil means `C-k' will behave specially in headlines.
1088 When nil, `C-k' will call the default `kill-line' command.
1089 When t, the following will happen while the cursor is in the headline:
1091 - When the cursor is at the beginning of a headline, kill the entire
1092 line and possible the folded subtree below the line.
1093 - When in the middle of the headline text, kill the headline up to the tags.
1094 - When after the headline text, kill the tags."
1095 :group 'org-edit-structure
1096 :type 'boolean)
1098 (defcustom org-ctrl-k-protect-subtree nil
1099 "Non-nil means, do not delete a hidden subtree with C-k.
1100 When set to the symbol `error', simply throw an error when C-k is
1101 used to kill (part-of) a headline that has hidden text behind it.
1102 Any other non-nil value will result in a query to the user, if it is
1103 OK to kill that hidden subtree. When nil, kill without remorse."
1104 :group 'org-edit-structure
1105 :version "24.1"
1106 :type '(choice
1107 (const :tag "Do not protect hidden subtrees" nil)
1108 (const :tag "Protect hidden subtrees with a security query" t)
1109 (const :tag "Never kill a hidden subtree with C-k" error)))
1111 (defcustom org-catch-invisible-edits nil
1112 "Check if in invisible region before inserting or deleting a character.
1113 Valid values are:
1115 nil Do not check, so just do invisible edits.
1116 error Throw an error and do nothing.
1117 show Make point visible, and do the requested edit.
1118 show-and-error Make point visible, then throw an error and abort the edit.
1119 smart Make point visible, and do insertion/deletion if it is
1120 adjacent to visible text and the change feels predictable.
1121 Never delete a previously invisible character or add in the
1122 middle or right after an invisible region. Basically, this
1123 allows insertion and backward-delete right before ellipses.
1124 FIXME: maybe in this case we should not even show?"
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not check" nil)
1129 (const :tag "Throw error when trying to edit" error)
1130 (const :tag "Unhide, but do not do the edit" show-and-error)
1131 (const :tag "Show invisible part and do the edit" show)
1132 (const :tag "Be smart and do the right thing" smart)))
1134 (defcustom org-yank-folded-subtrees t
1135 "Non-nil means when yanking subtrees, fold them.
1136 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1137 it starts with a heading and all other headings in it are either children
1138 or siblings, then fold all the subtrees. However, do this only if no
1139 text after the yank would be swallowed into a folded tree by this action."
1140 :group 'org-edit-structure
1141 :type 'boolean)
1143 (defcustom org-yank-adjusted-subtrees nil
1144 "Non-nil means when yanking subtrees, adjust the level.
1145 With this setting, `org-paste-subtree' is used to insert the subtree, see
1146 this function for details."
1147 :group 'org-edit-structure
1148 :type 'boolean)
1150 (defcustom org-M-RET-may-split-line '((default . t))
1151 "Non-nil means M-RET will split the line at the cursor position.
1152 When nil, it will go to the end of the line before making a
1153 new line.
1154 You may also set this option in a different way for different
1155 contexts. Valid contexts are:
1157 headline when creating a new headline
1158 item when creating a new item
1159 table in a table field
1160 default the value to be used for all contexts not explicitly
1161 customized"
1162 :group 'org-structure
1163 :group 'org-table
1164 :type '(choice
1165 (const :tag "Always" t)
1166 (const :tag "Never" nil)
1167 (repeat :greedy t :tag "Individual contexts"
1168 (cons
1169 (choice :tag "Context"
1170 (const headline)
1171 (const item)
1172 (const table)
1173 (const default))
1174 (boolean)))))
1177 (defcustom org-insert-heading-respect-content nil
1178 "Non-nil means insert new headings after the current subtree.
1179 When nil, the new heading is created directly after the current line.
1180 The commands \\[org-insert-heading-respect-content] and
1181 \\[org-insert-todo-heading-respect-content] turn this variable on
1182 for the duration of the command."
1183 :group 'org-structure
1184 :type 'boolean)
1186 (defcustom org-blank-before-new-entry '((heading . auto)
1187 (plain-list-item . auto))
1188 "Should `org-insert-heading' leave a blank line before new heading/item?
1189 The value is an alist, with `heading' and `plain-list-item' as CAR,
1190 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1191 which case Org will look at the surrounding headings/items and try to
1192 make an intelligent decision whether to insert a blank line or not.
1194 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1195 set, the setting here is ignored and no empty line is inserted, to avoid
1196 breaking the list structure."
1197 :group 'org-edit-structure
1198 :type '(list
1199 (cons (const heading)
1200 (choice (const :tag "Never" nil)
1201 (const :tag "Always" t)
1202 (const :tag "Auto" auto)))
1203 (cons (const plain-list-item)
1204 (choice (const :tag "Never" nil)
1205 (const :tag "Always" t)
1206 (const :tag "Auto" auto)))))
1208 (defcustom org-insert-heading-hook nil
1209 "Hook being run after inserting a new heading."
1210 :group 'org-edit-structure
1211 :type 'hook)
1213 (defcustom org-enable-fixed-width-editor t
1214 "Non-nil means lines starting with \":\" are treated as fixed-width.
1215 This currently only means they are never auto-wrapped.
1216 When nil, such lines will be treated like ordinary lines.
1217 See also the QUOTE keyword."
1218 :group 'org-edit-structure
1219 :type 'boolean)
1221 (defcustom org-goto-auto-isearch t
1222 "Non-nil means typing characters in `org-goto' starts incremental search."
1223 :group 'org-edit-structure
1224 :type 'boolean)
1226 (defgroup org-sparse-trees nil
1227 "Options concerning sparse trees in Org-mode."
1228 :tag "Org Sparse Trees"
1229 :group 'org-structure)
1231 (defcustom org-highlight-sparse-tree-matches t
1232 "Non-nil means highlight all matches that define a sparse tree.
1233 The highlights will automatically disappear the next time the buffer is
1234 changed by an edit command."
1235 :group 'org-sparse-trees
1236 :type 'boolean)
1238 (defcustom org-remove-highlights-with-change t
1239 "Non-nil means any change to the buffer will remove temporary highlights.
1240 Such highlights are created by `org-occur' and `org-clock-display'.
1241 When nil, `C-c C-c needs to be used to get rid of the highlights.
1242 The highlights created by `org-preview-latex-fragment' always need
1243 `C-c C-c' to be removed."
1244 :group 'org-sparse-trees
1245 :group 'org-time
1246 :type 'boolean)
1249 (defcustom org-occur-hook '(org-first-headline-recenter)
1250 "Hook that is run after `org-occur' has constructed a sparse tree.
1251 This can be used to recenter the window to show as much of the structure
1252 as possible."
1253 :group 'org-sparse-trees
1254 :type 'hook)
1256 (defgroup org-imenu-and-speedbar nil
1257 "Options concerning imenu and speedbar in Org-mode."
1258 :tag "Org Imenu and Speedbar"
1259 :group 'org-structure)
1261 (defcustom org-imenu-depth 2
1262 "The maximum level for Imenu access to Org-mode headlines.
1263 This also applied for speedbar access."
1264 :group 'org-imenu-and-speedbar
1265 :type 'integer)
1267 (defgroup org-table nil
1268 "Options concerning tables in Org-mode."
1269 :tag "Org Table"
1270 :group 'org)
1272 (defcustom org-enable-table-editor 'optimized
1273 "Non-nil means lines starting with \"|\" are handled by the table editor.
1274 When nil, such lines will be treated like ordinary lines.
1276 When equal to the symbol `optimized', the table editor will be optimized to
1277 do the following:
1278 - Automatic overwrite mode in front of whitespace in table fields.
1279 This makes the structure of the table stay in tact as long as the edited
1280 field does not exceed the column width.
1281 - Minimize the number of realigns. Normally, the table is aligned each time
1282 TAB or RET are pressed to move to another field. With optimization this
1283 happens only if changes to a field might have changed the column width.
1284 Optimization requires replacing the functions `self-insert-command',
1285 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1286 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1287 very good at guessing when a re-align will be necessary, but you can always
1288 force one with \\[org-ctrl-c-ctrl-c].
1290 If you would like to use the optimized version in Org-mode, but the
1291 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1293 This variable can be used to turn on and off the table editor during a session,
1294 but in order to toggle optimization, a restart is required.
1296 See also the variable `org-table-auto-blank-field'."
1297 :group 'org-table
1298 :type '(choice
1299 (const :tag "off" nil)
1300 (const :tag "on" t)
1301 (const :tag "on, optimized" optimized)))
1303 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1304 (version<= emacs-version "24.1"))
1305 "Non-nil means cluster self-insert commands for undo when possible.
1306 If this is set, then, like in the Emacs command loop, 20 consecutive
1307 characters will be undone together.
1308 This is configurable, because there is some impact on typing performance."
1309 :group 'org-table
1310 :type 'boolean)
1312 (defcustom org-table-tab-recognizes-table.el t
1313 "Non-nil means TAB will automatically notice a table.el table.
1314 When it sees such a table, it moves point into it and - if necessary -
1315 calls `table-recognize-table'."
1316 :group 'org-table-editing
1317 :type 'boolean)
1319 (defgroup org-link nil
1320 "Options concerning links in Org-mode."
1321 :tag "Org Link"
1322 :group 'org)
1324 (defvar org-link-abbrev-alist-local nil
1325 "Buffer-local version of `org-link-abbrev-alist', which see.
1326 The value of this is taken from the #+LINK lines.")
1327 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1329 (defcustom org-link-abbrev-alist nil
1330 "Alist of link abbreviations.
1331 The car of each element is a string, to be replaced at the start of a link.
1332 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1333 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1335 [[linkkey:tag][description]]
1337 The 'linkkey' must be a word word, starting with a letter, followed
1338 by letters, numbers, '-' or '_'.
1340 If REPLACE is a string, the tag will simply be appended to create the link.
1341 If the string contains \"%s\", the tag will be inserted there. If the string
1342 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1343 at that point (see the function `url-hexify-string'). If the string contains
1344 the specifier \"%(my-function)\", then the custom function `my-function' will
1345 be invoked: this function takes the tag as its only argument and must return
1346 a string.
1348 REPLACE may also be a function that will be called with the tag as the
1349 only argument to create the link, which should be returned as a string.
1351 See the manual for examples."
1352 :group 'org-link
1353 :type '(repeat
1354 (cons
1355 (string :tag "Protocol")
1356 (choice
1357 (string :tag "Format")
1358 (function)))))
1360 (defcustom org-descriptive-links t
1361 "Non-nil means Org will display descriptive links.
1362 E.g. [[http://orgmode.org][Org website]] will be displayed as
1363 \"Org Website\", hiding the link itself and just displaying its
1364 description. When set to `nil', Org will display the full links
1365 literally.
1367 You can interactively set the value of this variable by calling
1368 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1369 :group 'org-link
1370 :type 'boolean)
1372 (defcustom org-link-file-path-type 'adaptive
1373 "How the path name in file links should be stored.
1374 Valid values are:
1376 relative Relative to the current directory, i.e. the directory of the file
1377 into which the link is being inserted.
1378 absolute Absolute path, if possible with ~ for home directory.
1379 noabbrev Absolute path, no abbreviation of home directory.
1380 adaptive Use relative path for files in the current directory and sub-
1381 directories of it. For other files, use an absolute path."
1382 :group 'org-link
1383 :type '(choice
1384 (const relative)
1385 (const absolute)
1386 (const noabbrev)
1387 (const adaptive)))
1389 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1390 "Types of links that should be activated in Org-mode files.
1391 This is a list of symbols, each leading to the activation of a certain link
1392 type. In principle, it does not hurt to turn on most link types - there may
1393 be a small gain when turning off unused link types. The types are:
1395 bracket The recommended [[link][description]] or [[link]] links with hiding.
1396 angle Links in angular brackets that may contain whitespace like
1397 <bbdb:Carsten Dominik>.
1398 plain Plain links in normal text, no whitespace, like http://google.com.
1399 radio Text that is matched by a radio target, see manual for details.
1400 tag Tag settings in a headline (link to tag search).
1401 date Time stamps (link to calendar).
1402 footnote Footnote labels.
1404 Changing this variable requires a restart of Emacs to become effective."
1405 :group 'org-link
1406 :type '(set :greedy t
1407 (const :tag "Double bracket links" bracket)
1408 (const :tag "Angular bracket links" angle)
1409 (const :tag "Plain text links" plain)
1410 (const :tag "Radio target matches" radio)
1411 (const :tag "Tags" tag)
1412 (const :tag "Timestamps" date)
1413 (const :tag "Footnotes" footnote)))
1415 (defcustom org-make-link-description-function nil
1416 "Function to use for generating link descriptions from links.
1417 When nil, the link location will be used. This function must take
1418 two parameters: the first one is the link, the second one is the
1419 description generated by `org-insert-link'. The function should
1420 return the description to use."
1421 :group 'org-link
1422 :type 'function)
1424 (defgroup org-link-store nil
1425 "Options concerning storing links in Org-mode."
1426 :tag "Org Store Link"
1427 :group 'org-link)
1429 (defcustom org-url-hexify-p t
1430 "When non-nil, hexify URL when creating a link."
1431 :type 'boolean
1432 :version "24.3"
1433 :group 'org-link-store)
1435 (defcustom org-email-link-description-format "Email %c: %.30s"
1436 "Format of the description part of a link to an email or usenet message.
1437 The following %-escapes will be replaced by corresponding information:
1439 %F full \"From\" field
1440 %f name, taken from \"From\" field, address if no name
1441 %T full \"To\" field
1442 %t first name in \"To\" field, address if no name
1443 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1444 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1445 %s subject
1446 %d date
1447 %m message-id.
1449 You may use normal field width specification between the % and the letter.
1450 This is for example useful to limit the length of the subject.
1452 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1453 :group 'org-link-store
1454 :type 'string)
1456 (defcustom org-from-is-user-regexp
1457 (let (r1 r2)
1458 (when (and user-mail-address (not (string= user-mail-address "")))
1459 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1460 (when (and user-full-name (not (string= user-full-name "")))
1461 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1462 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1463 "Regexp matched against the \"From:\" header of an email or usenet message.
1464 It should match if the message is from the user him/herself."
1465 :group 'org-link-store
1466 :type 'regexp)
1468 (defcustom org-context-in-file-links t
1469 "Non-nil means file links from `org-store-link' contain context.
1470 A search string will be added to the file name with :: as separator and
1471 used to find the context when the link is activated by the command
1472 `org-open-at-point'. When this option is t, the entire active region
1473 will be placed in the search string of the file link. If set to a
1474 positive integer, only the first n lines of context will be stored.
1476 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1477 negates this setting for the duration of the command."
1478 :group 'org-link-store
1479 :type '(choice boolean integer))
1481 (defcustom org-keep-stored-link-after-insertion nil
1482 "Non-nil means keep link in list for entire session.
1484 The command `org-store-link' adds a link pointing to the current
1485 location to an internal list. These links accumulate during a session.
1486 The command `org-insert-link' can be used to insert links into any
1487 Org-mode file (offering completion for all stored links). When this
1488 option is nil, every link which has been inserted once using \\[org-insert-link]
1489 will be removed from the list, to make completing the unused links
1490 more efficient."
1491 :group 'org-link-store
1492 :type 'boolean)
1494 (defgroup org-link-follow nil
1495 "Options concerning following links in Org-mode."
1496 :tag "Org Follow Link"
1497 :group 'org-link)
1499 (defcustom org-link-translation-function nil
1500 "Function to translate links with different syntax to Org syntax.
1501 This can be used to translate links created for example by the Planner
1502 or emacs-wiki packages to Org syntax.
1503 The function must accept two parameters, a TYPE containing the link
1504 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1505 which is everything after the link protocol. It should return a cons
1506 with possibly modified values of type and path.
1507 Org contains a function for this, so if you set this variable to
1508 `org-translate-link-from-planner', you should be able follow many
1509 links created by planner."
1510 :group 'org-link-follow
1511 :type 'function)
1513 (defcustom org-follow-link-hook nil
1514 "Hook that is run after a link has been followed."
1515 :group 'org-link-follow
1516 :type 'hook)
1518 (defcustom org-tab-follows-link nil
1519 "Non-nil means on links TAB will follow the link.
1520 Needs to be set before org.el is loaded.
1521 This really should not be used, it does not make sense, and the
1522 implementation is bad."
1523 :group 'org-link-follow
1524 :type 'boolean)
1526 (defcustom org-return-follows-link nil
1527 "Non-nil means on links RET will follow the link."
1528 :group 'org-link-follow
1529 :type 'boolean)
1531 (defcustom org-mouse-1-follows-link
1532 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1533 "Non-nil means mouse-1 on a link will follow the link.
1534 A longer mouse click will still set point. Does not work on XEmacs.
1535 Needs to be set before org.el is loaded."
1536 :group 'org-link-follow
1537 :type 'boolean)
1539 (defcustom org-mark-ring-length 4
1540 "Number of different positions to be recorded in the ring.
1541 Changing this requires a restart of Emacs to work correctly."
1542 :group 'org-link-follow
1543 :type 'integer)
1545 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1546 "Non-nil means internal links in Org files must exactly match a headline.
1547 When nil, the link search tries to match a phrase with all words
1548 in the search text."
1549 :group 'org-link-follow
1550 :version "24.1"
1551 :type '(choice
1552 (const :tag "Use fuzzy text search" nil)
1553 (const :tag "Match only exact headline" t)
1554 (const :tag "Match exact headline or query to create it"
1555 query-to-create)))
1557 (defcustom org-link-frame-setup
1558 '((vm . vm-visit-folder-other-frame)
1559 (vm-imap . vm-visit-imap-folder-other-frame)
1560 (gnus . org-gnus-no-new-news)
1561 (file . find-file-other-window)
1562 (wl . wl-other-frame))
1563 "Setup the frame configuration for following links.
1564 When following a link with Emacs, it may often be useful to display
1565 this link in another window or frame. This variable can be used to
1566 set this up for the different types of links.
1567 For VM, use any of
1568 `vm-visit-folder'
1569 `vm-visit-folder-other-window'
1570 `vm-visit-folder-other-frame'
1571 For Gnus, use any of
1572 `gnus'
1573 `gnus-other-frame'
1574 `org-gnus-no-new-news'
1575 For FILE, use any of
1576 `find-file'
1577 `find-file-other-window'
1578 `find-file-other-frame'
1579 For Wanderlust use any of
1580 `wl'
1581 `wl-other-frame'
1582 For the calendar, use the variable `calendar-setup'.
1583 For BBDB, it is currently only possible to display the matches in
1584 another window."
1585 :group 'org-link-follow
1586 :type '(list
1587 (cons (const vm)
1588 (choice
1589 (const vm-visit-folder)
1590 (const vm-visit-folder-other-window)
1591 (const vm-visit-folder-other-frame)))
1592 (cons (const gnus)
1593 (choice
1594 (const gnus)
1595 (const gnus-other-frame)
1596 (const org-gnus-no-new-news)))
1597 (cons (const file)
1598 (choice
1599 (const find-file)
1600 (const find-file-other-window)
1601 (const find-file-other-frame)))
1602 (cons (const wl)
1603 (choice
1604 (const wl)
1605 (const wl-other-frame)))))
1607 (defcustom org-display-internal-link-with-indirect-buffer nil
1608 "Non-nil means use indirect buffer to display infile links.
1609 Activating internal links (from one location in a file to another location
1610 in the same file) normally just jumps to the location. When the link is
1611 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1612 is displayed in
1613 another window. When this option is set, the other window actually displays
1614 an indirect buffer clone of the current buffer, to avoid any visibility
1615 changes to the current buffer."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-open-non-existing-files nil
1620 "Non-nil means `org-open-file' will open non-existing files.
1621 When nil, an error will be generated.
1622 This variable applies only to external applications because they
1623 might choke on non-existing files. If the link is to a file that
1624 will be opened in Emacs, the variable is ignored."
1625 :group 'org-link-follow
1626 :type 'boolean)
1628 (defcustom org-open-directory-means-index-dot-org nil
1629 "Non-nil means a link to a directory really means to index.org.
1630 When nil, following a directory link will run dired or open a finder/explorer
1631 window on that directory."
1632 :group 'org-link-follow
1633 :type 'boolean)
1635 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1636 "Function and arguments to call for following mailto links.
1637 This is a list with the first element being a Lisp function, and the
1638 remaining elements being arguments to the function. In string arguments,
1639 %a will be replaced by the address, and %s will be replaced by the subject
1640 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1641 :group 'org-link-follow
1642 :type '(choice
1643 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1644 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1645 (const :tag "message-mail" (message-mail "%a" "%s"))
1646 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1648 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1649 "Non-nil means ask for confirmation before executing shell links.
1650 Shell links can be dangerous: just think about a link
1652 [[shell:rm -rf ~/*][Google Search]]
1654 This link would show up in your Org-mode document as \"Google Search\",
1655 but really it would remove your entire home directory.
1656 Therefore we advise against setting this variable to nil.
1657 Just change it to `y-or-n-p' if you want to confirm with a
1658 single keystroke rather than having to type \"yes\"."
1659 :group 'org-link-follow
1660 :type '(choice
1661 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1662 (const :tag "with y-or-n (faster)" y-or-n-p)
1663 (const :tag "no confirmation (dangerous)" nil)))
1664 (put 'org-confirm-shell-link-function
1665 'safe-local-variable
1666 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1668 (defcustom org-confirm-shell-link-not-regexp ""
1669 "A regexp to skip confirmation for shell links."
1670 :group 'org-link-follow
1671 :version "24.1"
1672 :type 'regexp)
1674 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1675 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1676 Elisp links can be dangerous: just think about a link
1678 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1680 This link would show up in your Org-mode document as \"Google Search\",
1681 but really it would remove your entire home directory.
1682 Therefore we advise against setting this variable to nil.
1683 Just change it to `y-or-n-p' if you want to confirm with a
1684 single keystroke rather than having to type \"yes\"."
1685 :group 'org-link-follow
1686 :type '(choice
1687 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1688 (const :tag "with y-or-n (faster)" y-or-n-p)
1689 (const :tag "no confirmation (dangerous)" nil)))
1690 (put 'org-confirm-shell-link-function
1691 'safe-local-variable
1692 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1694 (defcustom org-confirm-elisp-link-not-regexp ""
1695 "A regexp to skip confirmation for Elisp links."
1696 :group 'org-link-follow
1697 :version "24.1"
1698 :type 'regexp)
1700 (defconst org-file-apps-defaults-gnu
1701 '((remote . emacs)
1702 (system . mailcap)
1703 (t . mailcap))
1704 "Default file applications on a UNIX or GNU/Linux system.
1705 See `org-file-apps'.")
1707 (defconst org-file-apps-defaults-macosx
1708 '((remote . emacs)
1709 (t . "open %s")
1710 (system . "open %s")
1711 ("ps.gz" . "gv %s")
1712 ("eps.gz" . "gv %s")
1713 ("dvi" . "xdvi %s")
1714 ("fig" . "xfig %s"))
1715 "Default file applications on a MacOS X system.
1716 The system \"open\" is known as a default, but we use X11 applications
1717 for some files for which the OS does not have a good default.
1718 See `org-file-apps'.")
1720 (defconst org-file-apps-defaults-windowsnt
1721 (list
1722 '(remote . emacs)
1723 (cons t
1724 (list (if (featurep 'xemacs)
1725 'mswindows-shell-execute
1726 'w32-shell-execute)
1727 "open" 'file))
1728 (cons 'system
1729 (list (if (featurep 'xemacs)
1730 'mswindows-shell-execute
1731 'w32-shell-execute)
1732 "open" 'file)))
1733 "Default file applications on a Windows NT system.
1734 The system \"open\" is used for most files.
1735 See `org-file-apps'.")
1737 (defcustom org-file-apps
1739 (auto-mode . emacs)
1740 ("\\.mm\\'" . default)
1741 ("\\.x?html?\\'" . default)
1742 ("\\.pdf\\'" . default)
1744 "External applications for opening `file:path' items in a document.
1745 Org-mode uses system defaults for different file types, but
1746 you can use this variable to set the application for a given file
1747 extension. The entries in this list are cons cells where the car identifies
1748 files and the cdr the corresponding command. Possible values for the
1749 file identifier are
1750 \"string\" A string as a file identifier can be interpreted in different
1751 ways, depending on its contents:
1753 - Alphanumeric characters only:
1754 Match links with this file extension.
1755 Example: (\"pdf\" . \"evince %s\")
1756 to open PDFs with evince.
1758 - Regular expression: Match links where the
1759 filename matches the regexp. If you want to
1760 use groups here, use shy groups.
1762 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1763 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1764 to open *.html and *.xhtml with firefox.
1766 - Regular expression which contains (non-shy) groups:
1767 Match links where the whole link, including \"::\", and
1768 anything after that, matches the regexp.
1769 In a custom command string, %1, %2, etc. are replaced with
1770 the parts of the link that were matched by the groups.
1771 For backwards compatibility, if a command string is given
1772 that does not use any of the group matches, this case is
1773 handled identically to the second one (i.e. match against
1774 file name only).
1775 In a custom lisp form, you can access the group matches with
1776 (match-string n link).
1778 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1779 to open [[file:document.pdf::5]] with evince at page 5.
1781 `directory' Matches a directory
1782 `remote' Matches a remote file, accessible through tramp or efs.
1783 Remote files most likely should be visited through Emacs
1784 because external applications cannot handle such paths.
1785 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1786 so all files Emacs knows how to handle. Using this with
1787 command `emacs' will open most files in Emacs. Beware that this
1788 will also open html files inside Emacs, unless you add
1789 (\"html\" . default) to the list as well.
1790 t Default for files not matched by any of the other options.
1791 `system' The system command to open files, like `open' on Windows
1792 and Mac OS X, and mailcap under GNU/Linux. This is the command
1793 that will be selected if you call `C-c C-o' with a double
1794 \\[universal-argument] \\[universal-argument] prefix.
1796 Possible values for the command are:
1797 `emacs' The file will be visited by the current Emacs process.
1798 `default' Use the default application for this file type, which is the
1799 association for t in the list, most likely in the system-specific
1800 part.
1801 This can be used to overrule an unwanted setting in the
1802 system-specific variable.
1803 `system' Use the system command for opening files, like \"open\".
1804 This command is specified by the entry whose car is `system'.
1805 Most likely, the system-specific version of this variable
1806 does define this command, but you can overrule/replace it
1807 here.
1808 string A command to be executed by a shell; %s will be replaced
1809 by the path to the file.
1810 sexp A Lisp form which will be evaluated. The file path will
1811 be available in the Lisp variable `file'.
1812 For more examples, see the system specific constants
1813 `org-file-apps-defaults-macosx'
1814 `org-file-apps-defaults-windowsnt'
1815 `org-file-apps-defaults-gnu'."
1816 :group 'org-link-follow
1817 :type '(repeat
1818 (cons (choice :value ""
1819 (string :tag "Extension")
1820 (const :tag "System command to open files" system)
1821 (const :tag "Default for unrecognized files" t)
1822 (const :tag "Remote file" remote)
1823 (const :tag "Links to a directory" directory)
1824 (const :tag "Any files that have Emacs modes"
1825 auto-mode))
1826 (choice :value ""
1827 (const :tag "Visit with Emacs" emacs)
1828 (const :tag "Use default" default)
1829 (const :tag "Use the system command" system)
1830 (string :tag "Command")
1831 (sexp :tag "Lisp form")))))
1833 (defcustom org-doi-server-url "http://dx.doi.org/"
1834 "The URL of the DOI server."
1835 :type 'string
1836 :version "24.3"
1837 :group 'org-link-follow)
1839 (defgroup org-refile nil
1840 "Options concerning refiling entries in Org-mode."
1841 :tag "Org Refile"
1842 :group 'org)
1844 (defcustom org-directory "~/org"
1845 "Directory with org files.
1846 This is just a default location to look for Org files. There is no need
1847 at all to put your files into this directory. It is only used in the
1848 following situations:
1850 1. When a capture template specifies a target file that is not an
1851 absolute path. The path will then be interpreted relative to
1852 `org-directory'
1853 2. When a capture note is filed away in an interactive way (when exiting the
1854 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1855 with `org-directory' as the default path."
1856 :group 'org-refile
1857 :group 'org-remember
1858 :group 'org-capture
1859 :type 'directory)
1861 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1862 "Default target for storing notes.
1863 Used as a fall back file for org-remember.el and org-capture.el, for
1864 templates that do not specify a target file."
1865 :group 'org-refile
1866 :group 'org-remember
1867 :group 'org-capture
1868 :type '(choice
1869 (const :tag "Default from remember-data-file" nil)
1870 file))
1872 (defcustom org-goto-interface 'outline
1873 "The default interface to be used for `org-goto'.
1874 Allowed values are:
1875 outline The interface shows an outline of the relevant file
1876 and the correct heading is found by moving through
1877 the outline or by searching with incremental search.
1878 outline-path-completion Headlines in the current buffer are offered via
1879 completion. This is the interface also used by
1880 the refile command."
1881 :group 'org-refile
1882 :type '(choice
1883 (const :tag "Outline" outline)
1884 (const :tag "Outline-path-completion" outline-path-completion)))
1886 (defcustom org-goto-max-level 5
1887 "Maximum target level when running `org-goto' with refile interface."
1888 :group 'org-refile
1889 :type 'integer)
1891 (defcustom org-reverse-note-order nil
1892 "Non-nil means store new notes at the beginning of a file or entry.
1893 When nil, new notes will be filed to the end of a file or entry.
1894 This can also be a list with cons cells of regular expressions that
1895 are matched against file names, and values."
1896 :group 'org-remember
1897 :group 'org-capture
1898 :group 'org-refile
1899 :type '(choice
1900 (const :tag "Reverse always" t)
1901 (const :tag "Reverse never" nil)
1902 (repeat :tag "By file name regexp"
1903 (cons regexp boolean))))
1905 (defcustom org-log-refile nil
1906 "Information to record when a task is refiled.
1908 Possible values are:
1910 nil Don't add anything
1911 time Add a time stamp to the task
1912 note Prompt for a note and add it with template `org-log-note-headings'
1914 This option can also be set with on a per-file-basis with
1916 #+STARTUP: nologrefile
1917 #+STARTUP: logrefile
1918 #+STARTUP: lognoterefile
1920 You can have local logging settings for a subtree by setting the LOGGING
1921 property to one or more of these keywords.
1923 When bulk-refiling from the agenda, the value `note' is forbidden and
1924 will temporarily be changed to `time'."
1925 :group 'org-refile
1926 :group 'org-progress
1927 :version "24.1"
1928 :type '(choice
1929 (const :tag "No logging" nil)
1930 (const :tag "Record timestamp" time)
1931 (const :tag "Record timestamp with note." note)))
1933 (defcustom org-refile-targets nil
1934 "Targets for refiling entries with \\[org-refile].
1935 This is a list of cons cells. Each cell contains:
1936 - a specification of the files to be considered, either a list of files,
1937 or a symbol whose function or variable value will be used to retrieve
1938 a file name or a list of file names. If you use `org-agenda-files' for
1939 that, all agenda files will be scanned for targets. Nil means consider
1940 headings in the current buffer.
1941 - A specification of how to find candidate refile targets. This may be
1942 any of:
1943 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1944 This tag has to be present in all target headlines, inheritance will
1945 not be considered.
1946 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1947 todo keyword.
1948 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1949 headlines that are refiling targets.
1950 - a cons cell (:level . N). Any headline of level N is considered a target.
1951 Note that, when `org-odd-levels-only' is set, level corresponds to
1952 order in hierarchy, not to the number of stars.
1953 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1954 Note that, when `org-odd-levels-only' is set, level corresponds to
1955 order in hierarchy, not to the number of stars.
1957 Each element of this list generates a set of possible targets.
1958 The union of these sets is presented (with completion) to
1959 the user by `org-refile'.
1961 You can set the variable `org-refile-target-verify-function' to a function
1962 to verify each headline found by the simple criteria above.
1964 When this variable is nil, all top-level headlines in the current buffer
1965 are used, equivalent to the value `((nil . (:level . 1))'."
1966 :group 'org-refile
1967 :type '(repeat
1968 (cons
1969 (choice :value org-agenda-files
1970 (const :tag "All agenda files" org-agenda-files)
1971 (const :tag "Current buffer" nil)
1972 (function) (variable) (file))
1973 (choice :tag "Identify target headline by"
1974 (cons :tag "Specific tag" (const :value :tag) (string))
1975 (cons :tag "TODO keyword" (const :value :todo) (string))
1976 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1977 (cons :tag "Level number" (const :value :level) (integer))
1978 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1980 (defcustom org-refile-target-verify-function nil
1981 "Function to verify if the headline at point should be a refile target.
1982 The function will be called without arguments, with point at the
1983 beginning of the headline. It should return t and leave point
1984 where it is if the headline is a valid target for refiling.
1986 If the target should not be selected, the function must return nil.
1987 In addition to this, it may move point to a place from where the search
1988 should be continued. For example, the function may decide that the entire
1989 subtree of the current entry should be excluded and move point to the end
1990 of the subtree."
1991 :group 'org-refile
1992 :type 'function)
1994 (defcustom org-refile-use-cache nil
1995 "Non-nil means cache refile targets to speed up the process.
1996 The cache for a particular file will be updated automatically when
1997 the buffer has been killed, or when any of the marker used for flagging
1998 refile targets no longer points at a live buffer.
1999 If you have added new entries to a buffer that might themselves be targets,
2000 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2001 find that easier, `C-u C-u C-u C-c C-w'."
2002 :group 'org-refile
2003 :version "24.1"
2004 :type 'boolean)
2006 (defcustom org-refile-use-outline-path nil
2007 "Non-nil means provide refile targets as paths.
2008 So a level 3 headline will be available as level1/level2/level3.
2010 When the value is `file', also include the file name (without directory)
2011 into the path. In this case, you can also stop the completion after
2012 the file name, to get entries inserted as top level in the file.
2014 When `full-file-path', include the full file path."
2015 :group 'org-refile
2016 :type '(choice
2017 (const :tag "Not" nil)
2018 (const :tag "Yes" t)
2019 (const :tag "Start with file name" file)
2020 (const :tag "Start with full file path" full-file-path)))
2022 (defcustom org-outline-path-complete-in-steps t
2023 "Non-nil means complete the outline path in hierarchical steps.
2024 When Org-mode uses the refile interface to select an outline path
2025 \(see variable `org-refile-use-outline-path'), the completion of
2026 the path can be done is a single go, or if can be done in steps down
2027 the headline hierarchy. Going in steps is probably the best if you
2028 do not use a special completion package like `ido' or `icicles'.
2029 However, when using these packages, going in one step can be very
2030 fast, while still showing the whole path to the entry."
2031 :group 'org-refile
2032 :type 'boolean)
2034 (defcustom org-refile-allow-creating-parent-nodes nil
2035 "Non-nil means allow to create new nodes as refile targets.
2036 New nodes are then created by adding \"/new node name\" to the completion
2037 of an existing node. When the value of this variable is `confirm',
2038 new node creation must be confirmed by the user (recommended)
2039 When nil, the completion must match an existing entry.
2041 Note that, if the new heading is not seen by the criteria
2042 listed in `org-refile-targets', multiple instances of the same
2043 heading would be created by trying again to file under the new
2044 heading."
2045 :group 'org-refile
2046 :type '(choice
2047 (const :tag "Never" nil)
2048 (const :tag "Always" t)
2049 (const :tag "Prompt for confirmation" confirm)))
2051 (defcustom org-refile-active-region-within-subtree nil
2052 "Non-nil means also refile active region within a subtree.
2054 By default `org-refile' doesn't allow refiling regions if they
2055 don't contain a set of subtrees, but it might be convenient to
2056 do so sometimes: in that case, the first line of the region is
2057 converted to a headline before refiling."
2058 :group 'org-refile
2059 :version "24.1"
2060 :type 'boolean)
2062 (defgroup org-todo nil
2063 "Options concerning TODO items in Org-mode."
2064 :tag "Org TODO"
2065 :group 'org)
2067 (defgroup org-progress nil
2068 "Options concerning Progress logging in Org-mode."
2069 :tag "Org Progress"
2070 :group 'org-time)
2072 (defvar org-todo-interpretation-widgets
2073 '((:tag "Sequence (cycling hits every state)" sequence)
2074 (:tag "Type (cycling directly to DONE)" type))
2075 "The available interpretation symbols for customizing `org-todo-keywords'.
2076 Interested libraries should add to this list.")
2078 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2079 "List of TODO entry keyword sequences and their interpretation.
2080 \\<org-mode-map>This is a list of sequences.
2082 Each sequence starts with a symbol, either `sequence' or `type',
2083 indicating if the keywords should be interpreted as a sequence of
2084 action steps, or as different types of TODO items. The first
2085 keywords are states requiring action - these states will select a headline
2086 for inclusion into the global TODO list Org-mode produces. If one of
2087 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2088 signify that no further action is necessary. If \"|\" is not found,
2089 the last keyword is treated as the only DONE state of the sequence.
2091 The command \\[org-todo] cycles an entry through these states, and one
2092 additional state where no keyword is present. For details about this
2093 cycling, see the manual.
2095 TODO keywords and interpretation can also be set on a per-file basis with
2096 the special #+SEQ_TODO and #+TYP_TODO lines.
2098 Each keyword can optionally specify a character for fast state selection
2099 \(in combination with the variable `org-use-fast-todo-selection')
2100 and specifiers for state change logging, using the same syntax that
2101 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2102 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2103 indicates to record a time stamp each time this state is selected.
2105 Each keyword may also specify if a timestamp or a note should be
2106 recorded when entering or leaving the state, by adding additional
2107 characters in the parenthesis after the keyword. This looks like this:
2108 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2109 record only the time of the state change. With X and Y being either
2110 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2111 Y when leaving the state if and only if the *target* state does not
2112 define X. You may omit any of the fast-selection key or X or /Y,
2113 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2115 For backward compatibility, this variable may also be just a list
2116 of keywords. In this case the interpretation (sequence or type) will be
2117 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2118 :group 'org-todo
2119 :group 'org-keywords
2120 :type '(choice
2121 (repeat :tag "Old syntax, just keywords"
2122 (string :tag "Keyword"))
2123 (repeat :tag "New syntax"
2124 (cons
2125 (choice
2126 :tag "Interpretation"
2127 ;;Quick and dirty way to see
2128 ;;`org-todo-interpretations'. This takes the
2129 ;;place of item arguments
2130 :convert-widget
2131 (lambda (widget)
2132 (widget-put widget
2133 :args (mapcar
2134 #'(lambda (x)
2135 (widget-convert
2136 (cons 'const x)))
2137 org-todo-interpretation-widgets))
2138 widget))
2139 (repeat
2140 (string :tag "Keyword"))))))
2142 (defvar org-todo-keywords-1 nil
2143 "All TODO and DONE keywords active in a buffer.")
2144 (make-variable-buffer-local 'org-todo-keywords-1)
2145 (defvar org-todo-keywords-for-agenda nil)
2146 (defvar org-done-keywords-for-agenda nil)
2147 (defvar org-drawers-for-agenda nil)
2148 (defvar org-todo-keyword-alist-for-agenda nil)
2149 (defvar org-tag-alist-for-agenda nil)
2150 (defvar org-agenda-contributing-files nil)
2151 (defvar org-not-done-keywords nil)
2152 (make-variable-buffer-local 'org-not-done-keywords)
2153 (defvar org-done-keywords nil)
2154 (make-variable-buffer-local 'org-done-keywords)
2155 (defvar org-todo-heads nil)
2156 (make-variable-buffer-local 'org-todo-heads)
2157 (defvar org-todo-sets nil)
2158 (make-variable-buffer-local 'org-todo-sets)
2159 (defvar org-todo-log-states nil)
2160 (make-variable-buffer-local 'org-todo-log-states)
2161 (defvar org-todo-kwd-alist nil)
2162 (make-variable-buffer-local 'org-todo-kwd-alist)
2163 (defvar org-todo-key-alist nil)
2164 (make-variable-buffer-local 'org-todo-key-alist)
2165 (defvar org-todo-key-trigger nil)
2166 (make-variable-buffer-local 'org-todo-key-trigger)
2168 (defcustom org-todo-interpretation 'sequence
2169 "Controls how TODO keywords are interpreted.
2170 This variable is in principle obsolete and is only used for
2171 backward compatibility, if the interpretation of todo keywords is
2172 not given already in `org-todo-keywords'. See that variable for
2173 more information."
2174 :group 'org-todo
2175 :group 'org-keywords
2176 :type '(choice (const sequence)
2177 (const type)))
2179 (defcustom org-use-fast-todo-selection t
2180 "Non-nil means use the fast todo selection scheme with C-c C-t.
2181 This variable describes if and under what circumstances the cycling
2182 mechanism for TODO keywords will be replaced by a single-key, direct
2183 selection scheme.
2185 When nil, fast selection is never used.
2187 When the symbol `prefix', it will be used when `org-todo' is called
2188 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2189 `C-u t' in an agenda buffer.
2191 When t, fast selection is used by default. In this case, the prefix
2192 argument forces cycling instead.
2194 In all cases, the special interface is only used if access keys have
2195 actually been assigned by the user, i.e. if keywords in the configuration
2196 are followed by a letter in parenthesis, like TODO(t)."
2197 :group 'org-todo
2198 :type '(choice
2199 (const :tag "Never" nil)
2200 (const :tag "By default" t)
2201 (const :tag "Only with C-u C-c C-t" prefix)))
2203 (defcustom org-provide-todo-statistics t
2204 "Non-nil means update todo statistics after insert and toggle.
2205 ALL-HEADLINES means update todo statistics by including headlines
2206 with no TODO keyword as well, counting them as not done.
2207 A list of TODO keywords means the same, but skip keywords that are
2208 not in this list.
2210 When this is set, todo statistics is updated in the parent of the
2211 current entry each time a todo state is changed."
2212 :group 'org-todo
2213 :type '(choice
2214 (const :tag "Yes, only for TODO entries" t)
2215 (const :tag "Yes, including all entries" 'all-headlines)
2216 (repeat :tag "Yes, for TODOs in this list"
2217 (string :tag "TODO keyword"))
2218 (other :tag "No TODO statistics" nil)))
2220 (defcustom org-hierarchical-todo-statistics t
2221 "Non-nil means TODO statistics covers just direct children.
2222 When nil, all entries in the subtree are considered.
2223 This has only an effect if `org-provide-todo-statistics' is set.
2224 To set this to nil for only a single subtree, use a COOKIE_DATA
2225 property and include the word \"recursive\" into the value."
2226 :group 'org-todo
2227 :type 'boolean)
2229 (defcustom org-after-todo-state-change-hook nil
2230 "Hook which is run after the state of a TODO item was changed.
2231 The new state (a string with a TODO keyword, or nil) is available in the
2232 Lisp variable `org-state'."
2233 :group 'org-todo
2234 :type 'hook)
2236 (defvar org-blocker-hook nil
2237 "Hook for functions that are allowed to block a state change.
2239 Functions in this hook should not modify the buffer.
2240 Each function gets as its single argument a property list,
2241 see `org-trigger-hook' for more information about this list.
2243 If any of the functions in this hook returns nil, the state change
2244 is blocked.")
2246 (defvar org-trigger-hook nil
2247 "Hook for functions that are triggered by a state change.
2249 Each function gets as its single argument a property list with at
2250 least the following elements:
2252 (:type type-of-change :position pos-at-entry-start
2253 :from old-state :to new-state)
2255 Depending on the type, more properties may be present.
2257 This mechanism is currently implemented for:
2259 TODO state changes
2260 ------------------
2261 :type todo-state-change
2262 :from previous state (keyword as a string), or nil, or a symbol
2263 'todo' or 'done', to indicate the general type of state.
2264 :to new state, like in :from")
2266 (defcustom org-enforce-todo-dependencies nil
2267 "Non-nil means undone TODO entries will block switching the parent to DONE.
2268 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2269 be blocked if any prior sibling is not yet done.
2270 Finally, if the parent is blocked because of ordered siblings of its own,
2271 the child will also be blocked."
2272 :set (lambda (var val)
2273 (set var val)
2274 (if val
2275 (add-hook 'org-blocker-hook
2276 'org-block-todo-from-children-or-siblings-or-parent)
2277 (remove-hook 'org-blocker-hook
2278 'org-block-todo-from-children-or-siblings-or-parent)))
2279 :group 'org-todo
2280 :type 'boolean)
2282 (defcustom org-enforce-todo-checkbox-dependencies nil
2283 "Non-nil means unchecked boxes will block switching the parent to DONE.
2284 When this is nil, checkboxes have no influence on switching TODO states.
2285 When non-nil, you first need to check off all check boxes before the TODO
2286 entry can be switched to DONE.
2287 This variable needs to be set before org.el is loaded, and you need to
2288 restart Emacs after a change to make the change effective. The only way
2289 to change is while Emacs is running is through the customize interface."
2290 :set (lambda (var val)
2291 (set var val)
2292 (if val
2293 (add-hook 'org-blocker-hook
2294 'org-block-todo-from-checkboxes)
2295 (remove-hook 'org-blocker-hook
2296 'org-block-todo-from-checkboxes)))
2297 :group 'org-todo
2298 :type 'boolean)
2300 (defcustom org-treat-insert-todo-heading-as-state-change nil
2301 "Non-nil means inserting a TODO heading is treated as state change.
2302 So when the command \\[org-insert-todo-heading] is used, state change
2303 logging will apply if appropriate. When nil, the new TODO item will
2304 be inserted directly, and no logging will take place."
2305 :group 'org-todo
2306 :type 'boolean)
2308 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2309 "Non-nil means switching TODO states with S-cursor counts as state change.
2310 This is the default behavior. However, setting this to nil allows a
2311 convenient way to select a TODO state and bypass any logging associated
2312 with that."
2313 :group 'org-todo
2314 :type 'boolean)
2316 (defcustom org-todo-state-tags-triggers nil
2317 "Tag changes that should be triggered by TODO state changes.
2318 This is a list. Each entry is
2320 (state-change (tag . flag) .......)
2322 State-change can be a string with a state, and empty string to indicate the
2323 state that has no TODO keyword, or it can be one of the symbols `todo'
2324 or `done', meaning any not-done or done state, respectively."
2325 :group 'org-todo
2326 :group 'org-tags
2327 :type '(repeat
2328 (cons (choice :tag "When changing to"
2329 (const :tag "Not-done state" todo)
2330 (const :tag "Done state" done)
2331 (string :tag "State"))
2332 (repeat
2333 (cons :tag "Tag action"
2334 (string :tag "Tag")
2335 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2337 (defcustom org-log-done nil
2338 "Information to record when a task moves to the DONE state.
2340 Possible values are:
2342 nil Don't add anything, just change the keyword
2343 time Add a time stamp to the task
2344 note Prompt for a note and add it with template `org-log-note-headings'
2346 This option can also be set with on a per-file-basis with
2348 #+STARTUP: nologdone
2349 #+STARTUP: logdone
2350 #+STARTUP: lognotedone
2352 You can have local logging settings for a subtree by setting the LOGGING
2353 property to one or more of these keywords."
2354 :group 'org-todo
2355 :group 'org-progress
2356 :type '(choice
2357 (const :tag "No logging" nil)
2358 (const :tag "Record CLOSED timestamp" time)
2359 (const :tag "Record CLOSED timestamp with note." note)))
2361 ;; Normalize old uses of org-log-done.
2362 (cond
2363 ((eq org-log-done t) (setq org-log-done 'time))
2364 ((and (listp org-log-done) (memq 'done org-log-done))
2365 (setq org-log-done 'note)))
2367 (defcustom org-log-reschedule nil
2368 "Information to record when the scheduling date of a tasks is modified.
2370 Possible values are:
2372 nil Don't add anything, just change the date
2373 time Add a time stamp to the task
2374 note Prompt for a note and add it with template `org-log-note-headings'
2376 This option can also be set with on a per-file-basis with
2378 #+STARTUP: nologreschedule
2379 #+STARTUP: logreschedule
2380 #+STARTUP: lognotereschedule"
2381 :group 'org-todo
2382 :group 'org-progress
2383 :type '(choice
2384 (const :tag "No logging" nil)
2385 (const :tag "Record timestamp" time)
2386 (const :tag "Record timestamp with note." note)))
2388 (defcustom org-log-redeadline nil
2389 "Information to record when the deadline date of a tasks is modified.
2391 Possible values are:
2393 nil Don't add anything, just change the date
2394 time Add a time stamp to the task
2395 note Prompt for a note and add it with template `org-log-note-headings'
2397 This option can also be set with on a per-file-basis with
2399 #+STARTUP: nologredeadline
2400 #+STARTUP: logredeadline
2401 #+STARTUP: lognoteredeadline
2403 You can have local logging settings for a subtree by setting the LOGGING
2404 property to one or more of these keywords."
2405 :group 'org-todo
2406 :group 'org-progress
2407 :type '(choice
2408 (const :tag "No logging" nil)
2409 (const :tag "Record timestamp" time)
2410 (const :tag "Record timestamp with note." note)))
2412 (defcustom org-log-note-clock-out nil
2413 "Non-nil means record a note when clocking out of an item.
2414 This can also be configured on a per-file basis by adding one of
2415 the following lines anywhere in the buffer:
2417 #+STARTUP: lognoteclock-out
2418 #+STARTUP: nolognoteclock-out"
2419 :group 'org-todo
2420 :group 'org-progress
2421 :type 'boolean)
2423 (defcustom org-log-done-with-time t
2424 "Non-nil means the CLOSED time stamp will contain date and time.
2425 When nil, only the date will be recorded."
2426 :group 'org-progress
2427 :type 'boolean)
2429 (defcustom org-log-note-headings
2430 '((done . "CLOSING NOTE %t")
2431 (state . "State %-12s from %-12S %t")
2432 (note . "Note taken on %t")
2433 (reschedule . "Rescheduled from %S on %t")
2434 (delschedule . "Not scheduled, was %S on %t")
2435 (redeadline . "New deadline from %S on %t")
2436 (deldeadline . "Removed deadline, was %S on %t")
2437 (refile . "Refiled on %t")
2438 (clock-out . ""))
2439 "Headings for notes added to entries.
2440 The value is an alist, with the car being a symbol indicating the note
2441 context, and the cdr is the heading to be used. The heading may also be the
2442 empty string.
2443 %t in the heading will be replaced by a time stamp.
2444 %T will be an active time stamp instead the default inactive one
2445 %d will be replaced by a short-format time stamp.
2446 %D will be replaced by an active short-format time stamp.
2447 %s will be replaced by the new TODO state, in double quotes.
2448 %S will be replaced by the old TODO state, in double quotes.
2449 %u will be replaced by the user name.
2450 %U will be replaced by the full user name.
2452 In fact, it is not a good idea to change the `state' entry, because
2453 agenda log mode depends on the format of these entries."
2454 :group 'org-todo
2455 :group 'org-progress
2456 :type '(list :greedy t
2457 (cons (const :tag "Heading when closing an item" done) string)
2458 (cons (const :tag
2459 "Heading when changing todo state (todo sequence only)"
2460 state) string)
2461 (cons (const :tag "Heading when just taking a note" note) string)
2462 (cons (const :tag "Heading when clocking out" clock-out) string)
2463 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2464 (cons (const :tag "Heading when rescheduling" reschedule) string)
2465 (cons (const :tag "Heading when changing deadline" redeadline) string)
2466 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2467 (cons (const :tag "Heading when refiling" refile) string)))
2469 (unless (assq 'note org-log-note-headings)
2470 (push '(note . "%t") org-log-note-headings))
2472 (defcustom org-log-into-drawer nil
2473 "Non-nil means insert state change notes and time stamps into a drawer.
2474 When nil, state changes notes will be inserted after the headline and
2475 any scheduling and clock lines, but not inside a drawer.
2477 The value of this variable should be the name of the drawer to use.
2478 LOGBOOK is proposed as the default drawer for this purpose, you can
2479 also set this to a string to define the drawer of your choice.
2481 A value of t is also allowed, representing \"LOGBOOK\".
2483 If this variable is set, `org-log-state-notes-insert-after-drawers'
2484 will be ignored.
2486 You can set the property LOG_INTO_DRAWER to overrule this setting for
2487 a subtree."
2488 :group 'org-todo
2489 :group 'org-progress
2490 :type '(choice
2491 (const :tag "Not into a drawer" nil)
2492 (const :tag "LOGBOOK" t)
2493 (string :tag "Other")))
2495 (if (fboundp 'defvaralias)
2496 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2498 (defun org-log-into-drawer ()
2499 "Return the value of `org-log-into-drawer', but let properties overrule.
2500 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2501 used instead of the default value."
2502 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2503 (cond
2504 ((not p) org-log-into-drawer)
2505 ((equal p "nil") nil)
2506 ((equal p "t") "LOGBOOK")
2507 (t p))))
2509 (defcustom org-log-state-notes-insert-after-drawers nil
2510 "Non-nil means insert state change notes after any drawers in entry.
2511 Only the drawers that *immediately* follow the headline and the
2512 deadline/scheduled line are skipped.
2513 When nil, insert notes right after the heading and perhaps the line
2514 with deadline/scheduling if present.
2516 This variable will have no effect if `org-log-into-drawer' is
2517 set."
2518 :group 'org-todo
2519 :group 'org-progress
2520 :type 'boolean)
2522 (defcustom org-log-states-order-reversed t
2523 "Non-nil means the latest state note will be directly after heading.
2524 When nil, the state change notes will be ordered according to time."
2525 :group 'org-todo
2526 :group 'org-progress
2527 :type 'boolean)
2529 (defcustom org-todo-repeat-to-state nil
2530 "The TODO state to which a repeater should return the repeating task.
2531 By default this is the first task in a TODO sequence, or the previous state
2532 in a TODO_TYP set. But you can specify another task here.
2533 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2534 :group 'org-todo
2535 :version "24.1"
2536 :type '(choice (const :tag "Head of sequence" nil)
2537 (string :tag "Specific state")))
2539 (defcustom org-log-repeat 'time
2540 "Non-nil means record moving through the DONE state when triggering repeat.
2541 An auto-repeating task is immediately switched back to TODO when
2542 marked DONE. If you are not logging state changes (by adding \"@\"
2543 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2544 record a closing note, there will be no record of the task moving
2545 through DONE. This variable forces taking a note anyway.
2547 nil Don't force a record
2548 time Record a time stamp
2549 note Prompt for a note and add it with template `org-log-note-headings'
2551 This option can also be set with on a per-file-basis with
2553 #+STARTUP: nologrepeat
2554 #+STARTUP: logrepeat
2555 #+STARTUP: lognoterepeat
2557 You can have local logging settings for a subtree by setting the LOGGING
2558 property to one or more of these keywords."
2559 :group 'org-todo
2560 :group 'org-progress
2561 :type '(choice
2562 (const :tag "Don't force a record" nil)
2563 (const :tag "Force recording the DONE state" time)
2564 (const :tag "Force recording a note with the DONE state" note)))
2567 (defgroup org-priorities nil
2568 "Priorities in Org-mode."
2569 :tag "Org Priorities"
2570 :group 'org-todo)
2572 (defcustom org-enable-priority-commands t
2573 "Non-nil means priority commands are active.
2574 When nil, these commands will be disabled, so that you never accidentally
2575 set a priority."
2576 :group 'org-priorities
2577 :type 'boolean)
2579 (defcustom org-highest-priority ?A
2580 "The highest priority of TODO items. A character like ?A, ?B etc.
2581 Must have a smaller ASCII number than `org-lowest-priority'."
2582 :group 'org-priorities
2583 :type 'character)
2585 (defcustom org-lowest-priority ?C
2586 "The lowest priority of TODO items. A character like ?A, ?B etc.
2587 Must have a larger ASCII number than `org-highest-priority'."
2588 :group 'org-priorities
2589 :type 'character)
2591 (defcustom org-default-priority ?B
2592 "The default priority of TODO items.
2593 This is the priority an item gets if no explicit priority is given.
2594 When starting to cycle on an empty priority the first step in the cycle
2595 depends on `org-priority-start-cycle-with-default'. The resulting first
2596 step priority must not exceed the range from `org-highest-priority' to
2597 `org-lowest-priority' which means that `org-default-priority' has to be
2598 in this range exclusive or inclusive the range boundaries. Else the
2599 first step refuses to set the default and the second will fall back
2600 to (depending on the command used) the highest or lowest priority."
2601 :group 'org-priorities
2602 :type 'character)
2604 (defcustom org-priority-start-cycle-with-default t
2605 "Non-nil means start with default priority when starting to cycle.
2606 When this is nil, the first step in the cycle will be (depending on the
2607 command used) one higher or lower than the default priority.
2608 See also `org-default-priority'."
2609 :group 'org-priorities
2610 :type 'boolean)
2612 (defcustom org-get-priority-function nil
2613 "Function to extract the priority from a string.
2614 The string is normally the headline. If this is nil Org computes the
2615 priority from the priority cookie like [#A] in the headline. It returns
2616 an integer, increasing by 1000 for each priority level.
2617 The user can set a different function here, which should take a string
2618 as an argument and return the numeric priority."
2619 :group 'org-priorities
2620 :version "24.1"
2621 :type 'function)
2623 (defgroup org-time nil
2624 "Options concerning time stamps and deadlines in Org-mode."
2625 :tag "Org Time"
2626 :group 'org)
2628 (defcustom org-insert-labeled-timestamps-at-point nil
2629 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2630 When nil, these labeled time stamps are forces into the second line of an
2631 entry, just after the headline. When scheduling from the global TODO list,
2632 the time stamp will always be forced into the second line."
2633 :group 'org-time
2634 :type 'boolean)
2636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2637 "Formats for `format-time-string' which are used for time stamps.
2638 It is not recommended to change this constant.")
2640 (defcustom org-time-stamp-rounding-minutes '(0 5)
2641 "Number of minutes to round time stamps to.
2642 These are two values, the first applies when first creating a time stamp.
2643 The second applies when changing it with the commands `S-up' and `S-down'.
2644 When changing the time stamp, this means that it will change in steps
2645 of N minutes, as given by the second value.
2647 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2648 numbers should be factors of 60, so for example 5, 10, 15.
2650 When this is larger than 1, you can still force an exact time stamp by using
2651 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2652 and by using a prefix arg to `S-up/down' to specify the exact number
2653 of minutes to shift."
2654 :group 'org-time
2655 :get #'(lambda (var) ; Make sure both elements are there
2656 (if (integerp (default-value var))
2657 (list (default-value var) 5)
2658 (default-value var)))
2659 :type '(list
2660 (integer :tag "when inserting times")
2661 (integer :tag "when modifying times")))
2663 ;; Normalize old customizations of this variable.
2664 (when (integerp org-time-stamp-rounding-minutes)
2665 (setq org-time-stamp-rounding-minutes
2666 (list org-time-stamp-rounding-minutes
2667 org-time-stamp-rounding-minutes)))
2669 (defcustom org-display-custom-times nil
2670 "Non-nil means overlay custom formats over all time stamps.
2671 The formats are defined through the variable `org-time-stamp-custom-formats'.
2672 To turn this on on a per-file basis, insert anywhere in the file:
2673 #+STARTUP: customtime"
2674 :group 'org-time
2675 :set 'set-default
2676 :type 'sexp)
2677 (make-variable-buffer-local 'org-display-custom-times)
2679 (defcustom org-time-stamp-custom-formats
2680 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2681 "Custom formats for time stamps. See `format-time-string' for the syntax.
2682 These are overlaid over the default ISO format if the variable
2683 `org-display-custom-times' is set. Time like %H:%M should be at the
2684 end of the second format. The custom formats are also honored by export
2685 commands, if custom time display is turned on at the time of export."
2686 :group 'org-time
2687 :type 'sexp)
2689 (defun org-time-stamp-format (&optional long inactive)
2690 "Get the right format for a time string."
2691 (let ((f (if long (cdr org-time-stamp-formats)
2692 (car org-time-stamp-formats))))
2693 (if inactive
2694 (concat "[" (substring f 1 -1) "]")
2695 f)))
2697 (defcustom org-time-clocksum-format "%d:%02d"
2698 "The format string used when creating CLOCKSUM lines.
2699 This is also used when org-mode generates a time duration."
2700 :group 'org-time
2701 :type 'string)
2703 (defcustom org-time-clocksum-use-fractional nil
2704 "If non-nil, \\[org-clock-display] uses fractional times.
2705 org-mode generates a time duration."
2706 :group 'org-time
2707 :type 'boolean)
2709 (defcustom org-time-clocksum-fractional-format "%.2f"
2710 "The format string used when creating CLOCKSUM lines, or when
2711 org-mode generates a time duration."
2712 :group 'org-time
2713 :type 'string)
2715 (defcustom org-deadline-warning-days 14
2716 "No. of days before expiration during which a deadline becomes active.
2717 This variable governs the display in sparse trees and in the agenda.
2718 When 0 or negative, it means use this number (the absolute value of it)
2719 even if a deadline has a different individual lead time specified.
2721 Custom commands can set this variable in the options section."
2722 :group 'org-time
2723 :group 'org-agenda-daily/weekly
2724 :type 'integer)
2726 (defcustom org-read-date-prefer-future t
2727 "Non-nil means assume future for incomplete date input from user.
2728 This affects the following situations:
2729 1. The user gives a month but not a year.
2730 For example, if it is April and you enter \"feb 2\", this will be read
2731 as Feb 2, *next* year. \"May 5\", however, will be this year.
2732 2. The user gives a day, but no month.
2733 For example, if today is the 15th, and you enter \"3\", Org-mode will
2734 read this as the third of *next* month. However, if you enter \"17\",
2735 it will be considered as *this* month.
2737 If you set this variable to the symbol `time', then also the following
2738 will work:
2740 3. If the user gives a time.
2741 If the time is before now, it will be interpreted as tomorrow.
2743 Currently none of this works for ISO week specifications.
2745 When this option is nil, the current day, month and year will always be
2746 used as defaults.
2748 See also `org-agenda-jump-prefer-future'."
2749 :group 'org-time
2750 :type '(choice
2751 (const :tag "Never" nil)
2752 (const :tag "Check month and day" t)
2753 (const :tag "Check month, day, and time" time)))
2755 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2756 "Should the agenda jump command prefer the future for incomplete dates?
2757 The default is to do the same as configured in `org-read-date-prefer-future'.
2758 But you can also set a deviating value here.
2759 This may t or nil, or the symbol `org-read-date-prefer-future'."
2760 :group 'org-agenda
2761 :group 'org-time
2762 :version "24.1"
2763 :type '(choice
2764 (const :tag "Use org-read-date-prefer-future"
2765 org-read-date-prefer-future)
2766 (const :tag "Never" nil)
2767 (const :tag "Always" t)))
2769 (defcustom org-read-date-force-compatible-dates t
2770 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2772 Depending on the system Emacs is running on, certain dates cannot
2773 be represented with the type used internally to represent time.
2774 Dates between 1970-1-1 and 2038-1-1 can always be represented
2775 correctly. Some systems allow for earlier dates, some for later,
2776 some for both. One way to find out it to insert any date into an
2777 Org buffer, putting the cursor on the year and hitting S-up and
2778 S-down to test the range.
2780 When this variable is set to t, the date/time prompt will not let
2781 you specify dates outside the 1970-2037 range, so it is certain that
2782 these dates will work in whatever version of Emacs you are
2783 running, and also that you can move a file from one Emacs implementation
2784 to another. WHenever Org is forcing the year for you, it will display
2785 a message and beep.
2787 When this variable is nil, Org will check if the date is
2788 representable in the specific Emacs implementation you are using.
2789 If not, it will force a year, usually the current year, and beep
2790 to remind you. Currently this setting is not recommended because
2791 the likelihood that you will open your Org files in an Emacs that
2792 has limited date range is not negligible.
2794 A workaround for this problem is to use diary sexp dates for time
2795 stamps outside of this range."
2796 :group 'org-time
2797 :version "24.1"
2798 :type 'boolean)
2800 (defcustom org-read-date-display-live t
2801 "Non-nil means display current interpretation of date prompt live.
2802 This display will be in an overlay, in the minibuffer."
2803 :group 'org-time
2804 :type 'boolean)
2806 (defcustom org-read-date-popup-calendar t
2807 "Non-nil means pop up a calendar when prompting for a date.
2808 In the calendar, the date can be selected with mouse-1. However, the
2809 minibuffer will also be active, and you can simply enter the date as well.
2810 When nil, only the minibuffer will be available."
2811 :group 'org-time
2812 :type 'boolean)
2813 (if (fboundp 'defvaralias)
2814 (defvaralias 'org-popup-calendar-for-date-prompt
2815 'org-read-date-popup-calendar))
2817 (defcustom org-read-date-minibuffer-setup-hook nil
2818 "Hook to be used to set up keys for the date/time interface.
2819 Add key definitions to `minibuffer-local-map', which will be a temporary
2820 copy."
2821 :group 'org-time
2822 :type 'hook)
2824 (defcustom org-extend-today-until 0
2825 "The hour when your day really ends. Must be an integer.
2826 This has influence for the following applications:
2827 - When switching the agenda to \"today\". It it is still earlier than
2828 the time given here, the day recognized as TODAY is actually yesterday.
2829 - When a date is read from the user and it is still before the time given
2830 here, the current date and time will be assumed to be yesterday, 23:59.
2831 Also, timestamps inserted in capture templates follow this rule.
2833 IMPORTANT: This is a feature whose implementation is and likely will
2834 remain incomplete. Really, it is only here because past midnight seems to
2835 be the favorite working time of John Wiegley :-)"
2836 :group 'org-time
2837 :type 'integer)
2839 (defcustom org-use-effective-time nil
2840 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2841 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2842 \"effective time\" of any timestamps between midnight and 8am will be
2843 23:59 of the previous day."
2844 :group 'org-time
2845 :version "24.1"
2846 :type 'boolean)
2848 (defcustom org-edit-timestamp-down-means-later nil
2849 "Non-nil means S-down will increase the time in a time stamp.
2850 When nil, S-up will increase."
2851 :group 'org-time
2852 :type 'boolean)
2854 (defcustom org-calendar-follow-timestamp-change t
2855 "Non-nil means make the calendar window follow timestamp changes.
2856 When a timestamp is modified and the calendar window is visible, it will be
2857 moved to the new date."
2858 :group 'org-time
2859 :type 'boolean)
2861 (defgroup org-tags nil
2862 "Options concerning tags in Org-mode."
2863 :tag "Org Tags"
2864 :group 'org)
2866 (defcustom org-tag-alist nil
2867 "List of tags allowed in Org-mode files.
2868 When this list is nil, Org-mode will base TAG input on what is already in the
2869 buffer.
2870 The value of this variable is an alist, the car of each entry must be a
2871 keyword as a string, the cdr may be a character that is used to select
2872 that tag through the fast-tag-selection interface.
2873 See the manual for details."
2874 :group 'org-tags
2875 :type '(repeat
2876 (choice
2877 (cons (string :tag "Tag name")
2878 (character :tag "Access char"))
2879 (list :tag "Start radio group"
2880 (const :startgroup)
2881 (option (string :tag "Group description")))
2882 (list :tag "End radio group"
2883 (const :endgroup)
2884 (option (string :tag "Group description")))
2885 (const :tag "New line" (:newline)))))
2887 (defcustom org-tag-persistent-alist nil
2888 "List of tags that will always appear in all Org-mode files.
2889 This is in addition to any in buffer settings or customizations
2890 of `org-tag-alist'.
2891 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2892 The value of this variable is an alist, the car of each entry must be a
2893 keyword as a string, the cdr may be a character that is used to select
2894 that tag through the fast-tag-selection interface.
2895 See the manual for details.
2896 To disable these tags on a per-file basis, insert anywhere in the file:
2897 #+STARTUP: noptag"
2898 :group 'org-tags
2899 :type '(repeat
2900 (choice
2901 (cons (string :tag "Tag name")
2902 (character :tag "Access char"))
2903 (const :tag "Start radio group" (:startgroup))
2904 (const :tag "End radio group" (:endgroup))
2905 (const :tag "New line" (:newline)))))
2907 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2908 "If non-nil, always offer completion for all tags of all agenda files.
2909 Instead of customizing this variable directly, you might want to
2910 set it locally for capture buffers, because there no list of
2911 tags in that file can be created dynamically (there are none).
2913 (add-hook 'org-capture-mode-hook
2914 (lambda ()
2915 (set (make-local-variable
2916 'org-complete-tags-always-offer-all-agenda-tags)
2917 t)))"
2918 :group 'org-tags
2919 :version "24.1"
2920 :type 'boolean)
2922 (defvar org-file-tags nil
2923 "List of tags that can be inherited by all entries in the file.
2924 The tags will be inherited if the variable `org-use-tag-inheritance'
2925 says they should be.
2926 This variable is populated from #+FILETAGS lines.")
2928 (defcustom org-use-fast-tag-selection 'auto
2929 "Non-nil means use fast tag selection scheme.
2930 This is a special interface to select and deselect tags with single keys.
2931 When nil, fast selection is never used.
2932 When the symbol `auto', fast selection is used if and only if selection
2933 characters for tags have been configured, either through the variable
2934 `org-tag-alist' or through a #+TAGS line in the buffer.
2935 When t, fast selection is always used and selection keys are assigned
2936 automatically if necessary."
2937 :group 'org-tags
2938 :type '(choice
2939 (const :tag "Always" t)
2940 (const :tag "Never" nil)
2941 (const :tag "When selection characters are configured" 'auto)))
2943 (defcustom org-fast-tag-selection-single-key nil
2944 "Non-nil means fast tag selection exits after first change.
2945 When nil, you have to press RET to exit it.
2946 During fast tag selection, you can toggle this flag with `C-c'.
2947 This variable can also have the value `expert'. In this case, the window
2948 displaying the tags menu is not even shown, until you press C-c again."
2949 :group 'org-tags
2950 :type '(choice
2951 (const :tag "No" nil)
2952 (const :tag "Yes" t)
2953 (const :tag "Expert" expert)))
2955 (defvar org-fast-tag-selection-include-todo nil
2956 "Non-nil means fast tags selection interface will also offer TODO states.
2957 This is an undocumented feature, you should not rely on it.")
2959 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2960 "The column to which tags should be indented in a headline.
2961 If this number is positive, it specifies the column. If it is negative,
2962 it means that the tags should be flushright to that column. For example,
2963 -80 works well for a normal 80 character screen.
2964 When 0, place tags directly after headline text, with only one space in
2965 between."
2966 :group 'org-tags
2967 :type 'integer)
2969 (defcustom org-auto-align-tags t
2970 "Non-nil keeps tags aligned when modifying headlines.
2971 Some operations (i.e. demoting) change the length of a headline and
2972 therefore shift the tags around. With this option turned on, after
2973 each such operation the tags are again aligned to `org-tags-column'."
2974 :group 'org-tags
2975 :type 'boolean)
2977 (defcustom org-use-tag-inheritance t
2978 "Non-nil means tags in levels apply also for sublevels.
2979 When nil, only the tags directly given in a specific line apply there.
2980 This may also be a list of tags that should be inherited, or a regexp that
2981 matches tags that should be inherited. Additional control is possible
2982 with the variable `org-tags-exclude-from-inheritance' which gives an
2983 explicit list of tags to be excluded from inheritance., even if the value of
2984 `org-use-tag-inheritance' would select it for inheritance.
2986 If this option is t, a match early-on in a tree can lead to a large
2987 number of matches in the subtree when constructing the agenda or creating
2988 a sparse tree. If you only want to see the first match in a tree during
2989 a search, check out the variable `org-tags-match-list-sublevels'."
2990 :group 'org-tags
2991 :type '(choice
2992 (const :tag "Not" nil)
2993 (const :tag "Always" t)
2994 (repeat :tag "Specific tags" (string :tag "Tag"))
2995 (regexp :tag "Tags matched by regexp")))
2997 (defcustom org-tags-exclude-from-inheritance nil
2998 "List of tags that should never be inherited.
2999 This is a way to exclude a few tags from inheritance. For way to do
3000 the opposite, to actively allow inheritance for selected tags,
3001 see the variable `org-use-tag-inheritance'."
3002 :group 'org-tags
3003 :type '(repeat (string :tag "Tag")))
3005 (defun org-tag-inherit-p (tag)
3006 "Check if TAG is one that should be inherited."
3007 (cond
3008 ((member tag org-tags-exclude-from-inheritance) nil)
3009 ((eq org-use-tag-inheritance t) t)
3010 ((not org-use-tag-inheritance) nil)
3011 ((stringp org-use-tag-inheritance)
3012 (string-match org-use-tag-inheritance tag))
3013 ((listp org-use-tag-inheritance)
3014 (member tag org-use-tag-inheritance))
3015 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3017 (defcustom org-tags-match-list-sublevels t
3018 "Non-nil means list also sublevels of headlines matching a search.
3019 This variable applies to tags/property searches, and also to stuck
3020 projects because this search is based on a tags match as well.
3022 When set to the symbol `indented', sublevels are indented with
3023 leading dots.
3025 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3026 the sublevels of a headline matching a tag search often also match
3027 the same search. Listing all of them can create very long lists.
3028 Setting this variable to nil causes subtrees of a match to be skipped.
3030 This variable is semi-obsolete and probably should always be true. It
3031 is better to limit inheritance to certain tags using the variables
3032 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3033 :group 'org-tags
3034 :type '(choice
3035 (const :tag "No, don't list them" nil)
3036 (const :tag "Yes, do list them" t)
3037 (const :tag "List them, indented with leading dots" indented)))
3039 (defcustom org-tags-sort-function nil
3040 "When set, tags are sorted using this function as a comparator."
3041 :group 'org-tags
3042 :type '(choice
3043 (const :tag "No sorting" nil)
3044 (const :tag "Alphabetical" string<)
3045 (const :tag "Reverse alphabetical" string>)
3046 (function :tag "Custom function" nil)))
3048 (defvar org-tags-history nil
3049 "History of minibuffer reads for tags.")
3050 (defvar org-last-tags-completion-table nil
3051 "The last used completion table for tags.")
3052 (defvar org-after-tags-change-hook nil
3053 "Hook that is run after the tags in a line have changed.")
3055 (defgroup org-properties nil
3056 "Options concerning properties in Org-mode."
3057 :tag "Org Properties"
3058 :group 'org)
3060 (defcustom org-property-format "%-10s %s"
3061 "How property key/value pairs should be formatted by `indent-line'.
3062 When `indent-line' hits a property definition, it will format the line
3063 according to this format, mainly to make sure that the values are
3064 lined-up with respect to each other."
3065 :group 'org-properties
3066 :type 'string)
3068 (defcustom org-properties-postprocess-alist nil
3069 "Alist of properties and functions to adjust inserted values.
3070 Elements of this alist must be of the form
3072 ([string] [function])
3074 where [string] must be a property name and [function] must be a
3075 lambda expression: this lambda expression must take one argument,
3076 the value to adjust, and return the new value as a string.
3078 For example, this element will allow the property \"Remaining\"
3079 to be updated wrt the relation between the \"Effort\" property
3080 and the clock summary:
3082 ((\"Remaining\" (lambda(value)
3083 (let ((clocksum (org-clock-sum-current-item))
3084 (effort (org-duration-string-to-minutes
3085 (org-entry-get (point) \"Effort\"))))
3086 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3087 :group 'org-properties
3088 :version "24.1"
3089 :type '(alist :key-type (string :tag "Property")
3090 :value-type (function :tag "Function")))
3092 (defcustom org-use-property-inheritance nil
3093 "Non-nil means properties apply also for sublevels.
3095 This setting is chiefly used during property searches. Turning it on can
3096 cause significant overhead when doing a search, which is why it is not
3097 on by default.
3099 When nil, only the properties directly given in the current entry count.
3100 When t, every property is inherited. The value may also be a list of
3101 properties that should have inheritance, or a regular expression matching
3102 properties that should be inherited.
3104 However, note that some special properties use inheritance under special
3105 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3106 and the properties ending in \"_ALL\" when they are used as descriptor
3107 for valid values of a property.
3109 Note for programmers:
3110 When querying an entry with `org-entry-get', you can control if inheritance
3111 should be used. By default, `org-entry-get' looks only at the local
3112 properties. You can request inheritance by setting the inherit argument
3113 to t (to force inheritance) or to `selective' (to respect the setting
3114 in this variable)."
3115 :group 'org-properties
3116 :type '(choice
3117 (const :tag "Not" nil)
3118 (const :tag "Always" t)
3119 (repeat :tag "Specific properties" (string :tag "Property"))
3120 (regexp :tag "Properties matched by regexp")))
3122 (defun org-property-inherit-p (property)
3123 "Check if PROPERTY is one that should be inherited."
3124 (cond
3125 ((eq org-use-property-inheritance t) t)
3126 ((not org-use-property-inheritance) nil)
3127 ((stringp org-use-property-inheritance)
3128 (string-match org-use-property-inheritance property))
3129 ((listp org-use-property-inheritance)
3130 (member property org-use-property-inheritance))
3131 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3133 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3134 "The default column format, if no other format has been defined.
3135 This variable can be set on the per-file basis by inserting a line
3137 #+COLUMNS: %25ITEM ....."
3138 :group 'org-properties
3139 :type 'string)
3141 (defcustom org-columns-ellipses ".."
3142 "The ellipses to be used when a field in column view is truncated.
3143 When this is the empty string, as many characters as possible are shown,
3144 but then there will be no visual indication that the field has been truncated.
3145 When this is a string of length N, the last N characters of a truncated
3146 field are replaced by this string. If the column is narrower than the
3147 ellipses string, only part of the ellipses string will be shown."
3148 :group 'org-properties
3149 :type 'string)
3151 (defcustom org-columns-modify-value-for-display-function nil
3152 "Function that modifies values for display in column view.
3153 For example, it can be used to cut out a certain part from a time stamp.
3154 The function must take 2 arguments:
3156 column-title The title of the column (*not* the property name)
3157 value The value that should be modified.
3159 The function should return the value that should be displayed,
3160 or nil if the normal value should be used."
3161 :group 'org-properties
3162 :type 'function)
3164 (defcustom org-effort-property "Effort"
3165 "The property that is being used to keep track of effort estimates.
3166 Effort estimates given in this property need to have the format H:MM."
3167 :group 'org-properties
3168 :group 'org-progress
3169 :type '(string :tag "Property"))
3171 (defconst org-global-properties-fixed
3172 '(("VISIBILITY_ALL" . "folded children content all")
3173 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3174 "List of property/value pairs that can be inherited by any entry.
3176 These are fixed values, for the preset properties. The user variable
3177 that can be used to add to this list is `org-global-properties'.
3179 The entries in this list are cons cells where the car is a property
3180 name and cdr is a string with the value. If the value represents
3181 multiple items like an \"_ALL\" property, separate the items by
3182 spaces.")
3184 (defcustom org-global-properties nil
3185 "List of property/value pairs that can be inherited by any entry.
3187 This list will be combined with the constant `org-global-properties-fixed'.
3189 The entries in this list are cons cells where the car is a property
3190 name and cdr is a string with the value.
3192 You can set buffer-local values for the same purpose in the variable
3193 `org-file-properties' this by adding lines like
3195 #+PROPERTY: NAME VALUE"
3196 :group 'org-properties
3197 :type '(repeat
3198 (cons (string :tag "Property")
3199 (string :tag "Value"))))
3201 (defvar org-file-properties nil
3202 "List of property/value pairs that can be inherited by any entry.
3203 Valid for the current buffer.
3204 This variable is populated from #+PROPERTY lines.")
3205 (make-variable-buffer-local 'org-file-properties)
3207 (defgroup org-agenda nil
3208 "Options concerning agenda views in Org-mode."
3209 :tag "Org Agenda"
3210 :group 'org)
3212 (defvar org-category nil
3213 "Variable used by org files to set a category for agenda display.
3214 Such files should use a file variable to set it, for example
3216 # -*- mode: org; org-category: \"ELisp\"
3218 or contain a special line
3220 #+CATEGORY: ELisp
3222 If the file does not specify a category, then file's base name
3223 is used instead.")
3224 (make-variable-buffer-local 'org-category)
3225 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3227 (defcustom org-agenda-files nil
3228 "The files to be used for agenda display.
3229 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3230 \\[org-remove-file]. You can also use customize to edit the list.
3232 If an entry is a directory, all files in that directory that are matched by
3233 `org-agenda-file-regexp' will be part of the file list.
3235 If the value of the variable is not a list but a single file name, then
3236 the list of agenda files is actually stored and maintained in that file, one
3237 agenda file per line. In this file paths can be given relative to
3238 `org-directory'. Tilde expansion and environment variable substitution
3239 are also made."
3240 :group 'org-agenda
3241 :type '(choice
3242 (repeat :tag "List of files and directories" file)
3243 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3245 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3246 "Regular expression to match files for `org-agenda-files'.
3247 If any element in the list in that variable contains a directory instead
3248 of a normal file, all files in that directory that are matched by this
3249 regular expression will be included."
3250 :group 'org-agenda
3251 :type 'regexp)
3253 (defcustom org-agenda-text-search-extra-files nil
3254 "List of extra files to be searched by text search commands.
3255 These files will be search in addition to the agenda files by the
3256 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3257 Note that these files will only be searched for text search commands,
3258 not for the other agenda views like todo lists, tag searches or the weekly
3259 agenda. This variable is intended to list notes and possibly archive files
3260 that should also be searched by these two commands.
3261 In fact, if the first element in the list is the symbol `agenda-archives',
3262 than all archive files of all agenda files will be added to the search
3263 scope."
3264 :group 'org-agenda
3265 :type '(set :greedy t
3266 (const :tag "Agenda Archives" agenda-archives)
3267 (repeat :inline t (file))))
3269 (if (fboundp 'defvaralias)
3270 (defvaralias 'org-agenda-multi-occur-extra-files
3271 'org-agenda-text-search-extra-files))
3273 (defcustom org-agenda-skip-unavailable-files nil
3274 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3275 A nil value means to remove them, after a query, from the list."
3276 :group 'org-agenda
3277 :type 'boolean)
3279 (defcustom org-calendar-to-agenda-key [?c]
3280 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3281 The command `org-calendar-goto-agenda' will be bound to this key. The
3282 default is the character `c' because then `c' can be used to switch back and
3283 forth between agenda and calendar."
3284 :group 'org-agenda
3285 :type 'sexp)
3287 (defcustom org-calendar-insert-diary-entry-key [?i]
3288 "The key to be installed in `calendar-mode-map' for adding diary entries.
3289 This option is irrelevant until `org-agenda-diary-file' has been configured
3290 to point to an Org-mode file. When that is the case, the command
3291 `org-agenda-diary-entry' will be bound to the key given here, by default
3292 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3293 if you want to continue doing this, you need to change this to a different
3294 key."
3295 :group 'org-agenda
3296 :type 'sexp)
3298 (defcustom org-agenda-diary-file 'diary-file
3299 "File to which to add new entries with the `i' key in agenda and calendar.
3300 When this is the symbol `diary-file', the functionality in the Emacs
3301 calendar will be used to add entries to the `diary-file'. But when this
3302 points to a file, `org-agenda-diary-entry' will be used instead."
3303 :group 'org-agenda
3304 :type '(choice
3305 (const :tag "The standard Emacs diary file" diary-file)
3306 (file :tag "Special Org file diary entries")))
3308 (eval-after-load "calendar"
3309 '(progn
3310 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3311 'org-calendar-goto-agenda)
3312 (add-hook 'calendar-mode-hook
3313 (lambda ()
3314 (unless (eq org-agenda-diary-file 'diary-file)
3315 (define-key calendar-mode-map
3316 org-calendar-insert-diary-entry-key
3317 'org-agenda-diary-entry))))))
3319 (defgroup org-latex nil
3320 "Options for embedding LaTeX code into Org-mode."
3321 :tag "Org LaTeX"
3322 :group 'org)
3324 (defcustom org-format-latex-options
3325 '(:foreground default :background default :scale 1.0
3326 :html-foreground "Black" :html-background "Transparent"
3327 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3328 "Options for creating images from LaTeX fragments.
3329 This is a property list with the following properties:
3330 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3331 `default' means use the foreground of the default face.
3332 :background the background color, or \"Transparent\".
3333 `default' means use the background of the default face.
3334 :scale a scaling factor for the size of the images, to get more pixels
3335 :html-foreground, :html-background, :html-scale
3336 the same numbers for HTML export.
3337 :matchers a list indicating which matchers should be used to
3338 find LaTeX fragments. Valid members of this list are:
3339 \"begin\" find environments
3340 \"$1\" find single characters surrounded by $.$
3341 \"$\" find math expressions surrounded by $...$
3342 \"$$\" find math expressions surrounded by $$....$$
3343 \"\\(\" find math expressions surrounded by \\(...\\)
3344 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3345 :group 'org-latex
3346 :type 'plist)
3348 (defcustom org-format-latex-signal-error t
3349 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3350 When nil, just push out a message."
3351 :group 'org-latex
3352 :version "24.1"
3353 :type 'boolean)
3355 (defcustom org-latex-to-mathml-jar-file nil
3356 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3357 Use this to specify additional executable file say a jar file.
3359 When using MathToWeb as the converter, specify the full-path to
3360 your mathtoweb.jar file."
3361 :group 'org-latex
3362 :version "24.1"
3363 :type '(choice
3364 (const :tag "None" nil)
3365 (file :tag "JAR file" :must-match t)))
3367 (defcustom org-latex-to-mathml-convert-command nil
3368 "Command to convert LaTeX fragments to MathML.
3369 Replace format-specifiers in the command as noted below and use
3370 `shell-command' to convert LaTeX to MathML.
3371 %j: Executable file in fully expanded form as specified by
3372 `org-latex-to-mathml-jar-file'.
3373 %I: Input LaTeX file in fully expanded form
3374 %o: Output MathML file
3375 This command is used by `org-create-math-formula'.
3377 When using MathToWeb as the converter, set this to
3378 \"java -jar %j -unicode -force -df %o %I\"."
3379 :group 'org-latex
3380 :version "24.1"
3381 :type '(choice
3382 (const :tag "None" nil)
3383 (string :tag "\nShell command")))
3385 (defcustom org-latex-create-formula-image-program 'dvipng
3386 "Program to convert LaTeX fragments with.
3388 dvipng Process the LaTeX fragments to dvi file, then convert
3389 dvi files to png files using dvipng.
3390 This will also include processing of non-math environments.
3391 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3392 to convert pdf files to png files"
3393 :group 'org-latex
3394 :version "24.1"
3395 :type '(choice
3396 (const :tag "dvipng" dvipng)
3397 (const :tag "imagemagick" imagemagick)))
3399 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3400 "Path to store latex preview images. A relative path here creates many
3401 directories relative to the processed org files paths. An absolute path
3402 puts all preview images at the same place."
3403 :group 'org-latex
3404 :version "24.3"
3405 :type 'string)
3407 (defun org-format-latex-mathml-available-p ()
3408 "Return t if `org-latex-to-mathml-convert-command' is usable."
3409 (save-match-data
3410 (when (and (boundp 'org-latex-to-mathml-convert-command)
3411 org-latex-to-mathml-convert-command)
3412 (let ((executable (car (split-string
3413 org-latex-to-mathml-convert-command))))
3414 (when (executable-find executable)
3415 (if (string-match
3416 "%j" org-latex-to-mathml-convert-command)
3417 (file-readable-p org-latex-to-mathml-jar-file)
3418 t))))))
3420 (defcustom org-format-latex-header "\\documentclass{article}
3421 \\usepackage[usenames]{color}
3422 \\usepackage{amsmath}
3423 \\usepackage[mathscr]{eucal}
3424 \\pagestyle{empty} % do not remove
3425 \[PACKAGES]
3426 \[DEFAULT-PACKAGES]
3427 % The settings below are copied from fullpage.sty
3428 \\setlength{\\textwidth}{\\paperwidth}
3429 \\addtolength{\\textwidth}{-3cm}
3430 \\setlength{\\oddsidemargin}{1.5cm}
3431 \\addtolength{\\oddsidemargin}{-2.54cm}
3432 \\setlength{\\evensidemargin}{\\oddsidemargin}
3433 \\setlength{\\textheight}{\\paperheight}
3434 \\addtolength{\\textheight}{-\\headheight}
3435 \\addtolength{\\textheight}{-\\headsep}
3436 \\addtolength{\\textheight}{-\\footskip}
3437 \\addtolength{\\textheight}{-3cm}
3438 \\setlength{\\topmargin}{1.5cm}
3439 \\addtolength{\\topmargin}{-2.54cm}"
3440 "The document header used for processing LaTeX fragments.
3441 It is imperative that this header make sure that no page number
3442 appears on the page. The package defined in the variables
3443 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3444 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3445 will be appended."
3446 :group 'org-latex
3447 :type 'string)
3449 (defvar org-format-latex-header-extra nil)
3451 (defun org-set-packages-alist (var val)
3452 "Set the packages alist and make sure it has 3 elements per entry."
3453 (set var (mapcar (lambda (x)
3454 (if (and (consp x) (= (length x) 2))
3455 (list (car x) (nth 1 x) t)
3457 val)))
3459 (defun org-get-packages-alist (var)
3461 "Get the packages alist and make sure it has 3 elements per entry."
3462 (mapcar (lambda (x)
3463 (if (and (consp x) (= (length x) 2))
3464 (list (car x) (nth 1 x) t)
3466 (default-value var)))
3468 ;; The following variables are defined here because is it also used
3469 ;; when formatting latex fragments. Originally it was part of the
3470 ;; LaTeX exporter, which is why the name includes "export".
3471 (defcustom org-export-latex-default-packages-alist
3472 '(("AUTO" "inputenc" t)
3473 ("T1" "fontenc" t)
3474 ("" "fixltx2e" nil)
3475 ("" "graphicx" t)
3476 ("" "longtable" nil)
3477 ("" "float" nil)
3478 ("" "wrapfig" nil)
3479 ("" "soul" t)
3480 ("" "textcomp" t)
3481 ("" "marvosym" t)
3482 ("" "wasysym" t)
3483 ("" "latexsym" t)
3484 ("" "amssymb" t)
3485 ("" "hyperref" nil)
3486 "\\tolerance=1000"
3488 "Alist of default packages to be inserted in the header.
3489 Change this only if one of the packages here causes an incompatibility
3490 with another package you are using.
3491 The packages in this list are needed by one part or another of Org-mode
3492 to function properly.
3494 - inputenc, fontenc: for basic font and character selection
3495 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3496 for interpreting the entities in `org-entities'. You can skip some of these
3497 packages if you don't use any of the symbols in it.
3498 - graphicx: for including images
3499 - float, wrapfig: for figure placement
3500 - longtable: for long tables
3501 - hyperref: for cross references
3503 Therefore you should not modify this variable unless you know what you
3504 are doing. The one reason to change it anyway is that you might be loading
3505 some other package that conflicts with one of the default packages.
3506 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3507 If SNIPPET-FLAG is t, the package also needs to be included when
3508 compiling LaTeX snippets into images for inclusion into HTML."
3509 :group 'org-export-latex
3510 :set 'org-set-packages-alist
3511 :get 'org-get-packages-alist
3512 :version "24.1"
3513 :type '(repeat
3514 (choice
3515 (list :tag "options/package pair"
3516 (string :tag "options")
3517 (string :tag "package")
3518 (boolean :tag "Snippet"))
3519 (string :tag "A line of LaTeX"))))
3521 (defcustom org-export-latex-packages-alist nil
3522 "Alist of packages to be inserted in every LaTeX header.
3523 These will be inserted after `org-export-latex-default-packages-alist'.
3524 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3525 SNIPPET-FLAG, when t, indicates that this package is also needed when
3526 turning LaTeX snippets into images for inclusion into HTML.
3527 Make sure that you only list packages here which:
3528 - you want in every file
3529 - do not conflict with the default packages in
3530 `org-export-latex-default-packages-alist'
3531 - do not conflict with the setup in `org-format-latex-header'."
3532 :group 'org-export-latex
3533 :set 'org-set-packages-alist
3534 :get 'org-get-packages-alist
3535 :type '(repeat
3536 (choice
3537 (list :tag "options/package pair"
3538 (string :tag "options")
3539 (string :tag "package")
3540 (boolean :tag "Snippet"))
3541 (string :tag "A line of LaTeX"))))
3544 (defgroup org-appearance nil
3545 "Settings for Org-mode appearance."
3546 :tag "Org Appearance"
3547 :group 'org)
3549 (defcustom org-level-color-stars-only nil
3550 "Non-nil means fontify only the stars in each headline.
3551 When nil, the entire headline is fontified.
3552 Changing it requires restart of `font-lock-mode' to become effective
3553 also in regions already fontified."
3554 :group 'org-appearance
3555 :type 'boolean)
3557 (defcustom org-hide-leading-stars nil
3558 "Non-nil means hide the first N-1 stars in a headline.
3559 This works by using the face `org-hide' for these stars. This
3560 face is white for a light background, and black for a dark
3561 background. You may have to customize the face `org-hide' to
3562 make this work.
3563 Changing it requires restart of `font-lock-mode' to become effective
3564 also in regions already fontified.
3565 You may also set this on a per-file basis by adding one of the following
3566 lines to the buffer:
3568 #+STARTUP: hidestars
3569 #+STARTUP: showstars"
3570 :group 'org-appearance
3571 :type 'boolean)
3573 (defcustom org-hidden-keywords nil
3574 "List of symbols corresponding to keywords to be hidden the org buffer.
3575 For example, a value '(title) for this list will make the document's title
3576 appear in the buffer without the initial #+TITLE: keyword."
3577 :group 'org-appearance
3578 :version "24.1"
3579 :type '(set (const :tag "#+AUTHOR" author)
3580 (const :tag "#+DATE" date)
3581 (const :tag "#+EMAIL" email)
3582 (const :tag "#+TITLE" title)))
3584 (defcustom org-custom-properties nil
3585 "List of properties (as strings) with a special meaning.
3586 The default use of these custom properties is to let the user
3587 hide them with `org-toggle-custom-properties-visibility'."
3588 :group 'org-properties
3589 :group 'org-appearance
3590 :version "24.3"
3591 :type '(repeat (string :tag "Property Name")))
3593 (defcustom org-fontify-done-headline nil
3594 "Non-nil means change the face of a headline if it is marked DONE.
3595 Normally, only the TODO/DONE keyword indicates the state of a headline.
3596 When this is non-nil, the headline after the keyword is set to the
3597 `org-headline-done' as an additional indication."
3598 :group 'org-appearance
3599 :type 'boolean)
3601 (defcustom org-fontify-emphasized-text t
3602 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3603 Changing this variable requires a restart of Emacs to take effect."
3604 :group 'org-appearance
3605 :type 'boolean)
3607 (defcustom org-fontify-whole-heading-line nil
3608 "Non-nil means fontify the whole line for headings.
3609 This is useful when setting a background color for the
3610 org-level-* faces."
3611 :group 'org-appearance
3612 :type 'boolean)
3614 (defcustom org-highlight-latex-fragments-and-specials nil
3615 "Non-nil means fontify what is treated specially by the exporters."
3616 :group 'org-appearance
3617 :type 'boolean)
3619 (defcustom org-hide-emphasis-markers nil
3620 "Non-nil mean font-lock should hide the emphasis marker characters."
3621 :group 'org-appearance
3622 :type 'boolean)
3624 (defcustom org-pretty-entities nil
3625 "Non-nil means show entities as UTF8 characters.
3626 When nil, the \\name form remains in the buffer."
3627 :group 'org-appearance
3628 :version "24.1"
3629 :type 'boolean)
3631 (defcustom org-pretty-entities-include-sub-superscripts t
3632 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3633 :group 'org-appearance
3634 :version "24.1"
3635 :type 'boolean)
3637 (defvar org-emph-re nil
3638 "Regular expression for matching emphasis.
3639 After a match, the match groups contain these elements:
3640 0 The match of the full regular expression, including the characters
3641 before and after the proper match
3642 1 The character before the proper match, or empty at beginning of line
3643 2 The proper match, including the leading and trailing markers
3644 3 The leading marker like * or /, indicating the type of highlighting
3645 4 The text between the emphasis markers, not including the markers
3646 5 The character after the match, empty at the end of a line")
3647 (defvar org-verbatim-re nil
3648 "Regular expression for matching verbatim text.")
3649 (defvar org-emphasis-regexp-components) ; defined just below
3650 (defvar org-emphasis-alist) ; defined just below
3651 (defun org-set-emph-re (var val)
3652 "Set variable and compute the emphasis regular expression."
3653 (set var val)
3654 (when (and (boundp 'org-emphasis-alist)
3655 (boundp 'org-emphasis-regexp-components)
3656 org-emphasis-alist org-emphasis-regexp-components)
3657 (let* ((e org-emphasis-regexp-components)
3658 (pre (car e))
3659 (post (nth 1 e))
3660 (border (nth 2 e))
3661 (body (nth 3 e))
3662 (nl (nth 4 e))
3663 (body1 (concat body "*?"))
3664 (markers (mapconcat 'car org-emphasis-alist ""))
3665 (vmarkers (mapconcat
3666 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3667 org-emphasis-alist "")))
3668 ;; make sure special characters appear at the right position in the class
3669 (if (string-match "\\^" markers)
3670 (setq markers (concat (replace-match "" t t markers) "^")))
3671 (if (string-match "-" markers)
3672 (setq markers (concat (replace-match "" t t markers) "-")))
3673 (if (string-match "\\^" vmarkers)
3674 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3675 (if (string-match "-" vmarkers)
3676 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3677 (if (> nl 0)
3678 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3679 (int-to-string nl) "\\}")))
3680 ;; Make the regexp
3681 (setq org-emph-re
3682 (concat "\\([" pre "]\\|^\\)"
3683 "\\("
3684 "\\([" markers "]\\)"
3685 "\\("
3686 "[^" border "]\\|"
3687 "[^" border "]"
3688 body1
3689 "[^" border "]"
3690 "\\)"
3691 "\\3\\)"
3692 "\\([" post "]\\|$\\)"))
3693 (setq org-verbatim-re
3694 (concat "\\([" pre "]\\|^\\)"
3695 "\\("
3696 "\\([" vmarkers "]\\)"
3697 "\\("
3698 "[^" border "]\\|"
3699 "[^" border "]"
3700 body1
3701 "[^" border "]"
3702 "\\)"
3703 "\\3\\)"
3704 "\\([" post "]\\|$\\)")))))
3706 (defcustom org-emphasis-regexp-components
3707 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3708 "Components used to build the regular expression for emphasis.
3709 This is a list with five entries. Terminology: In an emphasis string
3710 like \" *strong word* \", we call the initial space PREMATCH, the final
3711 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3712 and \"trong wor\" is the body. The different components in this variable
3713 specify what is allowed/forbidden in each part:
3715 pre Chars allowed as prematch. Beginning of line will be allowed too.
3716 post Chars allowed as postmatch. End of line will be allowed too.
3717 border The chars *forbidden* as border characters.
3718 body-regexp A regexp like \".\" to match a body character. Don't use
3719 non-shy groups here, and don't allow newline here.
3720 newline The maximum number of newlines allowed in an emphasis exp.
3722 Use customize to modify this, or restart Emacs after changing it."
3723 :group 'org-appearance
3724 :set 'org-set-emph-re
3725 :type '(list
3726 (sexp :tag "Allowed chars in pre ")
3727 (sexp :tag "Allowed chars in post ")
3728 (sexp :tag "Forbidden chars in border ")
3729 (sexp :tag "Regexp for body ")
3730 (integer :tag "number of newlines allowed")
3731 (option (boolean :tag "Please ignore this button"))))
3733 (defcustom org-emphasis-alist
3734 `(("*" bold "<b>" "</b>")
3735 ("/" italic "<i>" "</i>")
3736 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3737 ("=" org-code "<code>" "</code>" verbatim)
3738 ("~" org-verbatim "<code>" "</code>" verbatim)
3739 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3740 "<del>" "</del>")
3742 "Special syntax for emphasized text.
3743 Text starting and ending with a special character will be emphasized, for
3744 example *bold*, _underlined_ and /italic/. This variable sets the marker
3745 characters, the face to be used by font-lock for highlighting in Org-mode
3746 Emacs buffers, and the HTML tags to be used for this.
3747 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3748 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3749 Use customize to modify this, or restart Emacs after changing it."
3750 :group 'org-appearance
3751 :set 'org-set-emph-re
3752 :type '(repeat
3753 (list
3754 (string :tag "Marker character")
3755 (choice
3756 (face :tag "Font-lock-face")
3757 (plist :tag "Face property list"))
3758 (string :tag "HTML start tag")
3759 (string :tag "HTML end tag")
3760 (option (const verbatim)))))
3762 (defvar org-protecting-blocks
3763 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3764 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3765 This is needed for font-lock setup.")
3767 ;;; Miscellaneous options
3769 (defgroup org-completion nil
3770 "Completion in Org-mode."
3771 :tag "Org Completion"
3772 :group 'org)
3774 (defcustom org-completion-use-ido nil
3775 "Non-nil means use ido completion wherever possible.
3776 Note that `ido-mode' must be active for this variable to be relevant.
3777 If you decide to turn this variable on, you might well want to turn off
3778 `org-outline-path-complete-in-steps'.
3779 See also `org-completion-use-iswitchb'."
3780 :group 'org-completion
3781 :type 'boolean)
3783 (defcustom org-completion-use-iswitchb nil
3784 "Non-nil means use iswitchb completion wherever possible.
3785 Note that `iswitchb-mode' must be active for this variable to be relevant.
3786 If you decide to turn this variable on, you might well want to turn off
3787 `org-outline-path-complete-in-steps'.
3788 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3789 :group 'org-completion
3790 :type 'boolean)
3792 (defcustom org-completion-fallback-command 'hippie-expand
3793 "The expansion command called by \\[pcomplete] in normal context.
3794 Normal means, no org-mode-specific context."
3795 :group 'org-completion
3796 :type 'function)
3798 ;;; Functions and variables from their packages
3799 ;; Declared here to avoid compiler warnings
3801 ;; XEmacs only
3802 (defvar outline-mode-menu-heading)
3803 (defvar outline-mode-menu-show)
3804 (defvar outline-mode-menu-hide)
3805 (defvar zmacs-regions) ; XEmacs regions
3807 ;; Emacs only
3808 (defvar mark-active)
3810 ;; Various packages
3811 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3812 (declare-function calendar-forward-day "cal-move" (arg))
3813 (declare-function calendar-goto-date "cal-move" (date))
3814 (declare-function calendar-goto-today "cal-move" ())
3815 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3816 (defvar calc-embedded-close-formula)
3817 (defvar calc-embedded-open-formula)
3818 (declare-function cdlatex-tab "ext:cdlatex" ())
3819 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3820 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3821 (defvar font-lock-unfontify-region-function)
3822 (declare-function iswitchb-read-buffer "iswitchb"
3823 (prompt &optional default require-match start matches-set))
3824 (defvar iswitchb-temp-buflist)
3825 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3826 (defvar org-agenda-tags-todo-honor-ignore-options)
3827 (declare-function org-agenda-skip "org-agenda" ())
3828 (declare-function
3829 org-agenda-format-item "org-agenda"
3830 (extra txt &optional category tags dotime noprefix remove-re habitp))
3831 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3832 (declare-function org-agenda-change-all-lines "org-agenda"
3833 (newhead hdmarker &optional fixface just-this))
3834 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3835 (declare-function org-agenda-maybe-redo "org-agenda" ())
3836 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3837 (beg end))
3838 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3839 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3840 "org-agenda" (&optional end))
3841 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3842 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3843 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3844 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3845 (declare-function org-indent-mode "org-indent" (&optional arg))
3846 (declare-function parse-time-string "parse-time" (string))
3847 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3848 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3849 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3850 (defvar remember-data-file)
3851 (defvar texmathp-why)
3852 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3853 (declare-function table--at-cell-p "table" (position &optional object at-column))
3855 (defvar w3m-current-url)
3856 (defvar w3m-current-title)
3858 (defvar org-latex-regexps)
3860 ;;; Autoload and prepare some org modules
3862 ;; Some table stuff that needs to be defined here, because it is used
3863 ;; by the functions setting up org-mode or checking for table context.
3865 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3866 "Detect an org-type or table-type table.")
3867 (defconst org-table-line-regexp "^[ \t]*|"
3868 "Detect an org-type table line.")
3869 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3870 "Detect an org-type table line.")
3871 (defconst org-table-hline-regexp "^[ \t]*|-"
3872 "Detect an org-type table hline.")
3873 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3874 "Detect a table-type table hline.")
3875 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3876 "Detect the first line outside a table when searching from within it.
3877 This works for both table types.")
3879 ;; Autoload the functions in org-table.el that are needed by functions here.
3881 (eval-and-compile
3882 (org-autoload "org-table"
3883 '(org-table-begin org-table-blank-field org-table-end)))
3885 ;;;###autoload
3886 (defun turn-on-orgtbl ()
3887 "Unconditionally turn on `orgtbl-mode'."
3888 (require 'org-table)
3889 (orgtbl-mode 1))
3891 (defun org-at-table-p (&optional table-type)
3892 "Return t if the cursor is inside an org-type table.
3893 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3894 (if org-enable-table-editor
3895 (save-excursion
3896 (beginning-of-line 1)
3897 (looking-at (if table-type org-table-any-line-regexp
3898 org-table-line-regexp)))
3899 nil))
3900 (defsubst org-table-p () (org-at-table-p))
3902 (defun org-at-table.el-p ()
3903 "Return t if and only if we are at a table.el table."
3904 (and (org-at-table-p 'any)
3905 (save-excursion
3906 (goto-char (org-table-begin 'any))
3907 (looking-at org-table1-hline-regexp))))
3908 (defun org-table-recognize-table.el ()
3909 "If there is a table.el table nearby, recognize it and move into it."
3910 (if org-table-tab-recognizes-table.el
3911 (if (org-at-table.el-p)
3912 (progn
3913 (beginning-of-line 1)
3914 (if (looking-at org-table-dataline-regexp)
3916 (if (looking-at org-table1-hline-regexp)
3917 (progn
3918 (beginning-of-line 2)
3919 (if (looking-at org-table-any-border-regexp)
3920 (beginning-of-line -1)))))
3921 (if (re-search-forward "|" (org-table-end t) t)
3922 (progn
3923 (require 'table)
3924 (if (table--at-cell-p (point))
3926 (message "recognizing table.el table...")
3927 (table-recognize-table)
3928 (message "recognizing table.el table...done")))
3929 (error "This should not happen"))
3931 nil)
3932 nil))
3934 (defun org-at-table-hline-p ()
3935 "Return t if the cursor is inside a hline in a table."
3936 (if org-enable-table-editor
3937 (save-excursion
3938 (beginning-of-line 1)
3939 (looking-at org-table-hline-regexp))
3940 nil))
3942 (defvar org-table-clean-did-remove-column nil)
3944 (defun org-table-map-tables (function &optional quietly)
3945 "Apply FUNCTION to the start of all tables in the buffer."
3946 (save-excursion
3947 (save-restriction
3948 (widen)
3949 (goto-char (point-min))
3950 (while (re-search-forward org-table-any-line-regexp nil t)
3951 (unless quietly
3952 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3953 (beginning-of-line 1)
3954 (when (and (looking-at org-table-line-regexp)
3955 ;; Exclude tables in src/example/verbatim/clocktable blocks
3956 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
3957 (save-excursion (funcall function))
3958 (or (looking-at org-table-line-regexp)
3959 (forward-char 1)))
3960 (re-search-forward org-table-any-border-regexp nil 1))))
3961 (unless quietly (message "Mapping tables: done")))
3963 ;; Declare and autoload functions from org-exp.el & Co
3965 (declare-function org-default-export-plist "org-exp")
3966 (declare-function org-infile-export-plist "org-exp")
3967 (declare-function org-get-current-options "org-exp")
3969 ;; Declare and autoload functions from org-agenda.el
3971 (eval-and-compile
3972 (org-autoload "org-agenda"
3973 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3975 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
3976 (declare-function org-clock-update-mode-line "org-clock" ())
3977 (declare-function org-resolve-clocks "org-clock"
3978 (&optional also-non-dangling-p prompt last-valid))
3979 (defvar org-clock-start-time)
3980 (defvar org-clock-marker (make-marker)
3981 "Marker recording the last clock-in.")
3982 (defvar org-clock-hd-marker (make-marker)
3983 "Marker recording the last clock-in, but the headline position.")
3984 (defvar org-clock-heading ""
3985 "The heading of the current clock entry.")
3986 (defun org-clock-is-active ()
3987 "Return non-nil if clock is currently running.
3988 The return value is actually the clock marker."
3989 (marker-buffer org-clock-marker))
3991 (eval-and-compile
3992 (org-autoload "org-clock" '(org-clock-remove-overlays
3993 org-clock-update-time-maybe
3994 org-clocktable-shift)))
3996 (defun org-check-running-clock ()
3997 "Check if the current buffer contains the running clock.
3998 If yes, offer to stop it and to save the buffer with the changes."
3999 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4000 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4001 (buffer-name))))
4002 (org-clock-out)
4003 (when (y-or-n-p "Save changed buffer?")
4004 (save-buffer))))
4006 (defun org-clocktable-try-shift (dir n)
4007 "Check if this line starts a clock table, if yes, shift the time block."
4008 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4009 (org-clocktable-shift dir n)))
4011 ;;;###autoload
4012 (defun org-clock-persistence-insinuate ()
4013 "Set up hooks for clock persistence."
4014 (require 'org-clock)
4015 (add-hook 'org-mode-hook 'org-clock-load)
4016 (add-hook 'kill-emacs-hook 'org-clock-save))
4018 ;; Define the variable already here, to make sure we have it.
4019 (defvar org-indent-mode nil
4020 "Non-nil if Org-Indent mode is enabled.
4021 Use the command `org-indent-mode' to change this variable.")
4023 ;; Autoload archiving code
4024 ;; The stuff that is needed for cycling and tags has to be defined here.
4026 (defgroup org-archive nil
4027 "Options concerning archiving in Org-mode."
4028 :tag "Org Archive"
4029 :group 'org-structure)
4031 (defcustom org-archive-location "%s_archive::"
4032 "The location where subtrees should be archived.
4034 The value of this variable is a string, consisting of two parts,
4035 separated by a double-colon. The first part is a filename and
4036 the second part is a headline.
4038 When the filename is omitted, archiving happens in the same file.
4039 %s in the filename will be replaced by the current file
4040 name (without the directory part). Archiving to a different file
4041 is useful to keep archived entries from contributing to the
4042 Org-mode Agenda.
4044 The archived entries will be filed as subtrees of the specified
4045 headline. When the headline is omitted, the subtrees are simply
4046 filed away at the end of the file, as top-level entries. Also in
4047 the heading you can use %s to represent the file name, this can be
4048 useful when using the same archive for a number of different files.
4050 Here are a few examples:
4051 \"%s_archive::\"
4052 If the current file is Projects.org, archive in file
4053 Projects.org_archive, as top-level trees. This is the default.
4055 \"::* Archived Tasks\"
4056 Archive in the current file, under the top-level headline
4057 \"* Archived Tasks\".
4059 \"~/org/archive.org::\"
4060 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4062 \"~/org/archive.org::* From %s\"
4063 Archive in file ~/org/archive.org (absolute path), under headlines
4064 \"From FILENAME\" where file name is the current file name.
4066 \"~/org/datetree.org::datetree/* Finished Tasks\"
4067 The \"datetree/\" string is special, signifying to archive
4068 items to the datetree. Items are placed in either the CLOSED
4069 date of the item, or the current date if there is no CLOSED date.
4070 The heading will be a subentry to the current date. There doesn't
4071 need to be a heading, but there always needs to be a slash after
4072 datetree. For example, to store archived items directly in the
4073 datetree, use \"~/org/datetree.org::datetree/\".
4075 \"basement::** Finished Tasks\"
4076 Archive in file ./basement (relative path), as level 3 trees
4077 below the level 2 heading \"** Finished Tasks\".
4079 You may set this option on a per-file basis by adding to the buffer a
4080 line like
4082 #+ARCHIVE: basement::** Finished Tasks
4084 You may also define it locally for a subtree by setting an ARCHIVE property
4085 in the entry. If such a property is found in an entry, or anywhere up
4086 the hierarchy, it will be used."
4087 :group 'org-archive
4088 :type 'string)
4090 (defcustom org-archive-tag "ARCHIVE"
4091 "The tag that marks a subtree as archived.
4092 An archived subtree does not open during visibility cycling, and does
4093 not contribute to the agenda listings.
4094 After changing this, font-lock must be restarted in the relevant buffers to
4095 get the proper fontification."
4096 :group 'org-archive
4097 :group 'org-keywords
4098 :type 'string)
4100 (defcustom org-agenda-skip-archived-trees t
4101 "Non-nil means the agenda will skip any items located in archived trees.
4102 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4103 variable is no longer recommended, you should leave it at the value t.
4104 Instead, use the key `v' to cycle the archives-mode in the agenda."
4105 :group 'org-archive
4106 :group 'org-agenda-skip
4107 :type 'boolean)
4109 (defcustom org-columns-skip-archived-trees t
4110 "Non-nil means ignore archived trees when creating column view."
4111 :group 'org-archive
4112 :group 'org-properties
4113 :type 'boolean)
4115 (defcustom org-cycle-open-archived-trees nil
4116 "Non-nil means `org-cycle' will open archived trees.
4117 An archived tree is a tree marked with the tag ARCHIVE.
4118 When nil, archived trees will stay folded. You can still open them with
4119 normal outline commands like `show-all', but not with the cycling commands."
4120 :group 'org-archive
4121 :group 'org-cycle
4122 :type 'boolean)
4124 (defcustom org-sparse-tree-open-archived-trees nil
4125 "Non-nil means sparse tree construction shows matches in archived trees.
4126 When nil, matches in these trees are highlighted, but the trees are kept in
4127 collapsed state."
4128 :group 'org-archive
4129 :group 'org-sparse-trees
4130 :type 'boolean)
4132 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4133 "The default date type when building a sparse tree.
4134 When this is nil, a date is a scheduled or a deadline timestamp.
4135 Otherwise, these types are allowed:
4137 all: all timestamps
4138 active: only active timestamps (<...>)
4139 inactive: only inactive timestamps (<...)
4140 scheduled: only scheduled timestamps
4141 deadline: only deadline timestamps"
4142 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4143 (const :tag "All timestamps" all)
4144 (const :tag "Only active timestamps" active)
4145 (const :tag "Only inactive timestamps" inactive)
4146 (const :tag "Only scheduled timestamps" scheduled)
4147 (const :tag "Only deadline timestamps" deadline))
4148 :version "24.3"
4149 :group 'org-sparse-trees)
4151 (defun org-cycle-hide-archived-subtrees (state)
4152 "Re-hide all archived subtrees after a visibility state change."
4153 (when (and (not org-cycle-open-archived-trees)
4154 (not (memq state '(overview folded))))
4155 (save-excursion
4156 (let* ((globalp (memq state '(contents all)))
4157 (beg (if globalp (point-min) (point)))
4158 (end (if globalp (point-max) (org-end-of-subtree t))))
4159 (org-hide-archived-subtrees beg end)
4160 (goto-char beg)
4161 (if (looking-at (concat ".*:" org-archive-tag ":"))
4162 (message "%s" (substitute-command-keys
4163 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4165 (defun org-force-cycle-archived ()
4166 "Cycle subtree even if it is archived."
4167 (interactive)
4168 (setq this-command 'org-cycle)
4169 (let ((org-cycle-open-archived-trees t))
4170 (call-interactively 'org-cycle)))
4172 (defun org-hide-archived-subtrees (beg end)
4173 "Re-hide all archived subtrees after a visibility state change."
4174 (save-excursion
4175 (let* ((re (concat ":" org-archive-tag ":")))
4176 (goto-char beg)
4177 (while (re-search-forward re end t)
4178 (when (org-at-heading-p)
4179 (org-flag-subtree t)
4180 (org-end-of-subtree t))))))
4182 (declare-function outline-end-of-heading "outline" ())
4183 (declare-function outline-flag-region "outline" (from to flag))
4184 (defun org-flag-subtree (flag)
4185 (save-excursion
4186 (org-back-to-heading t)
4187 (outline-end-of-heading)
4188 (outline-flag-region (point)
4189 (progn (org-end-of-subtree t) (point))
4190 flag)))
4192 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4194 (eval-and-compile
4195 (org-autoload "org-archive"
4196 '(org-add-archive-files)))
4198 ;; Autoload Column View Code
4200 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4201 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4202 (declare-function org-columns-compute "org-colview" (property))
4204 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4205 '(org-columns-number-to-string
4206 org-columns-get-format-and-top-level
4207 org-columns-compute
4208 org-columns-remove-overlays))
4210 ;; Autoload ID code
4212 (declare-function org-id-store-link "org-id")
4213 (declare-function org-id-locations-load "org-id")
4214 (declare-function org-id-locations-save "org-id")
4215 (defvar org-id-track-globally)
4216 (org-autoload "org-id"
4217 '(org-id-new
4218 org-id-copy
4219 org-id-get-with-outline-path-completion
4220 org-id-get-with-outline-drilling))
4222 ;;; Variables for pre-computed regular expressions, all buffer local
4224 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4225 "Matches first line of a hidden block.")
4226 (make-variable-buffer-local 'org-drawer-regexp)
4227 (defvar org-todo-regexp nil
4228 "Matches any of the TODO state keywords.")
4229 (make-variable-buffer-local 'org-todo-regexp)
4230 (defvar org-not-done-regexp nil
4231 "Matches any of the TODO state keywords except the last one.")
4232 (make-variable-buffer-local 'org-not-done-regexp)
4233 (defvar org-not-done-heading-regexp nil
4234 "Matches a TODO headline that is not done.")
4235 (make-variable-buffer-local 'org-not-done-regexp)
4236 (defvar org-todo-line-regexp nil
4237 "Matches a headline and puts TODO state into group 2 if present.")
4238 (make-variable-buffer-local 'org-todo-line-regexp)
4239 (defvar org-complex-heading-regexp nil
4240 "Matches a headline and puts everything into groups:
4241 group 1: the stars
4242 group 2: The todo keyword, maybe
4243 group 3: Priority cookie
4244 group 4: True headline
4245 group 5: Tags")
4246 (make-variable-buffer-local 'org-complex-heading-regexp)
4247 (defvar org-complex-heading-regexp-format nil
4248 "Printf format to make regexp to match an exact headline.
4249 This regexp will match the headline of any node which has the
4250 exact headline text that is put into the format, but may have any
4251 TODO state, priority and tags.")
4252 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4253 (defvar org-todo-line-tags-regexp nil
4254 "Matches a headline and puts TODO state into group 2 if present.
4255 Also put tags into group 4 if tags are present.")
4256 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4257 (defvar org-ds-keyword-length 12
4258 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4259 (make-variable-buffer-local 'org-ds-keyword-length)
4260 (defvar org-deadline-regexp nil
4261 "Matches the DEADLINE keyword.")
4262 (make-variable-buffer-local 'org-deadline-regexp)
4263 (defvar org-deadline-time-regexp nil
4264 "Matches the DEADLINE keyword together with a time stamp.")
4265 (make-variable-buffer-local 'org-deadline-time-regexp)
4266 (defvar org-deadline-line-regexp nil
4267 "Matches the DEADLINE keyword and the rest of the line.")
4268 (make-variable-buffer-local 'org-deadline-line-regexp)
4269 (defvar org-scheduled-regexp nil
4270 "Matches the SCHEDULED keyword.")
4271 (make-variable-buffer-local 'org-scheduled-regexp)
4272 (defvar org-scheduled-time-regexp nil
4273 "Matches the SCHEDULED keyword together with a time stamp.")
4274 (make-variable-buffer-local 'org-scheduled-time-regexp)
4275 (defvar org-closed-time-regexp nil
4276 "Matches the CLOSED keyword together with a time stamp.")
4277 (make-variable-buffer-local 'org-closed-time-regexp)
4279 (defvar org-keyword-time-regexp nil
4280 "Matches any of the 4 keywords, together with the time stamp.")
4281 (make-variable-buffer-local 'org-keyword-time-regexp)
4282 (defvar org-keyword-time-not-clock-regexp nil
4283 "Matches any of the 3 keywords, together with the time stamp.")
4284 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4285 (defvar org-maybe-keyword-time-regexp nil
4286 "Matches a timestamp, possibly preceded by a keyword.")
4287 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4288 (defvar org-all-time-keywords nil
4289 "List of time keywords.")
4290 (make-variable-buffer-local 'org-all-time-keywords)
4292 (defconst org-plain-time-of-day-regexp
4293 (concat
4294 "\\(\\<[012]?[0-9]"
4295 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4296 "\\(--?"
4297 "\\(\\<[012]?[0-9]"
4298 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4299 "\\)?")
4300 "Regular expression to match a plain time or time range.
4301 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4302 groups carry important information:
4303 0 the full match
4304 1 the first time, range or not
4305 8 the second time, if it is a range.")
4307 (defconst org-plain-time-extension-regexp
4308 (concat
4309 "\\(\\<[012]?[0-9]"
4310 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4311 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4312 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4313 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4314 groups carry important information:
4315 0 the full match
4316 7 hours of duration
4317 9 minutes of duration")
4319 (defconst org-stamp-time-of-day-regexp
4320 (concat
4321 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4322 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4323 "\\(--?"
4324 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4325 "Regular expression to match a timestamp time or time range.
4326 After a match, the following groups carry important information:
4327 0 the full match
4328 1 date plus weekday, for back referencing to make sure both times are on the same day
4329 2 the first time, range or not
4330 4 the second time, if it is a range.")
4332 (defconst org-startup-options
4333 '(("fold" org-startup-folded t)
4334 ("overview" org-startup-folded t)
4335 ("nofold" org-startup-folded nil)
4336 ("showall" org-startup-folded nil)
4337 ("showeverything" org-startup-folded showeverything)
4338 ("content" org-startup-folded content)
4339 ("indent" org-startup-indented t)
4340 ("noindent" org-startup-indented nil)
4341 ("hidestars" org-hide-leading-stars t)
4342 ("showstars" org-hide-leading-stars nil)
4343 ("odd" org-odd-levels-only t)
4344 ("oddeven" org-odd-levels-only nil)
4345 ("align" org-startup-align-all-tables t)
4346 ("noalign" org-startup-align-all-tables nil)
4347 ("inlineimages" org-startup-with-inline-images t)
4348 ("noinlineimages" org-startup-with-inline-images nil)
4349 ("customtime" org-display-custom-times t)
4350 ("logdone" org-log-done time)
4351 ("lognotedone" org-log-done note)
4352 ("nologdone" org-log-done nil)
4353 ("lognoteclock-out" org-log-note-clock-out t)
4354 ("nolognoteclock-out" org-log-note-clock-out nil)
4355 ("logrepeat" org-log-repeat state)
4356 ("lognoterepeat" org-log-repeat note)
4357 ("nologrepeat" org-log-repeat nil)
4358 ("logreschedule" org-log-reschedule time)
4359 ("lognotereschedule" org-log-reschedule note)
4360 ("nologreschedule" org-log-reschedule nil)
4361 ("logredeadline" org-log-redeadline time)
4362 ("lognoteredeadline" org-log-redeadline note)
4363 ("nologredeadline" org-log-redeadline nil)
4364 ("logrefile" org-log-refile time)
4365 ("lognoterefile" org-log-refile note)
4366 ("nologrefile" org-log-refile nil)
4367 ("fninline" org-footnote-define-inline t)
4368 ("nofninline" org-footnote-define-inline nil)
4369 ("fnlocal" org-footnote-section nil)
4370 ("fnauto" org-footnote-auto-label t)
4371 ("fnprompt" org-footnote-auto-label nil)
4372 ("fnconfirm" org-footnote-auto-label confirm)
4373 ("fnplain" org-footnote-auto-label plain)
4374 ("fnadjust" org-footnote-auto-adjust t)
4375 ("nofnadjust" org-footnote-auto-adjust nil)
4376 ("constcgs" constants-unit-system cgs)
4377 ("constSI" constants-unit-system SI)
4378 ("noptag" org-tag-persistent-alist nil)
4379 ("hideblocks" org-hide-block-startup t)
4380 ("nohideblocks" org-hide-block-startup nil)
4381 ("beamer" org-startup-with-beamer-mode t)
4382 ("entitiespretty" org-pretty-entities t)
4383 ("entitiesplain" org-pretty-entities nil))
4384 "Variable associated with STARTUP options for org-mode.
4385 Each element is a list of three items: the startup options (as written
4386 in the #+STARTUP line), the corresponding variable, and the value to set
4387 this variable to if the option is found. An optional forth element PUSH
4388 means to push this value onto the list in the variable.")
4390 (defun org-update-property-plist (key val props)
4391 "Update PROPS with KEY and VAL."
4392 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4393 (key (if appending (substring key 0 (- (length key) 1)) key))
4394 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4395 (previous (cdr (assoc key props))))
4396 (if appending
4397 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4398 (cons (cons key val) remainder))))
4400 (defconst org-block-regexp
4401 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4402 "Regular expression for hiding blocks.")
4403 (defconst org-heading-keyword-regexp-format
4404 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4405 "Printf format for a regexp matching an headline with some keyword.
4406 This regexp will match the headline of any node which has the
4407 exact keyword that is put into the format. The keyword isn't in
4408 any group by default, but the stars and the body are.")
4409 (defconst org-heading-keyword-maybe-regexp-format
4410 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4411 "Printf format for a regexp matching an headline, possibly with some keyword.
4412 This regexp can match any headline with the specified keyword, or
4413 without a keyword. The keyword isn't in any group by default,
4414 but the stars and the body are.")
4416 (defun org-set-regexps-and-options ()
4417 "Precompute regular expressions for current buffer."
4418 (when (derived-mode-p 'org-mode)
4419 (org-set-local 'org-todo-kwd-alist nil)
4420 (org-set-local 'org-todo-key-alist nil)
4421 (org-set-local 'org-todo-key-trigger nil)
4422 (org-set-local 'org-todo-keywords-1 nil)
4423 (org-set-local 'org-done-keywords nil)
4424 (org-set-local 'org-todo-heads nil)
4425 (org-set-local 'org-todo-sets nil)
4426 (org-set-local 'org-todo-log-states nil)
4427 (org-set-local 'org-file-properties nil)
4428 (org-set-local 'org-file-tags nil)
4429 (let ((re (org-make-options-regexp
4430 '("CATEGORY" "TODO" "COLUMNS"
4431 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4432 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4433 "OPTIONS")
4434 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4435 (splitre "[ \t]+")
4436 (scripts org-use-sub-superscripts)
4437 kwds kws0 kwsa key log value cat arch tags const links hw dws
4438 tail sep kws1 prio props ftags drawers beamer-p
4439 ext-setup-or-nil setup-contents (start 0))
4440 (save-excursion
4441 (save-restriction
4442 (widen)
4443 (goto-char (point-min))
4444 (while (or (and ext-setup-or-nil
4445 (string-match re ext-setup-or-nil start)
4446 (setq start (match-end 0)))
4447 (and (setq ext-setup-or-nil nil start 0)
4448 (re-search-forward re nil t)))
4449 (setq key (upcase (match-string 1 ext-setup-or-nil))
4450 value (org-match-string-no-properties 2 ext-setup-or-nil))
4451 (if (stringp value) (setq value (org-trim value)))
4452 (cond
4453 ((equal key "CATEGORY")
4454 (setq cat value))
4455 ((member key '("SEQ_TODO" "TODO"))
4456 (push (cons 'sequence (org-split-string value splitre)) kwds))
4457 ((equal key "TYP_TODO")
4458 (push (cons 'type (org-split-string value splitre)) kwds))
4459 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4460 ;; general TODO-like setup
4461 (push (cons (intern (downcase (match-string 1 key)))
4462 (org-split-string value splitre)) kwds))
4463 ((equal key "TAGS")
4464 (setq tags (append tags (if tags '("\\n") nil)
4465 (org-split-string value splitre))))
4466 ((equal key "COLUMNS")
4467 (org-set-local 'org-columns-default-format value))
4468 ((equal key "LINK")
4469 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4470 (push (cons (match-string 1 value)
4471 (org-trim (match-string 2 value)))
4472 links)))
4473 ((equal key "PRIORITIES")
4474 (setq prio (org-split-string value " +")))
4475 ((equal key "PROPERTY")
4476 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4477 (setq props (org-update-property-plist (match-string 1 value)
4478 (match-string 2 value)
4479 props))))
4480 ((equal key "FILETAGS")
4481 (when (string-match "\\S-" value)
4482 (setq ftags
4483 (append
4484 ftags
4485 (apply 'append
4486 (mapcar (lambda (x) (org-split-string x ":"))
4487 (org-split-string value)))))))
4488 ((equal key "DRAWERS")
4489 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4490 ((equal key "CONSTANTS")
4491 (setq const (append const (org-split-string value splitre))))
4492 ((equal key "STARTUP")
4493 (let ((opts (org-split-string value splitre))
4494 l var val)
4495 (while (setq l (pop opts))
4496 (when (setq l (assoc l org-startup-options))
4497 (setq var (nth 1 l) val (nth 2 l))
4498 (if (not (nth 3 l))
4499 (set (make-local-variable var) val)
4500 (if (not (listp (symbol-value var)))
4501 (set (make-local-variable var) nil))
4502 (set (make-local-variable var) (symbol-value var))
4503 (add-to-list var val))))))
4504 ((equal key "ARCHIVE")
4505 (setq arch value)
4506 (remove-text-properties 0 (length arch)
4507 '(face t fontified t) arch))
4508 ((equal key "LATEX_CLASS")
4509 (setq beamer-p (equal value "beamer")))
4510 ((equal key "OPTIONS")
4511 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4512 (setq scripts (read (match-string 2 value)))))
4513 ((equal key "SETUPFILE")
4514 (setq setup-contents (org-file-contents
4515 (expand-file-name
4516 (org-remove-double-quotes value))
4517 'noerror))
4518 (if (not ext-setup-or-nil)
4519 (setq ext-setup-or-nil setup-contents start 0)
4520 (setq ext-setup-or-nil
4521 (concat (substring ext-setup-or-nil 0 start)
4522 "\n" setup-contents "\n"
4523 (substring ext-setup-or-nil start)))))))
4524 ;; search for property blocks
4525 (goto-char (point-min))
4526 (while (re-search-forward org-block-regexp nil t)
4527 (when (equal "PROPERTY" (upcase (match-string 1)))
4528 (setq value (replace-regexp-in-string
4529 "[\n\r]" " " (match-string 4)))
4530 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4531 (setq props (org-update-property-plist (match-string 1 value)
4532 (match-string 2 value)
4533 props)))))))
4534 (org-set-local 'org-use-sub-superscripts scripts)
4535 (when cat
4536 (org-set-local 'org-category (intern cat))
4537 (push (cons "CATEGORY" cat) props))
4538 (when prio
4539 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4540 (setq prio (mapcar 'string-to-char prio))
4541 (org-set-local 'org-highest-priority (nth 0 prio))
4542 (org-set-local 'org-lowest-priority (nth 1 prio))
4543 (org-set-local 'org-default-priority (nth 2 prio)))
4544 (and props (org-set-local 'org-file-properties (nreverse props)))
4545 (and ftags (org-set-local 'org-file-tags
4546 (mapcar 'org-add-prop-inherited ftags)))
4547 (and drawers (org-set-local 'org-drawers drawers))
4548 (and arch (org-set-local 'org-archive-location arch))
4549 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4550 ;; Process the TODO keywords
4551 (unless kwds
4552 ;; Use the global values as if they had been given locally.
4553 (setq kwds (default-value 'org-todo-keywords))
4554 (if (stringp (car kwds))
4555 (setq kwds (list (cons org-todo-interpretation
4556 (default-value 'org-todo-keywords)))))
4557 (setq kwds (reverse kwds)))
4558 (setq kwds (nreverse kwds))
4559 (let (inter kws kw)
4560 (while (setq kws (pop kwds))
4561 (let ((kws (or
4562 (run-hook-with-args-until-success
4563 'org-todo-setup-filter-hook kws)
4564 kws)))
4565 (setq inter (pop kws) sep (member "|" kws)
4566 kws0 (delete "|" (copy-sequence kws))
4567 kwsa nil
4568 kws1 (mapcar
4569 (lambda (x)
4570 ;; 1 2
4571 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4572 (progn
4573 (setq kw (match-string 1 x)
4574 key (and (match-end 2) (match-string 2 x))
4575 log (org-extract-log-state-settings x))
4576 (push (cons kw (and key (string-to-char key))) kwsa)
4577 (and log (push log org-todo-log-states))
4579 (error "Invalid TODO keyword %s" x)))
4580 kws0)
4581 kwsa (if kwsa (append '((:startgroup))
4582 (nreverse kwsa)
4583 '((:endgroup))))
4584 hw (car kws1)
4585 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4586 tail (list inter hw (car dws) (org-last dws))))
4587 (add-to-list 'org-todo-heads hw 'append)
4588 (push kws1 org-todo-sets)
4589 (setq org-done-keywords (append org-done-keywords dws nil))
4590 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4591 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4592 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4593 (setq org-todo-sets (nreverse org-todo-sets)
4594 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4595 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4596 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4597 ;; Process the constants
4598 (when const
4599 (let (e cst)
4600 (while (setq e (pop const))
4601 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4602 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4603 (setq org-table-formula-constants-local cst)))
4605 ;; Process the tags.
4606 (when tags
4607 (let (e tgs)
4608 (while (setq e (pop tags))
4609 (cond
4610 ((equal e "{") (push '(:startgroup) tgs))
4611 ((equal e "}") (push '(:endgroup) tgs))
4612 ((equal e "\\n") (push '(:newline) tgs))
4613 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4614 (push (cons (match-string 1 e)
4615 (string-to-char (match-string 2 e)))
4616 tgs))
4617 (t (push (list e) tgs))))
4618 (org-set-local 'org-tag-alist nil)
4619 (while (setq e (pop tgs))
4620 (or (and (stringp (car e))
4621 (assoc (car e) org-tag-alist))
4622 (push e org-tag-alist)))))
4624 ;; Compute the regular expressions and other local variables.
4625 ;; Using `org-outline-regexp-bol' would complicate them much,
4626 ;; because of the fixed white space at the end of that string.
4627 (if (not org-done-keywords)
4628 (setq org-done-keywords (and org-todo-keywords-1
4629 (list (org-last org-todo-keywords-1)))))
4630 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4631 (length org-scheduled-string)
4632 (length org-clock-string)
4633 (length org-closed-string)))
4634 org-drawer-regexp
4635 (concat "^[ \t]*:\\("
4636 (mapconcat 'regexp-quote org-drawers "\\|")
4637 "\\):[ \t]*$")
4638 org-not-done-keywords
4639 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4640 org-todo-regexp
4641 (concat "\\("
4642 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4643 "\\)")
4644 org-not-done-regexp
4645 (concat "\\("
4646 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4647 "\\)")
4648 org-not-done-heading-regexp
4649 (format org-heading-keyword-regexp-format org-not-done-regexp)
4650 org-todo-line-regexp
4651 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4652 org-complex-heading-regexp
4653 (concat "^\\(\\*+\\)"
4654 "\\(?: +" org-todo-regexp "\\)?"
4655 "\\(?: +\\(\\[#.\\]\\)\\)?"
4656 "\\(?: +\\(.*?\\)\\)??"
4657 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4658 "[ \t]*$")
4659 org-complex-heading-regexp-format
4660 (concat "^\\(\\*+\\)"
4661 "\\(?: +" org-todo-regexp "\\)?"
4662 "\\(?: +\\(\\[#.\\]\\)\\)?"
4663 "\\(?: +"
4664 ;; Stats cookies can be stuck to body.
4665 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4666 "\\(%s\\)"
4667 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4668 "\\)"
4669 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4670 "[ \t]*$")
4671 org-todo-line-tags-regexp
4672 (concat "^\\(\\*+\\)"
4673 "\\(?: +" org-todo-regexp "\\)?"
4674 "\\(?: +\\(.*?\\)\\)??"
4675 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4676 "[ \t]*$")
4677 org-deadline-regexp (concat "\\<" org-deadline-string)
4678 org-deadline-time-regexp
4679 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4680 org-deadline-line-regexp
4681 (concat "\\<\\(" org-deadline-string "\\).*")
4682 org-scheduled-regexp
4683 (concat "\\<" org-scheduled-string)
4684 org-scheduled-time-regexp
4685 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4686 org-closed-time-regexp
4687 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4688 org-keyword-time-regexp
4689 (concat "\\<\\(" org-scheduled-string
4690 "\\|" org-deadline-string
4691 "\\|" org-closed-string
4692 "\\|" org-clock-string "\\)"
4693 " *[[<]\\([^]>]+\\)[]>]")
4694 org-keyword-time-not-clock-regexp
4695 (concat "\\<\\(" org-scheduled-string
4696 "\\|" org-deadline-string
4697 "\\|" org-closed-string
4698 "\\)"
4699 " *[[<]\\([^]>]+\\)[]>]")
4700 org-maybe-keyword-time-regexp
4701 (concat "\\(\\<\\(" org-scheduled-string
4702 "\\|" org-deadline-string
4703 "\\|" org-closed-string
4704 "\\|" org-clock-string "\\)\\)?"
4705 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4706 org-all-time-keywords
4707 (mapcar (lambda (w) (substring w 0 -1))
4708 (list org-scheduled-string org-deadline-string
4709 org-clock-string org-closed-string))
4711 (org-compute-latex-and-specials-regexp)
4712 (org-set-font-lock-defaults))))
4714 (defun org-file-contents (file &optional noerror)
4715 "Return the contents of FILE, as a string."
4716 (if (or (not file)
4717 (not (file-readable-p file)))
4718 (if noerror
4719 (progn
4720 (message "Cannot read file \"%s\"" file)
4721 (ding) (sit-for 2)
4723 (error "Cannot read file \"%s\"" file))
4724 (with-temp-buffer
4725 (insert-file-contents file)
4726 (buffer-string))))
4728 (defun org-extract-log-state-settings (x)
4729 "Extract the log state setting from a TODO keyword string.
4730 This will extract info from a string like \"WAIT(w@/!)\"."
4731 (let (kw key log1 log2)
4732 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4733 (setq kw (match-string 1 x)
4734 key (and (match-end 2) (match-string 2 x))
4735 log1 (and (match-end 3) (match-string 3 x))
4736 log2 (and (match-end 4) (match-string 4 x)))
4737 (and (or log1 log2)
4738 (list kw
4739 (and log1 (if (equal log1 "!") 'time 'note))
4740 (and log2 (if (equal log2 "!") 'time 'note)))))))
4742 (defun org-remove-keyword-keys (list)
4743 "Remove a pair of parenthesis at the end of each string in LIST."
4744 (mapcar (lambda (x)
4745 (if (string-match "(.*)$" x)
4746 (substring x 0 (match-beginning 0))
4748 list))
4750 (defun org-assign-fast-keys (alist)
4751 "Assign fast keys to a keyword-key alist.
4752 Respect keys that are already there."
4753 (let (new e (alt ?0))
4754 (while (setq e (pop alist))
4755 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4756 (cdr e)) ;; Key already assigned.
4757 (push e new)
4758 (let ((clist (string-to-list (downcase (car e))))
4759 (used (append new alist)))
4760 (when (= (car clist) ?@)
4761 (pop clist))
4762 (while (and clist (rassoc (car clist) used))
4763 (pop clist))
4764 (unless clist
4765 (while (rassoc alt used)
4766 (incf alt)))
4767 (push (cons (car e) (or (car clist) alt)) new))))
4768 (nreverse new)))
4770 ;;; Some variables used in various places
4772 (defvar org-window-configuration nil
4773 "Used in various places to store a window configuration.")
4774 (defvar org-selected-window nil
4775 "Used in various places to store a window configuration.")
4776 (defvar org-finish-function nil
4777 "Function to be called when `C-c C-c' is used.
4778 This is for getting out of special buffers like capture.")
4781 ;; FIXME: Occasionally check by commenting these, to make sure
4782 ;; no other functions uses these, forgetting to let-bind them.
4783 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4784 (defvar org-last-state)
4785 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4787 ;; Defined somewhere in this file, but used before definition.
4788 (defvar org-entities) ;; defined in org-entities.el
4789 (defvar org-struct-menu)
4790 (defvar org-org-menu)
4791 (defvar org-tbl-menu)
4793 ;;;; Define the Org-mode
4795 ;; We use a before-change function to check if a table might need
4796 ;; an update.
4797 (defvar org-table-may-need-update t
4798 "Indicates that a table might need an update.
4799 This variable is set by `org-before-change-function'.
4800 `org-table-align' sets it back to nil.")
4801 (defun org-before-change-function (beg end)
4802 "Every change indicates that a table might need an update."
4803 (setq org-table-may-need-update t))
4804 (defvar org-mode-map)
4805 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4806 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4807 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4808 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4809 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4810 (defvar org-table-buffer-is-an nil)
4812 (defvar bidi-paragraph-direction)
4813 (defvar buffer-face-mode-face)
4815 (require 'outline)
4816 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4817 (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"))
4818 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4820 ;; Other stuff we need.
4821 (require 'time-date)
4822 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4823 (require 'easymenu)
4824 (require 'overlay)
4826 (require 'org-macs)
4827 (require 'org-entities)
4828 ;; (require 'org-compat) moved higher up in the file before it is first used
4829 (require 'org-faces)
4830 (require 'org-list)
4831 (require 'org-pcomplete)
4832 (require 'org-src)
4833 (require 'org-footnote)
4835 ;; babel
4836 (require 'ob)
4837 (require 'ob-table)
4838 (require 'ob-lob)
4839 (require 'ob-ref)
4840 (require 'ob-tangle)
4841 (require 'ob-comint)
4842 (require 'ob-keys)
4844 ;;;###autoload
4845 (define-derived-mode org-mode outline-mode "Org"
4846 "Outline-based notes management and organizer, alias
4847 \"Carsten's outline-mode for keeping track of everything.\"
4849 Org-mode develops organizational tasks around a NOTES file which
4850 contains information about projects as plain text. Org-mode is
4851 implemented on top of outline-mode, which is ideal to keep the content
4852 of large files well structured. It supports ToDo items, deadlines and
4853 time stamps, which magically appear in the diary listing of the Emacs
4854 calendar. Tables are easily created with a built-in table editor.
4855 Plain text URL-like links connect to websites, emails (VM), Usenet
4856 messages (Gnus), BBDB entries, and any files related to the project.
4857 For printing and sharing of notes, an Org-mode file (or a part of it)
4858 can be exported as a structured ASCII or HTML file.
4860 The following commands are available:
4862 \\{org-mode-map}"
4864 ;; Get rid of Outline menus, they are not needed
4865 ;; Need to do this here because define-derived-mode sets up
4866 ;; the keymap so late. Still, it is a waste to call this each time
4867 ;; we switch another buffer into org-mode.
4868 (if (featurep 'xemacs)
4869 (when (boundp 'outline-mode-menu-heading)
4870 ;; Assume this is Greg's port, it uses easymenu
4871 (easy-menu-remove outline-mode-menu-heading)
4872 (easy-menu-remove outline-mode-menu-show)
4873 (easy-menu-remove outline-mode-menu-hide))
4874 (define-key org-mode-map [menu-bar headings] 'undefined)
4875 (define-key org-mode-map [menu-bar hide] 'undefined)
4876 (define-key org-mode-map [menu-bar show] 'undefined))
4878 (org-load-modules-maybe)
4879 (easy-menu-add org-org-menu)
4880 (easy-menu-add org-tbl-menu)
4881 (org-install-agenda-files-menu)
4882 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4883 (add-to-invisibility-spec '(org-cwidth))
4884 (add-to-invisibility-spec '(org-hide-block . t))
4885 (when (featurep 'xemacs)
4886 (org-set-local 'line-move-ignore-invisible t))
4887 (org-set-local 'outline-regexp org-outline-regexp)
4888 (org-set-local 'outline-level 'org-outline-level)
4889 (setq bidi-paragraph-direction 'left-to-right)
4890 (when (and org-ellipsis
4891 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4892 (fboundp 'make-glyph-code))
4893 (unless org-display-table
4894 (setq org-display-table (make-display-table)))
4895 (set-display-table-slot
4896 org-display-table 4
4897 (vconcat (mapcar
4898 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4899 org-ellipsis)))
4900 (if (stringp org-ellipsis) org-ellipsis "..."))))
4901 (setq buffer-display-table org-display-table))
4902 (org-set-regexps-and-options)
4903 (when (and org-tag-faces (not org-tags-special-faces-re))
4904 ;; tag faces set outside customize.... force initialization.
4905 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4906 ;; Calc embedded
4907 (org-set-local 'calc-embedded-open-mode "# ")
4908 (modify-syntax-entry ?@ "w")
4909 (if org-startup-truncated (setq truncate-lines t))
4910 (org-set-local 'font-lock-unfontify-region-function
4911 'org-unfontify-region)
4912 ;; Activate before-change-function
4913 (org-set-local 'org-table-may-need-update t)
4914 (org-add-hook 'before-change-functions 'org-before-change-function nil
4915 'local)
4916 ;; Check for running clock before killing a buffer
4917 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4918 ;; Indentation.
4919 (org-set-local 'indent-line-function 'org-indent-line)
4920 (org-set-local 'indent-region-function 'org-indent-region)
4921 ;; Initialize radio targets.
4922 (org-update-radio-target-regexp)
4923 ;; Filling and auto-filling.
4924 (org-setup-filling)
4925 ;; Comments.
4926 (org-setup-comments-handling)
4927 ;; Beginning/end of defun
4928 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
4929 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
4930 ;; Next error for sparse trees
4931 (org-set-local 'next-error-function 'org-occur-next-match)
4932 ;; Make sure dependence stuff works reliably, even for users who set it
4933 ;; too late :-(
4934 (if org-enforce-todo-dependencies
4935 (add-hook 'org-blocker-hook
4936 'org-block-todo-from-children-or-siblings-or-parent)
4937 (remove-hook 'org-blocker-hook
4938 'org-block-todo-from-children-or-siblings-or-parent))
4939 (if org-enforce-todo-checkbox-dependencies
4940 (add-hook 'org-blocker-hook
4941 'org-block-todo-from-checkboxes)
4942 (remove-hook 'org-blocker-hook
4943 'org-block-todo-from-checkboxes))
4945 ;; Align options lines
4946 (org-set-local
4947 'align-mode-rules-list
4948 '((org-in-buffer-settings
4949 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4950 (modes . '(org-mode)))))
4952 ;; Imenu
4953 (org-set-local 'imenu-create-index-function
4954 'org-imenu-get-tree)
4956 ;; Make isearch reveal context
4957 (if (or (featurep 'xemacs)
4958 (not (boundp 'outline-isearch-open-invisible-function)))
4959 ;; Emacs 21 and XEmacs make use of the hook
4960 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4961 ;; Emacs 22 deals with this through a special variable
4962 (org-set-local 'outline-isearch-open-invisible-function
4963 (lambda (&rest ignore) (org-show-context 'isearch))))
4965 ;; Turn on org-beamer-mode?
4966 (and org-startup-with-beamer-mode (org-beamer-mode))
4968 ;; Setup the pcomplete hooks
4969 (set (make-local-variable 'pcomplete-command-completion-function)
4970 'org-pcomplete-initial)
4971 (set (make-local-variable 'pcomplete-command-name-function)
4972 'org-command-at-point)
4973 (set (make-local-variable 'pcomplete-default-completion-function)
4974 'ignore)
4975 (set (make-local-variable 'pcomplete-parse-arguments-function)
4976 'org-parse-arguments)
4977 (set (make-local-variable 'pcomplete-termination-string) "")
4978 (when (>= emacs-major-version 23)
4979 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
4981 ;; If empty file that did not turn on org-mode automatically, make it to.
4982 (if (and org-insert-mode-line-in-empty-file
4983 (org-called-interactively-p 'any)
4984 (= (point-min) (point-max)))
4985 (insert "# -*- mode: org -*-\n\n"))
4986 (unless org-inhibit-startup
4987 (when org-startup-align-all-tables
4988 (let ((bmp (buffer-modified-p)))
4989 (org-table-map-tables 'org-table-align 'quietly)
4990 (set-buffer-modified-p bmp)))
4991 (when org-startup-with-inline-images
4992 (org-display-inline-images))
4993 (when org-startup-indented
4994 (require 'org-indent)
4995 (org-indent-mode 1))
4996 (unless org-inhibit-startup-visibility-stuff
4997 (org-set-startup-visibility)))
4998 ;; Try to set org-hide correctly
4999 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5001 (when (fboundp 'abbrev-table-put)
5002 (abbrev-table-put org-mode-abbrev-table
5003 :parents (list text-mode-abbrev-table)))
5005 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5008 (defun org-find-invisible-foreground ()
5009 (let ((candidates (remove
5010 "unspecified-bg"
5011 (nconc
5012 (list (face-background 'default)
5013 (face-background 'org-default))
5014 (mapcar
5015 (lambda (alist)
5016 (when (boundp alist)
5017 (cdr (assoc 'background-color (symbol-value alist)))))
5018 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5019 (list (face-foreground 'org-hide))))))
5020 (car (remove nil candidates))))
5022 (defun org-current-time ()
5023 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5024 (if (> (car org-time-stamp-rounding-minutes) 1)
5025 (let ((r (car org-time-stamp-rounding-minutes))
5026 (time (decode-time)))
5027 (apply 'encode-time
5028 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5029 (nthcdr 2 time))))
5030 (current-time)))
5032 (defun org-today ()
5033 "Return today date, considering `org-extend-today-until'."
5034 (time-to-days
5035 (time-subtract (current-time)
5036 (list 0 (* 3600 org-extend-today-until) 0))))
5038 ;;;; Font-Lock stuff, including the activators
5040 (defvar org-mouse-map (make-sparse-keymap))
5041 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5042 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5043 (when org-mouse-1-follows-link
5044 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5045 (when org-tab-follows-link
5046 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5047 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5049 (require 'font-lock)
5051 (defconst org-non-link-chars "]\t\n\r<>")
5052 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5053 "shell" "elisp" "doi" "message"))
5054 (defvar org-link-types-re nil
5055 "Matches a link that has a url-like prefix like \"http:\"")
5056 (defvar org-link-re-with-space nil
5057 "Matches a link with spaces, optional angular brackets around it.")
5058 (defvar org-link-re-with-space2 nil
5059 "Matches a link with spaces, optional angular brackets around it.")
5060 (defvar org-link-re-with-space3 nil
5061 "Matches a link with spaces, only for internal part in bracket links.")
5062 (defvar org-angle-link-re nil
5063 "Matches link with angular brackets, spaces are allowed.")
5064 (defvar org-plain-link-re nil
5065 "Matches plain link, without spaces.")
5066 (defvar org-bracket-link-regexp nil
5067 "Matches a link in double brackets.")
5068 (defvar org-bracket-link-analytic-regexp nil
5069 "Regular expression used to analyze links.
5070 Here is what the match groups contain after a match:
5071 1: http:
5072 2: http
5073 3: path
5074 4: [desc]
5075 5: desc")
5076 (defvar org-bracket-link-analytic-regexp++ nil
5077 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5078 (defvar org-any-link-re nil
5079 "Regular expression matching any link.")
5081 (defcustom org-match-sexp-depth 3
5082 "Number of stacked braces for sub/superscript matching.
5083 This has to be set before loading org.el to be effective."
5084 :group 'org-export-translation ; ??????????????????????????/
5085 :type 'integer)
5087 (defun org-create-multibrace-regexp (left right n)
5088 "Create a regular expression which will match a balanced sexp.
5089 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5090 as single character strings.
5091 The regexp returned will match the entire expression including the
5092 delimiters. It will also define a single group which contains the
5093 match except for the outermost delimiters. The maximum depth of
5094 stacked delimiters is N. Escaping delimiters is not possible."
5095 (let* ((nothing (concat "[^" left right "]*?"))
5096 (or "\\|")
5097 (re nothing)
5098 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5099 (while (> n 1)
5100 (setq n (1- n)
5101 re (concat re or next)
5102 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5103 (concat left "\\(" re "\\)" right)))
5105 (defvar org-match-substring-regexp
5106 (concat
5107 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5108 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5109 "\\|"
5110 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5111 "\\|"
5112 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5113 "The regular expression matching a sub- or superscript.")
5115 (defvar org-match-substring-with-braces-regexp
5116 (concat
5117 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5118 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5119 "\\)")
5120 "The regular expression matching a sub- or superscript, forcing braces.")
5122 (defun org-make-link-regexps ()
5123 "Update the link regular expressions.
5124 This should be called after the variable `org-link-types' has changed."
5125 (setq org-link-types-re
5126 (concat
5127 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5128 org-link-re-with-space
5129 (concat
5130 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5131 "\\([^" org-non-link-chars " ]"
5132 "[^" org-non-link-chars "]*"
5133 "[^" org-non-link-chars " ]\\)>?")
5134 org-link-re-with-space2
5135 (concat
5136 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5137 "\\([^" org-non-link-chars " ]"
5138 "[^\t\n\r]*"
5139 "[^" org-non-link-chars " ]\\)>?")
5140 org-link-re-with-space3
5141 (concat
5142 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5143 "\\([^" org-non-link-chars " ]"
5144 "[^\t\n\r]*\\)")
5145 org-angle-link-re
5146 (concat
5147 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5148 "\\([^" org-non-link-chars " ]"
5149 "[^" org-non-link-chars "]*"
5150 "\\)>")
5151 org-plain-link-re
5152 (concat
5153 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5154 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5155 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5156 org-bracket-link-regexp
5157 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5158 org-bracket-link-analytic-regexp
5159 (concat
5160 "\\[\\["
5161 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5162 "\\([^]]+\\)"
5163 "\\]"
5164 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5165 "\\]")
5166 org-bracket-link-analytic-regexp++
5167 (concat
5168 "\\[\\["
5169 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5170 "\\([^]]+\\)"
5171 "\\]"
5172 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5173 "\\]")
5174 org-any-link-re
5175 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5176 org-angle-link-re "\\)\\|\\("
5177 org-plain-link-re "\\)")))
5179 (org-make-link-regexps)
5181 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5182 "Regular expression for fast time stamp matching.")
5183 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5184 "Regular expression for fast time stamp matching.")
5185 (defconst org-ts-regexp0
5186 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5187 "Regular expression matching time strings for analysis.
5188 This one does not require the space after the date, so it can be used
5189 on a string that terminates immediately after the date.")
5190 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5191 "Regular expression matching time strings for analysis.")
5192 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5193 "Regular expression matching time stamps, with groups.")
5194 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5195 "Regular expression matching time stamps (also [..]), with groups.")
5196 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5197 "Regular expression matching a time stamp range.")
5198 (defconst org-tr-regexp-both
5199 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5200 "Regular expression matching a time stamp range.")
5201 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5202 org-ts-regexp "\\)?")
5203 "Regular expression matching a time stamp or time stamp range.")
5204 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5205 org-ts-regexp-both "\\)?")
5206 "Regular expression matching a time stamp or time stamp range.
5207 The time stamps may be either active or inactive.")
5209 (defvar org-emph-face nil)
5211 (defun org-do-emphasis-faces (limit)
5212 "Run through the buffer and add overlays to emphasized strings."
5213 (let (rtn a)
5214 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5215 (if (not (= (char-after (match-beginning 3))
5216 (char-after (match-beginning 4))))
5217 (progn
5218 (setq rtn t)
5219 (setq a (assoc (match-string 3) org-emphasis-alist))
5220 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5221 'face
5222 (nth 1 a))
5223 (and (nth 4 a)
5224 (org-remove-flyspell-overlays-in
5225 (match-beginning 0) (match-end 0)))
5226 (add-text-properties (match-beginning 2) (match-end 2)
5227 '(font-lock-multiline t org-emphasis t))
5228 (when org-hide-emphasis-markers
5229 (add-text-properties (match-end 4) (match-beginning 5)
5230 '(invisible org-link))
5231 (add-text-properties (match-beginning 3) (match-end 3)
5232 '(invisible org-link)))))
5233 (backward-char 1))
5234 rtn))
5236 (defun org-emphasize (&optional char)
5237 "Insert or change an emphasis, i.e. a font like bold or italic.
5238 If there is an active region, change that region to a new emphasis.
5239 If there is no region, just insert the marker characters and position
5240 the cursor between them.
5241 CHAR should be either the marker character, or the first character of the
5242 HTML tag associated with that emphasis. If CHAR is a space, the means
5243 to remove the emphasis of the selected region.
5244 If char is not given (for example in an interactive call) it
5245 will be prompted for."
5246 (interactive)
5247 (let ((eal org-emphasis-alist) e det
5248 (erc org-emphasis-regexp-components)
5249 (prompt "")
5250 (string "") beg end move tag c s)
5251 (if (org-region-active-p)
5252 (setq beg (region-beginning) end (region-end)
5253 string (buffer-substring beg end))
5254 (setq move t))
5256 (while (setq e (pop eal))
5257 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5258 c (aref tag 0))
5259 (push (cons c (string-to-char (car e))) det)
5260 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5261 (substring tag 1)))))
5262 (setq det (nreverse det))
5263 (unless char
5264 (message "%s" (concat "Emphasis marker or tag:" prompt))
5265 (setq char (read-char-exclusive)))
5266 (setq char (or (cdr (assoc char det)) char))
5267 (if (equal char ?\ )
5268 (setq s "" move nil)
5269 (unless (assoc (char-to-string char) org-emphasis-alist)
5270 (error "No such emphasis marker: \"%c\"" char))
5271 (setq s (char-to-string char)))
5272 (while (and (> (length string) 1)
5273 (equal (substring string 0 1) (substring string -1))
5274 (assoc (substring string 0 1) org-emphasis-alist))
5275 (setq string (substring string 1 -1)))
5276 (setq string (concat s string s))
5277 (if beg (delete-region beg end))
5278 (unless (or (bolp)
5279 (string-match (concat "[" (nth 0 erc) "\n]")
5280 (char-to-string (char-before (point)))))
5281 (insert " "))
5282 (unless (or (eobp)
5283 (string-match (concat "[" (nth 1 erc) "\n]")
5284 (char-to-string (char-after (point)))))
5285 (insert " ") (backward-char 1))
5286 (insert string)
5287 (and move (backward-char 1))))
5289 (defconst org-nonsticky-props
5290 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5292 (defsubst org-rear-nonsticky-at (pos)
5293 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5295 (defun org-activate-plain-links (limit)
5296 "Run through the buffer and add overlays to links."
5297 (catch 'exit
5298 (let (f)
5299 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5300 (not (org-in-src-block-p)))
5301 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5302 (setq f (get-text-property (match-beginning 0) 'face))
5303 (unless (or (org-in-src-block-p)
5304 (eq f 'org-tag)
5305 (and (listp f) (memq 'org-tag f)))
5306 (add-text-properties (match-beginning 0) (match-end 0)
5307 (list 'mouse-face 'highlight
5308 'face 'org-link
5309 'keymap org-mouse-map))
5310 (org-rear-nonsticky-at (match-end 0)))
5311 t))))
5313 (defun org-activate-code (limit)
5314 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5315 (progn
5316 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5317 (remove-text-properties (match-beginning 0) (match-end 0)
5318 '(display t invisible t intangible t))
5319 t)))
5321 (defcustom org-src-fontify-natively nil
5322 "When non-nil, fontify code in code blocks."
5323 :type 'boolean
5324 :version "24.1"
5325 :group 'org-appearance
5326 :group 'org-babel)
5328 (defcustom org-allow-promoting-top-level-subtree nil
5329 "When non-nil, allow promoting a top level subtree.
5330 The leading star of the top level headline will be replaced
5331 by a #."
5332 :type 'boolean
5333 :version "24.1"
5334 :group 'org-appearance)
5336 (defun org-fontify-meta-lines-and-blocks (limit)
5337 (condition-case nil
5338 (org-fontify-meta-lines-and-blocks-1 limit)
5339 (error (message "org-mode fontification error"))))
5341 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5342 "Fontify #+ lines and blocks, in the correct ways."
5343 (let ((case-fold-search t))
5344 (if (re-search-forward
5345 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5346 limit t)
5347 (let ((beg (match-beginning 0))
5348 (block-start (match-end 0))
5349 (block-end nil)
5350 (lang (match-string 7))
5351 (beg1 (line-beginning-position 2))
5352 (dc1 (downcase (match-string 2)))
5353 (dc3 (downcase (match-string 3)))
5354 end end1 quoting block-type ovl)
5355 (cond
5356 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5357 ;; a single line of backend-specific content
5358 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5359 (remove-text-properties (match-beginning 0) (match-end 0)
5360 '(display t invisible t intangible t))
5361 (add-text-properties (match-beginning 1) (match-end 3)
5362 '(font-lock-fontified t face org-meta-line))
5363 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5364 '(font-lock-fontified t face org-block))
5365 ; for backend-specific code
5367 ((and (match-end 4) (equal dc3 "+begin"))
5368 ;; Truly a block
5369 (setq block-type (downcase (match-string 5))
5370 quoting (member block-type org-protecting-blocks))
5371 (when (re-search-forward
5372 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5373 nil t) ;; on purpose, we look further than LIMIT
5374 (setq end (min (point-max) (match-end 0))
5375 end1 (min (point-max) (1- (match-beginning 0))))
5376 (setq block-end (match-beginning 0))
5377 (when quoting
5378 (remove-text-properties beg end
5379 '(display t invisible t intangible t)))
5380 (add-text-properties
5381 beg end
5382 '(font-lock-fontified t font-lock-multiline t))
5383 (add-text-properties beg beg1 '(face org-meta-line))
5384 (add-text-properties end1 (min (point-max) (1+ end))
5385 '(face org-meta-line)) ; for end_src
5386 (cond
5387 ((and lang (not (string= lang "")) org-src-fontify-natively)
5388 (org-src-font-lock-fontify-block lang block-start block-end)
5389 ;; remove old background overlays
5390 (mapc (lambda (ov)
5391 (if (eq (overlay-get ov 'face) 'org-block-background)
5392 (delete-overlay ov)))
5393 (overlays-at (/ (+ beg1 block-end) 2)))
5394 ;; add a background overlay
5395 (setq ovl (make-overlay beg1 block-end))
5396 (overlay-put ovl 'face 'org-block-background)
5397 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5398 (quoting
5399 (add-text-properties beg1 (min (point-max) (1+ end1))
5400 '(face org-block))) ; end of source block
5401 ((not org-fontify-quote-and-verse-blocks))
5402 ((string= block-type "quote")
5403 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5404 ((string= block-type "verse")
5405 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5406 (add-text-properties beg beg1 '(face org-block-begin-line))
5407 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5408 '(face org-block-end-line))
5410 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5411 (add-text-properties
5412 beg (match-end 3)
5413 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5414 '(font-lock-fontified t invisible t)
5415 '(font-lock-fontified t face org-document-info-keyword)))
5416 (add-text-properties
5417 (match-beginning 6) (match-end 6)
5418 (if (string-equal dc1 "+title:")
5419 '(font-lock-fontified t face org-document-title)
5420 '(font-lock-fontified t face org-document-info))))
5421 ((or (equal dc1 "+results")
5422 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5423 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5424 "+call:" "+header:" "+headers:" "+name:"))
5425 (and (match-end 4) (equal dc3 "+attr")))
5426 (add-text-properties
5427 beg (match-end 0)
5428 '(font-lock-fontified t face org-meta-line))
5430 ((member dc3 '(" " ""))
5431 (add-text-properties
5432 beg (match-end 0)
5433 '(font-lock-fontified t face font-lock-comment-face)))
5434 ((not (member (char-after beg) '(?\ ?\t)))
5435 ;; just any other in-buffer setting, but not indented
5436 (add-text-properties
5437 beg (match-end 0)
5438 '(font-lock-fontified t face org-meta-line))
5440 (t nil))))))
5442 (defun org-activate-angle-links (limit)
5443 "Run through the buffer and add overlays to links."
5444 (if (and (re-search-forward org-angle-link-re limit t)
5445 (not (org-in-src-block-p)))
5446 (progn
5447 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5448 (add-text-properties (match-beginning 0) (match-end 0)
5449 (list 'mouse-face 'highlight
5450 'keymap org-mouse-map))
5451 (org-rear-nonsticky-at (match-end 0))
5452 t)))
5454 (defun org-activate-footnote-links (limit)
5455 "Run through the buffer and add overlays to footnotes."
5456 (let ((fn (org-footnote-next-reference-or-definition limit)))
5457 (when fn
5458 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5459 (org-remove-flyspell-overlays-in beg end)
5460 (add-text-properties beg end
5461 (list 'mouse-face 'highlight
5462 'keymap org-mouse-map
5463 'help-echo
5464 (if (= (point-at-bol) beg)
5465 "Footnote definition"
5466 "Footnote reference")
5467 'font-lock-fontified t
5468 'font-lock-multiline t
5469 'face 'org-footnote))))))
5471 (defun org-activate-bracket-links (limit)
5472 "Run through the buffer and add overlays to bracketed links."
5473 (if (and (re-search-forward org-bracket-link-regexp limit t)
5474 (not (org-in-src-block-p)))
5475 (let* ((help (concat "LINK: "
5476 (org-match-string-no-properties 1)))
5477 ;; FIXME: above we should remove the escapes.
5478 ;; but that requires another match, protecting match data,
5479 ;; a lot of overhead for font-lock.
5480 (ip (org-maybe-intangible
5481 (list 'invisible 'org-link
5482 'keymap org-mouse-map 'mouse-face 'highlight
5483 'font-lock-multiline t 'help-echo help)))
5484 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5485 'font-lock-multiline t 'help-echo help)))
5486 ;; We need to remove the invisible property here. Table narrowing
5487 ;; may have made some of this invisible.
5488 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5489 (remove-text-properties (match-beginning 0) (match-end 0)
5490 '(invisible nil))
5491 (if (match-end 3)
5492 (progn
5493 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5494 (org-rear-nonsticky-at (match-beginning 3))
5495 (add-text-properties (match-beginning 3) (match-end 3) vp)
5496 (org-rear-nonsticky-at (match-end 3))
5497 (add-text-properties (match-end 3) (match-end 0) ip)
5498 (org-rear-nonsticky-at (match-end 0)))
5499 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5500 (org-rear-nonsticky-at (match-beginning 1))
5501 (add-text-properties (match-beginning 1) (match-end 1) vp)
5502 (org-rear-nonsticky-at (match-end 1))
5503 (add-text-properties (match-end 1) (match-end 0) ip)
5504 (org-rear-nonsticky-at (match-end 0)))
5505 t)))
5507 (defun org-activate-dates (limit)
5508 "Run through the buffer and add overlays to dates."
5509 (if (re-search-forward org-tsr-regexp-both limit t)
5510 (progn
5511 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5512 (add-text-properties (match-beginning 0) (match-end 0)
5513 (list 'mouse-face 'highlight
5514 'keymap org-mouse-map))
5515 (org-rear-nonsticky-at (match-end 0))
5516 (when org-display-custom-times
5517 (if (match-end 3)
5518 (org-display-custom-time (match-beginning 3) (match-end 3)))
5519 (org-display-custom-time (match-beginning 1) (match-end 1)))
5520 t)))
5522 (defvar org-target-link-regexp nil
5523 "Regular expression matching radio targets in plain text.")
5524 (make-variable-buffer-local 'org-target-link-regexp)
5525 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5526 "Regular expression matching a link target.")
5527 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5528 "Regular expression matching a radio target.")
5529 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5530 "Regular expression matching any target.")
5532 (defun org-activate-target-links (limit)
5533 "Run through the buffer and add overlays to target matches."
5534 (when org-target-link-regexp
5535 (let ((case-fold-search t))
5536 (if (re-search-forward org-target-link-regexp limit t)
5537 (progn
5538 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5539 (add-text-properties (match-beginning 0) (match-end 0)
5540 (list 'mouse-face 'highlight
5541 'keymap org-mouse-map
5542 'help-echo "Radio target link"
5543 'org-linked-text t))
5544 (org-rear-nonsticky-at (match-end 0))
5545 t)))))
5547 (defun org-update-radio-target-regexp ()
5548 "Find all radio targets in this file and update the regular expression."
5549 (interactive)
5550 (when (memq 'radio org-activate-links)
5551 (setq org-target-link-regexp
5552 (org-make-target-link-regexp (org-all-targets 'radio)))
5553 (org-restart-font-lock)))
5555 (defun org-hide-wide-columns (limit)
5556 (let (s e)
5557 (setq s (text-property-any (point) (or limit (point-max))
5558 'org-cwidth t))
5559 (when s
5560 (setq e (next-single-property-change s 'org-cwidth))
5561 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5562 (goto-char e)
5563 t)))
5565 (defvar org-latex-and-specials-regexp nil
5566 "Regular expression for highlighting export special stuff.")
5567 (defvar org-match-substring-regexp)
5568 (defvar org-match-substring-with-braces-regexp)
5570 ;; This should be with the exporter code, but we also use if for font-locking
5571 (defconst org-export-html-special-string-regexps
5572 '(("\\\\-" . "&shy;")
5573 ("---\\([^-]\\)" . "&mdash;\\1")
5574 ("--\\([^-]\\)" . "&ndash;\\1")
5575 ("\\.\\.\\." . "&hellip;"))
5576 "Regular expressions for special string conversion.")
5579 (defun org-compute-latex-and-specials-regexp ()
5580 "Compute regular expression for stuff treated specially by exporters."
5581 (if (not org-highlight-latex-fragments-and-specials)
5582 (org-set-local 'org-latex-and-specials-regexp nil)
5583 (require 'org-exp)
5584 (let*
5585 ((matchers (plist-get org-format-latex-options :matchers))
5586 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5587 org-latex-regexps)))
5588 (org-export-allow-BIND nil)
5589 (options (org-combine-plists (org-default-export-plist)
5590 (org-infile-export-plist)))
5591 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5592 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5593 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5594 (org-export-html-expand (plist-get options :expand-quoted-html))
5595 (org-export-with-special-strings (plist-get options :special-strings))
5596 (re-sub
5597 (cond
5598 ((equal org-export-with-sub-superscripts '{})
5599 (list org-match-substring-with-braces-regexp))
5600 (org-export-with-sub-superscripts
5601 (list org-match-substring-regexp))))
5602 (re-latex
5603 (if org-export-with-LaTeX-fragments
5604 (mapcar (lambda (x) (nth 1 x)) latexs)))
5605 (re-macros
5606 (if org-export-with-TeX-macros
5607 (list (concat "\\\\"
5608 (regexp-opt
5609 (append
5611 (delq nil
5612 (mapcar 'car-safe
5613 (append org-entities-user
5614 org-entities)))
5615 (if (boundp 'org-latex-entities)
5616 (mapcar (lambda (x)
5617 (or (car-safe x) x))
5618 org-latex-entities)
5619 nil))
5620 'words))) ; FIXME
5622 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5623 (re-special (if org-export-with-special-strings
5624 (mapcar (lambda (x) (car x))
5625 org-export-html-special-string-regexps)))
5626 (re-rest
5627 (delq nil
5628 (list
5629 (if org-export-html-expand "@<[^>\n]+>")
5630 ))))
5631 (org-set-local
5632 'org-latex-and-specials-regexp
5633 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5634 re-rest) "\\|")))))
5636 (defun org-do-latex-and-special-faces (limit)
5637 "Run through the buffer and add overlays to links."
5638 (when org-latex-and-specials-regexp
5639 (let (rtn d)
5640 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5641 limit t))
5642 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5643 'face))
5644 '(org-code org-verbatim underline)))
5645 (progn
5646 (setq rtn t
5647 d (cond ((member (char-after (1+ (match-beginning 0)))
5648 '(?_ ?^)) 1)
5649 (t 0)))
5650 (font-lock-prepend-text-property
5651 (+ d (match-beginning 0)) (match-end 0)
5652 'face 'org-latex-and-export-specials)
5653 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5654 '(font-lock-multiline t)))))
5655 rtn)))
5657 (defun org-restart-font-lock ()
5658 "Restart `font-lock-mode', to force refontification."
5659 (when (and (boundp 'font-lock-mode) font-lock-mode)
5660 (font-lock-mode -1)
5661 (font-lock-mode 1)))
5663 (defun org-all-targets (&optional radio)
5664 "Return a list of all targets in this file.
5665 With optional argument RADIO, only find radio targets."
5666 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5667 rtn)
5668 (save-excursion
5669 (goto-char (point-min))
5670 (while (re-search-forward re nil t)
5671 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5672 rtn)))
5674 (defun org-make-target-link-regexp (targets)
5675 "Make regular expression matching all strings in TARGETS.
5676 The regular expression finds the targets also if there is a line break
5677 between words."
5678 (and targets
5679 (concat
5680 "\\<\\("
5681 (mapconcat
5682 (lambda (x)
5683 (setq x (regexp-quote x))
5684 (while (string-match " +" x)
5685 (setq x (replace-match "\\s-+" t t x)))
5687 targets
5688 "\\|")
5689 "\\)\\>")))
5691 (defun org-activate-tags (limit)
5692 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5693 (progn
5694 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5695 (add-text-properties (match-beginning 1) (match-end 1)
5696 (list 'mouse-face 'highlight
5697 'keymap org-mouse-map))
5698 (org-rear-nonsticky-at (match-end 1))
5699 t)))
5701 (defun org-outline-level ()
5702 "Compute the outline level of the heading at point.
5703 This function assumes that the cursor is at the beginning of a line matched
5704 by `outline-regexp'. Otherwise it returns garbage.
5705 If this is called at a normal headline, the level is the number of stars.
5706 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5707 (save-excursion
5708 (looking-at org-outline-regexp)
5709 (1- (- (match-end 0) (match-beginning 0)))))
5711 (defvar org-font-lock-keywords nil)
5713 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5714 "Regular expression matching a property line.")
5716 (defvar org-font-lock-hook nil
5717 "Functions to be called for special font lock stuff.")
5719 (defvar org-font-lock-set-keywords-hook nil
5720 "Functions that can manipulate `org-font-lock-extra-keywords'.
5721 This is called after `org-font-lock-extra-keywords' is defined, but before
5722 it is installed to be used by font lock. This can be useful if something
5723 needs to be inserted at a specific position in the font-lock sequence.")
5725 (defun org-font-lock-hook (limit)
5726 "Run `org-font-lock-hook' within LIMIT."
5727 (run-hook-with-args 'org-font-lock-hook limit))
5729 (defun org-set-font-lock-defaults ()
5730 "Set font lock defaults for the current buffer."
5731 (let* ((em org-fontify-emphasized-text)
5732 (lk org-activate-links)
5733 (org-font-lock-extra-keywords
5734 (list
5735 ;; Call the hook
5736 '(org-font-lock-hook)
5737 ;; Headlines
5738 `(,(if org-fontify-whole-heading-line
5739 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5740 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5741 (1 (org-get-level-face 1))
5742 (2 (org-get-level-face 2))
5743 (3 (org-get-level-face 3)))
5744 ;; Table lines
5745 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5746 (1 'org-table t))
5747 ;; Table internals
5748 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5749 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5750 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5751 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5752 ;; Drawers
5753 (list org-drawer-regexp '(0 'org-special-keyword t))
5754 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5755 ;; Properties
5756 (list org-property-re
5757 '(1 'org-special-keyword t)
5758 '(3 'org-property-value t))
5759 ;; Links
5760 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5761 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5762 (if (memq 'plain lk) '(org-activate-plain-links))
5763 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5764 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5765 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5766 (if (memq 'footnote lk) '(org-activate-footnote-links))
5767 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5768 '(org-hide-wide-columns (0 nil append))
5769 ;; TODO keyword
5770 (list (format org-heading-keyword-regexp-format
5771 org-todo-regexp)
5772 '(2 (org-get-todo-face 2) t))
5773 ;; DONE
5774 (if org-fontify-done-headline
5775 (list (format org-heading-keyword-regexp-format
5776 (concat
5777 "\\(?:"
5778 (mapconcat 'regexp-quote org-done-keywords "\\|")
5779 "\\)"))
5780 '(2 'org-headline-done t))
5781 nil)
5782 ;; Priorities
5783 '(org-font-lock-add-priority-faces)
5784 ;; Tags
5785 '(org-font-lock-add-tag-faces)
5786 ;; Special keywords
5787 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5788 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5789 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5790 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5791 ;; Emphasis
5792 (if em
5793 (if (featurep 'xemacs)
5794 '(org-do-emphasis-faces (0 nil append))
5795 '(org-do-emphasis-faces)))
5796 ;; Checkboxes
5797 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5798 1 'org-checkbox prepend)
5799 (if (cdr (assq 'checkbox org-list-automatic-rules))
5800 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5801 (0 (org-get-checkbox-statistics-face) t)))
5802 ;; Description list items
5803 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5804 1 'org-list-dt prepend)
5805 ;; ARCHIVEd headings
5806 (list (concat
5807 org-outline-regexp-bol
5808 "\\(.*:" org-archive-tag ":.*\\)")
5809 '(1 'org-archived prepend))
5810 ;; Specials
5811 '(org-do-latex-and-special-faces)
5812 '(org-fontify-entities)
5813 '(org-raise-scripts)
5814 ;; Code
5815 '(org-activate-code (1 'org-code t))
5816 ;; COMMENT
5817 (list (format org-heading-keyword-regexp-format
5818 (concat "\\("
5819 org-comment-string "\\|" org-quote-string
5820 "\\)"))
5821 '(2 'org-special-keyword t))
5822 ;; Blocks and meta lines
5823 '(org-fontify-meta-lines-and-blocks)
5825 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5826 (run-hooks 'org-font-lock-set-keywords-hook)
5827 ;; Now set the full font-lock-keywords
5828 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5829 (org-set-local 'font-lock-defaults
5830 '(org-font-lock-keywords t nil nil backward-paragraph))
5831 (kill-local-variable 'font-lock-keywords) nil))
5833 (defun org-toggle-pretty-entities ()
5834 "Toggle the composition display of entities as UTF8 characters."
5835 (interactive)
5836 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5837 (org-restart-font-lock)
5838 (if org-pretty-entities
5839 (message "Entities are displayed as UTF8 characters")
5840 (save-restriction
5841 (widen)
5842 (org-decompose-region (point-min) (point-max))
5843 (message "Entities are displayed plain"))))
5845 (defvar org-custom-properties-overlays nil
5846 "List of overlays used for custom properties.")
5847 (make-variable-buffer-local 'org-custom-properties-overlays)
5849 (defun org-toggle-custom-properties-visibility ()
5850 "Display or hide properties in `org-custom-properties'."
5851 (interactive)
5852 (if org-custom-properties-overlays
5853 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5854 (setq org-custom-properties-overlays nil))
5855 (unless (not org-custom-properties)
5856 (save-excursion
5857 (save-restriction
5858 (widen)
5859 (goto-char (point-min))
5860 (while (re-search-forward org-property-re nil t)
5861 (mapc (lambda(p)
5862 (when (equal p (substring (match-string 1) 1 -1))
5863 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5864 (overlay-put o 'invisible t)
5865 (overlay-put o 'org-custom-property t)
5866 (push o org-custom-properties-overlays))))
5867 org-custom-properties)))))))
5869 (defun org-fontify-entities (limit)
5870 "Find an entity to fontify."
5871 (let (ee)
5872 (when org-pretty-entities
5873 (catch 'match
5874 (while (re-search-forward
5875 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5876 limit t)
5877 (if (and (not (org-in-indented-comment-line))
5878 (setq ee (org-entity-get (match-string 1)))
5879 (= (length (nth 6 ee)) 1))
5880 (let*
5881 ((end (if (equal (match-string 2) "{}")
5882 (match-end 2)
5883 (match-end 1))))
5884 (add-text-properties
5885 (match-beginning 0) end
5886 (list 'font-lock-fontified t))
5887 (compose-region (match-beginning 0) end
5888 (nth 6 ee) nil)
5889 (backward-char 1)
5890 (throw 'match t))))
5891 nil))))
5893 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5894 "Fontify string S like in Org-mode."
5895 (with-temp-buffer
5896 (insert s)
5897 (let ((org-odd-levels-only odd-levels))
5898 (org-mode)
5899 (font-lock-fontify-buffer)
5900 (buffer-string))))
5902 (defvar org-m nil)
5903 (defvar org-l nil)
5904 (defvar org-f nil)
5905 (defun org-get-level-face (n)
5906 "Get the right face for match N in font-lock matching of headlines."
5907 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5908 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5909 (if org-cycle-level-faces
5910 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5911 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5912 (cond
5913 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5914 ((eq n 2) org-f)
5915 (t (if org-level-color-stars-only nil org-f))))
5918 (defun org-get-todo-face (kwd)
5919 "Get the right face for a TODO keyword KWD.
5920 If KWD is a number, get the corresponding match group."
5921 (if (numberp kwd) (setq kwd (match-string kwd)))
5922 (or (org-face-from-face-or-color
5923 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5924 (and (member kwd org-done-keywords) 'org-done)
5925 'org-todo))
5927 (defun org-face-from-face-or-color (context inherit face-or-color)
5928 "Create a face list that inherits INHERIT, but sets the foreground color.
5929 When FACE-OR-COLOR is not a string, just return it."
5930 (if (stringp face-or-color)
5931 (list :inherit inherit
5932 (cdr (assoc context org-faces-easy-properties))
5933 face-or-color)
5934 face-or-color))
5936 (defun org-font-lock-add-tag-faces (limit)
5937 "Add the special tag faces."
5938 (when (and org-tag-faces org-tags-special-faces-re)
5939 (while (re-search-forward org-tags-special-faces-re limit t)
5940 (add-text-properties (match-beginning 1) (match-end 1)
5941 (list 'face (org-get-tag-face 1)
5942 'font-lock-fontified t))
5943 (backward-char 1))))
5945 (defun org-font-lock-add-priority-faces (limit)
5946 "Add the special priority faces."
5947 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5948 (when (save-match-data (org-at-heading-p))
5949 (add-text-properties
5950 (match-beginning 0) (match-end 0)
5951 (list 'face (or (org-face-from-face-or-color
5952 'priority 'org-special-keyword
5953 (cdr (assoc (char-after (match-beginning 1))
5954 org-priority-faces)))
5955 'org-special-keyword)
5956 'font-lock-fontified t)))))
5958 (defun org-get-tag-face (kwd)
5959 "Get the right face for a TODO keyword KWD.
5960 If KWD is a number, get the corresponding match group."
5961 (if (numberp kwd) (setq kwd (match-string kwd)))
5962 (or (org-face-from-face-or-color
5963 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5964 'org-tag))
5966 (defun org-unfontify-region (beg end &optional maybe_loudly)
5967 "Remove fontification and activation overlays from links."
5968 (font-lock-default-unfontify-region beg end)
5969 (let* ((buffer-undo-list t)
5970 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5971 (inhibit-modification-hooks t)
5972 deactivate-mark buffer-file-name buffer-file-truename)
5973 (org-decompose-region beg end)
5974 (remove-text-properties beg end
5975 '(mouse-face t keymap t org-linked-text t
5976 invisible t intangible t
5977 org-no-flyspell t org-emphasis t))
5978 (org-remove-font-lock-display-properties beg end)))
5980 (defconst org-script-display '(((raise -0.3) (height 0.7))
5981 ((raise 0.3) (height 0.7))
5982 ((raise -0.5))
5983 ((raise 0.5)))
5984 "Display properties for showing superscripts and subscripts.")
5986 (defun org-remove-font-lock-display-properties (beg end)
5987 "Remove specific display properties that have been added by font lock.
5988 The will remove the raise properties that are used to show superscripts
5989 and subscripts."
5990 (let (next prop)
5991 (while (< beg end)
5992 (setq next (next-single-property-change beg 'display nil end)
5993 prop (get-text-property beg 'display))
5994 (if (member prop org-script-display)
5995 (put-text-property beg next 'display nil))
5996 (setq beg next))))
5998 (defun org-raise-scripts (limit)
5999 "Add raise properties to sub/superscripts."
6000 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6001 (if (re-search-forward
6002 (if (eq org-use-sub-superscripts t)
6003 org-match-substring-regexp
6004 org-match-substring-with-braces-regexp)
6005 limit t)
6006 (let* ((pos (point)) table-p comment-p
6007 (mpos (match-beginning 3))
6008 (emph-p (get-text-property mpos 'org-emphasis))
6009 (link-p (get-text-property mpos 'mouse-face))
6010 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6011 (goto-char (point-at-bol))
6012 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6013 comment-p (org-looking-at-p "[ \t]*#"))
6014 (goto-char pos)
6015 ;; FIXME: Should we go back one character here, for a_b^c
6016 ;; (goto-char (1- pos)) ;????????????????????
6017 (if (or comment-p emph-p link-p keyw-p)
6019 (put-text-property (match-beginning 3) (match-end 0)
6020 'display
6021 (if (equal (char-after (match-beginning 2)) ?^)
6022 (nth (if table-p 3 1) org-script-display)
6023 (nth (if table-p 2 0) org-script-display)))
6024 (add-text-properties (match-beginning 2) (match-end 2)
6025 (list 'invisible t
6026 'org-dwidth t 'org-dwidth-n 1))
6027 (if (and (eq (char-after (match-beginning 3)) ?{)
6028 (eq (char-before (match-end 3)) ?}))
6029 (progn
6030 (add-text-properties
6031 (match-beginning 3) (1+ (match-beginning 3))
6032 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6033 (add-text-properties
6034 (1- (match-end 3)) (match-end 3)
6035 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6036 t)))))
6038 ;;;; Visibility cycling, including org-goto and indirect buffer
6040 ;;; Cycling
6042 (defvar org-cycle-global-status nil)
6043 (make-variable-buffer-local 'org-cycle-global-status)
6044 (defvar org-cycle-subtree-status nil)
6045 (make-variable-buffer-local 'org-cycle-subtree-status)
6047 (defvar org-inlinetask-min-level)
6049 ;;;###autoload
6050 (defun org-cycle (&optional arg)
6051 "TAB-action and visibility cycling for Org-mode.
6053 This is the command invoked in Org-mode by the TAB key. Its main purpose
6054 is outline visibility cycling, but it also invokes other actions
6055 in special contexts.
6057 - When this function is called with a prefix argument, rotate the entire
6058 buffer through 3 states (global cycling)
6059 1. OVERVIEW: Show only top-level headlines.
6060 2. CONTENTS: Show all headlines of all levels, but no body text.
6061 3. SHOW ALL: Show everything.
6062 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6063 determined by the variable `org-startup-folded', and by any VISIBILITY
6064 properties in the buffer.
6065 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6066 including any drawers.
6068 - When inside a table, re-align the table and move to the next field.
6070 - When point is at the beginning of a headline, rotate the subtree started
6071 by this line through 3 different states (local cycling)
6072 1. FOLDED: Only the main headline is shown.
6073 2. CHILDREN: The main headline and the direct children are shown.
6074 From this state, you can move to one of the children
6075 and zoom in further.
6076 3. SUBTREE: Show the entire subtree, including body text.
6077 If there is no subtree, switch directly from CHILDREN to FOLDED.
6079 - When point is at the beginning of an empty headline and the variable
6080 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6081 of the headline by demoting and promoting it to likely levels. This
6082 speeds up creation document structure by pressing TAB once or several
6083 times right after creating a new headline.
6085 - When there is a numeric prefix, go up to a heading with level ARG, do
6086 a `show-subtree' and return to the previous cursor position. If ARG
6087 is negative, go up that many levels.
6089 - When point is not at the beginning of a headline, execute the global
6090 binding for TAB, which is re-indenting the line. See the option
6091 `org-cycle-emulate-tab' for details.
6093 - Special case: if point is at the beginning of the buffer and there is
6094 no headline in line 1, this function will act as if called with prefix arg
6095 (C-u TAB, same as S-TAB) also when called without prefix arg.
6096 But only if also the variable `org-cycle-global-at-bob' is t."
6097 (interactive "P")
6098 (org-load-modules-maybe)
6099 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6100 (and org-cycle-level-after-item/entry-creation
6101 (or (org-cycle-level)
6102 (org-cycle-item-indentation))))
6103 (let* ((limit-level
6104 (or org-cycle-max-level
6105 (and (boundp 'org-inlinetask-min-level)
6106 org-inlinetask-min-level
6107 (1- org-inlinetask-min-level))))
6108 (nstars (and limit-level
6109 (if org-odd-levels-only
6110 (and limit-level (1- (* limit-level 2)))
6111 limit-level)))
6112 (org-outline-regexp
6113 (if (not (derived-mode-p 'org-mode))
6114 outline-regexp
6115 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6116 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6117 (not (looking-at org-outline-regexp))))
6118 (org-cycle-hook
6119 (if bob-special
6120 (delq 'org-optimize-window-after-visibility-change
6121 (copy-sequence org-cycle-hook))
6122 org-cycle-hook))
6123 (pos (point)))
6125 (if (or bob-special (equal arg '(4)))
6126 ;; special case: use global cycling
6127 (setq arg t))
6129 (cond
6131 ((equal arg '(16))
6132 (setq last-command 'dummy)
6133 (org-set-startup-visibility)
6134 (message "Startup visibility, plus VISIBILITY properties"))
6136 ((equal arg '(64))
6137 (show-all)
6138 (message "Entire buffer visible, including drawers"))
6140 ;; Table: enter it or move to the next field.
6141 ((org-at-table-p 'any)
6142 (if (org-at-table.el-p)
6143 (message "Use C-c ' to edit table.el tables")
6144 (if arg (org-table-edit-field t)
6145 (org-table-justify-field-maybe)
6146 (call-interactively 'org-table-next-field))))
6148 ((run-hook-with-args-until-success
6149 'org-tab-after-check-for-table-hook))
6151 ;; Global cycling: delegate to `org-cycle-internal-global'.
6152 ((eq arg t) (org-cycle-internal-global))
6154 ;; Drawers: delegate to `org-flag-drawer'.
6155 ((and org-drawers org-drawer-regexp
6156 (save-excursion
6157 (beginning-of-line 1)
6158 (looking-at org-drawer-regexp)))
6159 (org-flag-drawer ; toggle block visibility
6160 (not (get-char-property (match-end 0) 'invisible))))
6162 ;; Show-subtree, ARG levels up from here.
6163 ((integerp arg)
6164 (save-excursion
6165 (org-back-to-heading)
6166 (outline-up-heading (if (< arg 0) (- arg)
6167 (- (funcall outline-level) arg)))
6168 (org-show-subtree)))
6170 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6171 ((and (featurep 'org-inlinetask)
6172 (org-inlinetask-at-task-p)
6173 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6174 (org-inlinetask-toggle-visibility))
6176 ((org-try-cdlatex-tab))
6178 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6179 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6180 (save-excursion (beginning-of-line 1)
6181 (looking-at org-outline-regexp)))
6182 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6183 (org-cycle-internal-local))
6185 ;; From there: TAB emulation and template completion.
6186 (buffer-read-only (org-back-to-heading))
6188 ((run-hook-with-args-until-success
6189 'org-tab-after-check-for-cycling-hook))
6191 ((org-try-structure-completion))
6193 ((run-hook-with-args-until-success
6194 'org-tab-before-tab-emulation-hook))
6196 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6197 (or (not (bolp))
6198 (not (looking-at org-outline-regexp))))
6199 (call-interactively (global-key-binding "\t")))
6201 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6202 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6203 (or (and (eq org-cycle-emulate-tab 'white)
6204 (= (match-end 0) (point-at-eol)))
6205 (and (eq org-cycle-emulate-tab 'whitestart)
6206 (>= (match-end 0) pos))))
6208 (eq org-cycle-emulate-tab t))
6209 (call-interactively (global-key-binding "\t")))
6211 (t (save-excursion
6212 (org-back-to-heading)
6213 (org-cycle)))))))
6215 (defun org-cycle-internal-global ()
6216 "Do the global cycling action."
6217 ;; Hack to avoid display of messages for .org attachments in Gnus
6218 (let ((ga (string-match "\\*fontification" (buffer-name))))
6219 (cond
6220 ((and (eq last-command this-command)
6221 (eq org-cycle-global-status 'overview))
6222 ;; We just created the overview - now do table of contents
6223 ;; This can be slow in very large buffers, so indicate action
6224 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6225 (unless ga (message "CONTENTS..."))
6226 (org-content)
6227 (unless ga (message "CONTENTS...done"))
6228 (setq org-cycle-global-status 'contents)
6229 (run-hook-with-args 'org-cycle-hook 'contents))
6231 ((and (eq last-command this-command)
6232 (eq org-cycle-global-status 'contents))
6233 ;; We just showed the table of contents - now show everything
6234 (run-hook-with-args 'org-pre-cycle-hook 'all)
6235 (show-all)
6236 (unless ga (message "SHOW ALL"))
6237 (setq org-cycle-global-status 'all)
6238 (run-hook-with-args 'org-cycle-hook 'all))
6241 ;; Default action: go to overview
6242 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6243 (org-overview)
6244 (unless ga (message "OVERVIEW"))
6245 (setq org-cycle-global-status 'overview)
6246 (run-hook-with-args 'org-cycle-hook 'overview)))))
6248 (defun org-cycle-internal-local ()
6249 "Do the local cycling action."
6250 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6251 ;; First, determine end of headline (EOH), end of subtree or item
6252 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6253 (save-excursion
6254 (if (org-at-item-p)
6255 (progn
6256 (beginning-of-line)
6257 (setq struct (org-list-struct))
6258 (setq eoh (point-at-eol))
6259 (setq eos (org-list-get-item-end-before-blank (point) struct))
6260 (setq has-children (org-list-has-child-p (point) struct)))
6261 (org-back-to-heading)
6262 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6263 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6264 (setq has-children
6265 (or (save-excursion
6266 (let ((level (funcall outline-level)))
6267 (outline-next-heading)
6268 (and (org-at-heading-p t)
6269 (> (funcall outline-level) level))))
6270 (save-excursion
6271 (org-list-search-forward (org-item-beginning-re) eos t)))))
6272 ;; Determine end invisible part of buffer (EOL)
6273 (beginning-of-line 2)
6274 ;; XEmacs doesn't have `next-single-char-property-change'
6275 (if (featurep 'xemacs)
6276 (while (and (not (eobp)) ;; this is like `next-line'
6277 (get-char-property (1- (point)) 'invisible))
6278 (beginning-of-line 2))
6279 (while (and (not (eobp)) ;; this is like `next-line'
6280 (get-char-property (1- (point)) 'invisible))
6281 (goto-char (next-single-char-property-change (point) 'invisible))
6282 (and (eolp) (beginning-of-line 2))))
6283 (setq eol (point)))
6284 ;; Find out what to do next and set `this-command'
6285 (cond
6286 ((= eos eoh)
6287 ;; Nothing is hidden behind this heading
6288 (unless (org-before-first-heading-p)
6289 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6290 (message "EMPTY ENTRY")
6291 (setq org-cycle-subtree-status nil)
6292 (save-excursion
6293 (goto-char eos)
6294 (outline-next-heading)
6295 (if (outline-invisible-p) (org-flag-heading nil))))
6296 ((and (or (>= eol eos)
6297 (not (string-match "\\S-" (buffer-substring eol eos))))
6298 (or has-children
6299 (not (setq children-skipped
6300 org-cycle-skip-children-state-if-no-children))))
6301 ;; Entire subtree is hidden in one line: children view
6302 (unless (org-before-first-heading-p)
6303 (run-hook-with-args 'org-pre-cycle-hook 'children))
6304 (if (org-at-item-p)
6305 (org-list-set-item-visibility (point-at-bol) struct 'children)
6306 (org-show-entry)
6307 (org-with-limited-levels (show-children))
6308 ;; FIXME: This slows down the func way too much.
6309 ;; How keep drawers hidden in subtree anyway?
6310 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6311 ;; (org-cycle-hide-drawers 'subtree))
6313 ;; Fold every list in subtree to top-level items.
6314 (when (eq org-cycle-include-plain-lists 'integrate)
6315 (save-excursion
6316 (org-back-to-heading)
6317 (while (org-list-search-forward (org-item-beginning-re) eos t)
6318 (beginning-of-line 1)
6319 (let* ((struct (org-list-struct))
6320 (prevs (org-list-prevs-alist struct))
6321 (end (org-list-get-bottom-point struct)))
6322 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6323 (org-list-get-all-items (point) struct prevs))
6324 (goto-char end))))))
6325 (message "CHILDREN")
6326 (save-excursion
6327 (goto-char eos)
6328 (outline-next-heading)
6329 (if (outline-invisible-p) (org-flag-heading nil)))
6330 (setq org-cycle-subtree-status 'children)
6331 (unless (org-before-first-heading-p)
6332 (run-hook-with-args 'org-cycle-hook 'children)))
6333 ((or children-skipped
6334 (and (eq last-command this-command)
6335 (eq org-cycle-subtree-status 'children)))
6336 ;; We just showed the children, or no children are there,
6337 ;; now show everything.
6338 (unless (org-before-first-heading-p)
6339 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6340 (outline-flag-region eoh eos nil)
6341 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6342 (setq org-cycle-subtree-status 'subtree)
6343 (unless (org-before-first-heading-p)
6344 (run-hook-with-args 'org-cycle-hook 'subtree)))
6346 ;; Default action: hide the subtree.
6347 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6348 (outline-flag-region eoh eos t)
6349 (message "FOLDED")
6350 (setq org-cycle-subtree-status 'folded)
6351 (unless (org-before-first-heading-p)
6352 (run-hook-with-args 'org-cycle-hook 'folded))))))
6354 ;;;###autoload
6355 (defun org-global-cycle (&optional arg)
6356 "Cycle the global visibility. For details see `org-cycle'.
6357 With \\[universal-argument] prefix arg, switch to startup visibility.
6358 With a numeric prefix, show all headlines up to that level."
6359 (interactive "P")
6360 (let ((org-cycle-include-plain-lists
6361 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6362 (cond
6363 ((integerp arg)
6364 (show-all)
6365 (hide-sublevels arg)
6366 (setq org-cycle-global-status 'contents))
6367 ((equal arg '(4))
6368 (org-set-startup-visibility)
6369 (message "Startup visibility, plus VISIBILITY properties."))
6371 (org-cycle '(4))))))
6373 (defun org-set-startup-visibility ()
6374 "Set the visibility required by startup options and properties."
6375 (cond
6376 ((eq org-startup-folded t)
6377 (org-cycle '(4)))
6378 ((eq org-startup-folded 'content)
6379 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6380 (org-cycle '(4)) (org-cycle '(4)))))
6381 (unless (eq org-startup-folded 'showeverything)
6382 (if org-hide-block-startup (org-hide-block-all))
6383 (org-set-visibility-according-to-property 'no-cleanup)
6384 (org-cycle-hide-archived-subtrees 'all)
6385 (org-cycle-hide-drawers 'all)
6386 (org-cycle-show-empty-lines t)))
6388 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6389 "Switch subtree visibilities according to :VISIBILITY: property."
6390 (interactive)
6391 (let (org-show-entry-below state)
6392 (save-excursion
6393 (goto-char (point-min))
6394 (while (re-search-forward
6395 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6396 nil t)
6397 (setq state (match-string 1))
6398 (save-excursion
6399 (org-back-to-heading t)
6400 (hide-subtree)
6401 (org-reveal)
6402 (cond
6403 ((equal state '("fold" "folded"))
6404 (hide-subtree))
6405 ((equal state "children")
6406 (org-show-hidden-entry)
6407 (show-children))
6408 ((equal state "content")
6409 (save-excursion
6410 (save-restriction
6411 (org-narrow-to-subtree)
6412 (org-content))))
6413 ((member state '("all" "showall"))
6414 (show-subtree)))))
6415 (unless no-cleanup
6416 (org-cycle-hide-archived-subtrees 'all)
6417 (org-cycle-hide-drawers 'all)
6418 (org-cycle-show-empty-lines 'all)))))
6420 ;; This function uses outline-regexp instead of the more fundamental
6421 ;; org-outline-regexp so that org-cycle-global works outside of Org
6422 ;; buffers, where outline-regexp is needed.
6423 (defun org-overview ()
6424 "Switch to overview mode, showing only top-level headlines.
6425 Really, this shows all headlines with level equal or greater than the level
6426 of the first headline in the buffer. This is important, because if the
6427 first headline is not level one, then (hide-sublevels 1) gives confusing
6428 results."
6429 (interactive)
6430 (let ((level (save-excursion
6431 (goto-char (point-min))
6432 (if (re-search-forward (concat "^" outline-regexp) nil t)
6433 (progn
6434 (goto-char (match-beginning 0))
6435 (funcall outline-level))))))
6436 (and level (hide-sublevels level))))
6438 (defun org-content (&optional arg)
6439 "Show all headlines in the buffer, like a table of contents.
6440 With numerical argument N, show content up to level N."
6441 (interactive "P")
6442 (save-excursion
6443 ;; Visit all headings and show their offspring
6444 (and (integerp arg) (org-overview))
6445 (goto-char (point-max))
6446 (catch 'exit
6447 (while (and (progn (condition-case nil
6448 (outline-previous-visible-heading 1)
6449 (error (goto-char (point-min))))
6451 (looking-at org-outline-regexp))
6452 (if (integerp arg)
6453 (show-children (1- arg))
6454 (show-branches))
6455 (if (bobp) (throw 'exit nil))))))
6458 (defun org-optimize-window-after-visibility-change (state)
6459 "Adjust the window after a change in outline visibility.
6460 This function is the default value of the hook `org-cycle-hook'."
6461 (when (get-buffer-window (current-buffer))
6462 (cond
6463 ((eq state 'content) nil)
6464 ((eq state 'all) nil)
6465 ((eq state 'folded) nil)
6466 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6467 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6469 (defun org-remove-empty-overlays-at (pos)
6470 "Remove outline overlays that do not contain non-white stuff."
6471 (mapc
6472 (lambda (o)
6473 (and (eq 'outline (overlay-get o 'invisible))
6474 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6475 (overlay-end o))))
6476 (delete-overlay o)))
6477 (overlays-at pos)))
6479 (defun org-clean-visibility-after-subtree-move ()
6480 "Fix visibility issues after moving a subtree."
6481 ;; First, find a reasonable region to look at:
6482 ;; Start two siblings above, end three below
6483 (let* ((beg (save-excursion
6484 (and (org-get-last-sibling)
6485 (org-get-last-sibling))
6486 (point)))
6487 (end (save-excursion
6488 (and (org-get-next-sibling)
6489 (org-get-next-sibling)
6490 (org-get-next-sibling))
6491 (if (org-at-heading-p)
6492 (point-at-eol)
6493 (point))))
6494 (level (looking-at "\\*+"))
6495 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6496 (save-excursion
6497 (save-restriction
6498 (narrow-to-region beg end)
6499 (when re
6500 ;; Properly fold already folded siblings
6501 (goto-char (point-min))
6502 (while (re-search-forward re nil t)
6503 (if (and (not (outline-invisible-p))
6504 (save-excursion
6505 (goto-char (point-at-eol)) (outline-invisible-p)))
6506 (hide-entry))))
6507 (org-cycle-show-empty-lines 'overview)
6508 (org-cycle-hide-drawers 'overview)))))
6510 (defun org-cycle-show-empty-lines (state)
6511 "Show empty lines above all visible headlines.
6512 The region to be covered depends on STATE when called through
6513 `org-cycle-hook'. Lisp program can use t for STATE to get the
6514 entire buffer covered. Note that an empty line is only shown if there
6515 are at least `org-cycle-separator-lines' empty lines before the headline."
6516 (when (not (= org-cycle-separator-lines 0))
6517 (save-excursion
6518 (let* ((n (abs org-cycle-separator-lines))
6519 (re (cond
6520 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6521 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6522 (t (let ((ns (number-to-string (- n 2))))
6523 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6524 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6525 beg end b e)
6526 (cond
6527 ((memq state '(overview contents t))
6528 (setq beg (point-min) end (point-max)))
6529 ((memq state '(children folded))
6530 (setq beg (point) end (progn (org-end-of-subtree t t)
6531 (beginning-of-line 2)
6532 (point)))))
6533 (when beg
6534 (goto-char beg)
6535 (while (re-search-forward re end t)
6536 (unless (get-char-property (match-end 1) 'invisible)
6537 (setq e (match-end 1))
6538 (if (< org-cycle-separator-lines 0)
6539 (setq b (save-excursion
6540 (goto-char (match-beginning 0))
6541 (org-back-over-empty-lines)
6542 (if (save-excursion
6543 (goto-char (max (point-min) (1- (point))))
6544 (org-at-heading-p))
6545 (1- (point))
6546 (point))))
6547 (setq b (match-beginning 1)))
6548 (outline-flag-region b e nil)))))))
6549 ;; Never hide empty lines at the end of the file.
6550 (save-excursion
6551 (goto-char (point-max))
6552 (outline-previous-heading)
6553 (outline-end-of-heading)
6554 (if (and (looking-at "[ \t\n]+")
6555 (= (match-end 0) (point-max)))
6556 (outline-flag-region (point) (match-end 0) nil))))
6558 (defun org-show-empty-lines-in-parent ()
6559 "Move to the parent and re-show empty lines before visible headlines."
6560 (save-excursion
6561 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6562 (org-cycle-show-empty-lines context))))
6564 (defun org-files-list ()
6565 "Return `org-agenda-files' list, plus all open org-mode files.
6566 This is useful for operations that need to scan all of a user's
6567 open and agenda-wise Org files."
6568 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6569 (dolist (buf (buffer-list))
6570 (with-current-buffer buf
6571 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6572 (let ((file (expand-file-name (buffer-file-name))))
6573 (unless (member file files)
6574 (push file files))))))
6575 files))
6577 (defsubst org-entry-beginning-position ()
6578 "Return the beginning position of the current entry."
6579 (save-excursion (outline-back-to-heading t) (point)))
6581 (defsubst org-entry-end-position ()
6582 "Return the end position of the current entry."
6583 (save-excursion (outline-next-heading) (point)))
6585 (defun org-cycle-hide-drawers (state)
6586 "Re-hide all drawers after a visibility state change."
6587 (when (and (derived-mode-p 'org-mode)
6588 (not (memq state '(overview folded contents))))
6589 (save-excursion
6590 (let* ((globalp (memq state '(contents all)))
6591 (beg (if globalp (point-min) (point)))
6592 (end (if globalp (point-max)
6593 (if (eq state 'children)
6594 (save-excursion (outline-next-heading) (point))
6595 (org-end-of-subtree t)))))
6596 (goto-char beg)
6597 (while (re-search-forward org-drawer-regexp end t)
6598 (org-flag-drawer t))))))
6600 (defun org-flag-drawer (flag)
6601 "When FLAG is non-nil, hide the drawer we are within.
6602 Otherwise make it visible."
6603 (save-excursion
6604 (beginning-of-line 1)
6605 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6606 (let ((b (match-end 0)))
6607 (if (re-search-forward
6608 "^[ \t]*:END:"
6609 (save-excursion (outline-next-heading) (point)) t)
6610 (outline-flag-region b (point-at-eol) flag)
6611 (error ":END: line missing at position %s" b))))))
6613 (defun org-subtree-end-visible-p ()
6614 "Is the end of the current subtree visible?"
6615 (pos-visible-in-window-p
6616 (save-excursion (org-end-of-subtree t) (point))))
6618 (defun org-first-headline-recenter (&optional N)
6619 "Move cursor to the first headline and recenter the headline.
6620 Optional argument N means put the headline into the Nth line of the window."
6621 (goto-char (point-min))
6622 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6623 (beginning-of-line)
6624 (recenter (prefix-numeric-value N))))
6626 ;;; Saving and restoring visibility
6628 (defun org-outline-overlay-data (&optional use-markers)
6629 "Return a list of the locations of all outline overlays.
6630 These are overlays with the `invisible' property value `outline'.
6631 The return value is a list of cons cells, with start and stop
6632 positions for each overlay.
6633 If USE-MARKERS is set, return the positions as markers."
6634 (let (beg end)
6635 (save-excursion
6636 (save-restriction
6637 (widen)
6638 (delq nil
6639 (mapcar (lambda (o)
6640 (when (eq (overlay-get o 'invisible) 'outline)
6641 (setq beg (overlay-start o)
6642 end (overlay-end o))
6643 (and beg end (> end beg)
6644 (if use-markers
6645 (cons (move-marker (make-marker) beg)
6646 (move-marker (make-marker) end))
6647 (cons beg end)))))
6648 (overlays-in (point-min) (point-max))))))))
6650 (defun org-set-outline-overlay-data (data)
6651 "Create visibility overlays for all positions in DATA.
6652 DATA should have been made by `org-outline-overlay-data'."
6653 (let (o)
6654 (save-excursion
6655 (save-restriction
6656 (widen)
6657 (show-all)
6658 (mapc (lambda (c)
6659 (outline-flag-region (car c) (cdr c) t))
6660 data)))))
6662 ;;; Folding of blocks
6664 (defvar org-hide-block-overlays nil
6665 "Overlays hiding blocks.")
6666 (make-variable-buffer-local 'org-hide-block-overlays)
6668 (defun org-block-map (function &optional start end)
6669 "Call FUNCTION at the head of all source blocks in the current buffer.
6670 Optional arguments START and END can be used to limit the range."
6671 (let ((start (or start (point-min)))
6672 (end (or end (point-max))))
6673 (save-excursion
6674 (goto-char start)
6675 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6676 (save-excursion
6677 (save-match-data
6678 (goto-char (match-beginning 0))
6679 (funcall function)))))))
6681 (defun org-hide-block-toggle-all ()
6682 "Toggle the visibility of all blocks in the current buffer."
6683 (org-block-map #'org-hide-block-toggle))
6685 (defun org-hide-block-all ()
6686 "Fold all blocks in the current buffer."
6687 (interactive)
6688 (org-show-block-all)
6689 (org-block-map #'org-hide-block-toggle-maybe))
6691 (defun org-show-block-all ()
6692 "Unfold all blocks in the current buffer."
6693 (interactive)
6694 (mapc 'delete-overlay org-hide-block-overlays)
6695 (setq org-hide-block-overlays nil))
6697 (defun org-hide-block-toggle-maybe ()
6698 "Toggle visibility of block at point."
6699 (interactive)
6700 (let ((case-fold-search t))
6701 (if (save-excursion
6702 (beginning-of-line 1)
6703 (looking-at org-block-regexp))
6704 (progn (org-hide-block-toggle)
6705 t) ;; to signal that we took action
6706 nil))) ;; to signal that we did not
6708 (defun org-hide-block-toggle (&optional force)
6709 "Toggle the visibility of the current block."
6710 (interactive)
6711 (save-excursion
6712 (beginning-of-line)
6713 (if (re-search-forward org-block-regexp nil t)
6714 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6715 (end (match-end 0)) ;; end of entire body
6717 (if (memq t (mapcar (lambda (overlay)
6718 (eq (overlay-get overlay 'invisible)
6719 'org-hide-block))
6720 (overlays-at start)))
6721 (if (or (not force) (eq force 'off))
6722 (mapc (lambda (ov)
6723 (when (member ov org-hide-block-overlays)
6724 (setq org-hide-block-overlays
6725 (delq ov org-hide-block-overlays)))
6726 (when (eq (overlay-get ov 'invisible)
6727 'org-hide-block)
6728 (delete-overlay ov)))
6729 (overlays-at start)))
6730 (setq ov (make-overlay start end))
6731 (overlay-put ov 'invisible 'org-hide-block)
6732 ;; make the block accessible to isearch
6733 (overlay-put
6734 ov 'isearch-open-invisible
6735 (lambda (ov)
6736 (when (member ov org-hide-block-overlays)
6737 (setq org-hide-block-overlays
6738 (delq ov org-hide-block-overlays)))
6739 (when (eq (overlay-get ov 'invisible)
6740 'org-hide-block)
6741 (delete-overlay ov))))
6742 (push ov org-hide-block-overlays)))
6743 (error "Not looking at a source block"))))
6745 ;; org-tab-after-check-for-cycling-hook
6746 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6747 ;; Remove overlays when changing major mode
6748 (add-hook 'org-mode-hook
6749 (lambda () (org-add-hook 'change-major-mode-hook
6750 'org-show-block-all 'append 'local)))
6752 ;;; Org-goto
6754 (defvar org-goto-window-configuration nil)
6755 (defvar org-goto-marker nil)
6756 (defvar org-goto-map
6757 (let ((map (make-sparse-keymap)))
6758 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6759 (while (setq cmd (pop cmds))
6760 (substitute-key-definition cmd cmd map global-map)))
6761 (suppress-keymap map)
6762 (org-defkey map "\C-m" 'org-goto-ret)
6763 (org-defkey map [(return)] 'org-goto-ret)
6764 (org-defkey map [(left)] 'org-goto-left)
6765 (org-defkey map [(right)] 'org-goto-right)
6766 (org-defkey map [(control ?g)] 'org-goto-quit)
6767 (org-defkey map "\C-i" 'org-cycle)
6768 (org-defkey map [(tab)] 'org-cycle)
6769 (org-defkey map [(down)] 'outline-next-visible-heading)
6770 (org-defkey map [(up)] 'outline-previous-visible-heading)
6771 (if org-goto-auto-isearch
6772 (if (fboundp 'define-key-after)
6773 (define-key-after map [t] 'org-goto-local-auto-isearch)
6774 nil)
6775 (org-defkey map "q" 'org-goto-quit)
6776 (org-defkey map "n" 'outline-next-visible-heading)
6777 (org-defkey map "p" 'outline-previous-visible-heading)
6778 (org-defkey map "f" 'outline-forward-same-level)
6779 (org-defkey map "b" 'outline-backward-same-level)
6780 (org-defkey map "u" 'outline-up-heading))
6781 (org-defkey map "/" 'org-occur)
6782 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6783 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6784 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6785 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6786 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6787 map))
6789 (defconst org-goto-help
6790 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6791 RET=jump to location [Q]uit and return to previous location
6792 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6794 (defvar org-goto-start-pos) ; dynamically scoped parameter
6796 ;; FIXME: Docstring does not mention both interfaces
6797 (defun org-goto (&optional alternative-interface)
6798 "Look up a different location in the current file, keeping current visibility.
6800 When you want look-up or go to a different location in a
6801 document, the fastest way is often to fold the entire buffer and
6802 then dive into the tree. This method has the disadvantage, that
6803 the previous location will be folded, which may not be what you
6804 want.
6806 This command works around this by showing a copy of the current
6807 buffer in an indirect buffer, in overview mode. You can dive
6808 into the tree in that copy, use org-occur and incremental search
6809 to find a location. When pressing RET or `Q', the command
6810 returns to the original buffer in which the visibility is still
6811 unchanged. After RET it will also jump to the location selected
6812 in the indirect buffer and expose the headline hierarchy above.
6814 With a prefix argument, use the alternative interface: e.g. if
6815 `org-goto-interface' is 'outline use 'outline-path-completion."
6816 (interactive "P")
6817 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6818 (org-refile-use-outline-path t)
6819 (org-refile-target-verify-function nil)
6820 (interface
6821 (if (not alternative-interface)
6822 org-goto-interface
6823 (if (eq org-goto-interface 'outline)
6824 'outline-path-completion
6825 'outline)))
6826 (org-goto-start-pos (point))
6827 (selected-point
6828 (if (eq interface 'outline)
6829 (car (org-get-location (current-buffer) org-goto-help))
6830 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6831 (org-refile-check-position pa)
6832 (nth 3 pa)))))
6833 (if selected-point
6834 (progn
6835 (org-mark-ring-push org-goto-start-pos)
6836 (goto-char selected-point)
6837 (if (or (outline-invisible-p) (org-invisible-p2))
6838 (org-show-context 'org-goto)))
6839 (message "Quit"))))
6841 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6842 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6843 (defvar org-goto-local-auto-isearch-map) ; defined below
6845 (defun org-get-location (buf help)
6846 "Let the user select a location in the Org-mode buffer BUF.
6847 This function uses a recursive edit. It returns the selected position
6848 or nil."
6849 (org-no-popups
6850 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6851 (isearch-hide-immediately nil)
6852 (isearch-search-fun-function
6853 (lambda () 'org-goto-local-search-headings))
6854 (org-goto-selected-point org-goto-exit-command))
6855 (save-excursion
6856 (save-window-excursion
6857 (delete-other-windows)
6858 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6859 (org-pop-to-buffer-same-window
6860 (condition-case nil
6861 (make-indirect-buffer (current-buffer) "*org-goto*")
6862 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6863 (with-output-to-temp-buffer "*Help*"
6864 (princ help))
6865 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6866 (setq buffer-read-only nil)
6867 (let ((org-startup-truncated t)
6868 (org-startup-folded nil)
6869 (org-startup-align-all-tables nil))
6870 (org-mode)
6871 (org-overview))
6872 (setq buffer-read-only t)
6873 (if (and (boundp 'org-goto-start-pos)
6874 (integer-or-marker-p org-goto-start-pos))
6875 (let ((org-show-hierarchy-above t)
6876 (org-show-siblings t)
6877 (org-show-following-heading t))
6878 (goto-char org-goto-start-pos)
6879 (and (outline-invisible-p) (org-show-context)))
6880 (goto-char (point-min)))
6881 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6882 (message "Select location and press RET")
6883 (use-local-map org-goto-map)
6884 (recursive-edit)
6886 (kill-buffer "*org-goto*")
6887 (cons org-goto-selected-point org-goto-exit-command))))
6889 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6890 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6891 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6892 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6894 (defun org-goto-local-search-headings (string bound noerror)
6895 "Search and make sure that any matches are in headlines."
6896 (catch 'return
6897 (while (if isearch-forward
6898 (search-forward string bound noerror)
6899 (search-backward string bound noerror))
6900 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6901 (and (member :headline context)
6902 (not (member :tags context))))
6903 (throw 'return (point))))))
6905 (defun org-goto-local-auto-isearch ()
6906 "Start isearch."
6907 (interactive)
6908 (goto-char (point-min))
6909 (let ((keys (this-command-keys)))
6910 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6911 (isearch-mode t)
6912 (isearch-process-search-char (string-to-char keys)))))
6914 (defun org-goto-ret (&optional arg)
6915 "Finish `org-goto' by going to the new location."
6916 (interactive "P")
6917 (setq org-goto-selected-point (point)
6918 org-goto-exit-command 'return)
6919 (throw 'exit nil))
6921 (defun org-goto-left ()
6922 "Finish `org-goto' by going to the new location."
6923 (interactive)
6924 (if (org-at-heading-p)
6925 (progn
6926 (beginning-of-line 1)
6927 (setq org-goto-selected-point (point)
6928 org-goto-exit-command 'left)
6929 (throw 'exit nil))
6930 (error "Not on a heading")))
6932 (defun org-goto-right ()
6933 "Finish `org-goto' by going to the new location."
6934 (interactive)
6935 (if (org-at-heading-p)
6936 (progn
6937 (setq org-goto-selected-point (point)
6938 org-goto-exit-command 'right)
6939 (throw 'exit nil))
6940 (error "Not on a heading")))
6942 (defun org-goto-quit ()
6943 "Finish `org-goto' without cursor motion."
6944 (interactive)
6945 (setq org-goto-selected-point nil)
6946 (setq org-goto-exit-command 'quit)
6947 (throw 'exit nil))
6949 ;;; Indirect buffer display of subtrees
6951 (defvar org-indirect-dedicated-frame nil
6952 "This is the frame being used for indirect tree display.")
6953 (defvar org-last-indirect-buffer nil)
6955 (defun org-tree-to-indirect-buffer (&optional arg)
6956 "Create indirect buffer and narrow it to current subtree.
6957 With a numerical prefix ARG, go up to this level and then take that tree.
6958 If ARG is negative, go up that many levels.
6960 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6961 indirect buffer previously made with this command, to avoid proliferation of
6962 indirect buffers. However, when you call the command with a \
6963 \\[universal-argument] prefix, or
6964 when `org-indirect-buffer-display' is `new-frame', the last buffer
6965 is kept so that you can work with several indirect buffers at the same time.
6966 If `org-indirect-buffer-display' is `dedicated-frame', the \
6967 \\[universal-argument] prefix also
6968 requests that a new frame be made for the new buffer, so that the dedicated
6969 frame is not changed."
6970 (interactive "P")
6971 (let ((cbuf (current-buffer))
6972 (cwin (selected-window))
6973 (pos (point))
6974 beg end level heading ibuf)
6975 (save-excursion
6976 (org-back-to-heading t)
6977 (when (numberp arg)
6978 (setq level (org-outline-level))
6979 (if (< arg 0) (setq arg (+ level arg)))
6980 (while (> (setq level (org-outline-level)) arg)
6981 (org-up-heading-safe)))
6982 (setq beg (point)
6983 heading (org-get-heading))
6984 (org-end-of-subtree t t)
6985 (if (org-at-heading-p) (backward-char 1))
6986 (setq end (point)))
6987 (if (and (buffer-live-p org-last-indirect-buffer)
6988 (not (eq org-indirect-buffer-display 'new-frame))
6989 (not arg))
6990 (kill-buffer org-last-indirect-buffer))
6991 (setq ibuf (org-get-indirect-buffer cbuf)
6992 org-last-indirect-buffer ibuf)
6993 (cond
6994 ((or (eq org-indirect-buffer-display 'new-frame)
6995 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6996 (select-frame (make-frame))
6997 (delete-other-windows)
6998 (org-pop-to-buffer-same-window ibuf)
6999 (org-set-frame-title heading))
7000 ((eq org-indirect-buffer-display 'dedicated-frame)
7001 (raise-frame
7002 (select-frame (or (and org-indirect-dedicated-frame
7003 (frame-live-p org-indirect-dedicated-frame)
7004 org-indirect-dedicated-frame)
7005 (setq org-indirect-dedicated-frame (make-frame)))))
7006 (delete-other-windows)
7007 (org-pop-to-buffer-same-window ibuf)
7008 (org-set-frame-title (concat "Indirect: " heading)))
7009 ((eq org-indirect-buffer-display 'current-window)
7010 (org-pop-to-buffer-same-window ibuf))
7011 ((eq org-indirect-buffer-display 'other-window)
7012 (pop-to-buffer ibuf))
7013 (t (error "Invalid value")))
7014 (if (featurep 'xemacs)
7015 (save-excursion (org-mode) (turn-on-font-lock)))
7016 (narrow-to-region beg end)
7017 (show-all)
7018 (goto-char pos)
7019 (run-hook-with-args 'org-cycle-hook 'all)
7020 (and (window-live-p cwin) (select-window cwin))))
7022 (defun org-get-indirect-buffer (&optional buffer)
7023 (setq buffer (or buffer (current-buffer)))
7024 (let ((n 1) (base (buffer-name buffer)) bname)
7025 (while (buffer-live-p
7026 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7027 (setq n (1+ n)))
7028 (condition-case nil
7029 (make-indirect-buffer buffer bname 'clone)
7030 (error (make-indirect-buffer buffer bname)))))
7032 (defun org-set-frame-title (title)
7033 "Set the title of the current frame to the string TITLE."
7034 ;; FIXME: how to name a single frame in XEmacs???
7035 (unless (featurep 'xemacs)
7036 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7038 ;;;; Structure editing
7040 ;;; Inserting headlines
7042 (defun org-previous-line-empty-p ()
7043 (save-excursion
7044 (and (not (bobp))
7045 (or (beginning-of-line 0) t)
7046 (save-match-data
7047 (looking-at "[ \t]*$")))))
7049 (defun org-insert-heading (&optional force-heading invisible-ok)
7050 "Insert a new heading or item with same depth at point.
7051 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7052 If point is at the beginning of a headline, insert a sibling before the
7053 current headline. If point is not at the beginning, split the line,
7054 create the new headline with the text in the current line after point
7055 \(but see also the variable `org-M-RET-may-split-line').
7057 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7058 This is important for non-interactive uses of the command."
7059 (interactive "P")
7060 (if (or (= (buffer-size) 0)
7061 (and (not (save-excursion
7062 (and (ignore-errors (org-back-to-heading invisible-ok))
7063 (org-at-heading-p))))
7064 (or force-heading (not (org-in-item-p)))))
7065 (progn
7066 (insert "\n* ")
7067 (run-hooks 'org-insert-heading-hook))
7068 (when (or force-heading (not (org-insert-item)))
7069 (let* ((empty-line-p nil)
7070 (level nil)
7071 (on-heading (org-at-heading-p))
7072 (head (save-excursion
7073 (condition-case nil
7074 (progn
7075 (org-back-to-heading invisible-ok)
7076 (when (and (not on-heading)
7077 (featurep 'org-inlinetask)
7078 (integerp org-inlinetask-min-level)
7079 (>= (length (match-string 0))
7080 org-inlinetask-min-level))
7081 ;; Find a heading level before the inline task
7082 (while (and (setq level (org-up-heading-safe))
7083 (>= level org-inlinetask-min-level)))
7084 (if (org-at-heading-p)
7085 (org-back-to-heading invisible-ok)
7086 (error "This should not happen")))
7087 (setq empty-line-p (org-previous-line-empty-p))
7088 (match-string 0))
7089 (error "*"))))
7090 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7091 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7092 pos hide-previous previous-pos)
7093 (cond
7094 ((and (org-at-heading-p) (bolp)
7095 (or (bobp)
7096 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7097 ;; insert before the current line
7098 (open-line (if blank 2 1)))
7099 ((and (bolp)
7100 (not org-insert-heading-respect-content)
7101 (or (bobp)
7102 (save-excursion
7103 (backward-char 1) (not (outline-invisible-p)))))
7104 ;; insert right here
7105 nil)
7107 ;; somewhere in the line
7108 (save-excursion
7109 (setq previous-pos (point-at-bol))
7110 (end-of-line)
7111 (setq hide-previous (outline-invisible-p)))
7112 (and org-insert-heading-respect-content (org-show-subtree))
7113 (let ((split
7114 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7115 (save-excursion
7116 (let ((p (point)))
7117 (goto-char (point-at-bol))
7118 (and (looking-at org-complex-heading-regexp)
7119 (match-beginning 4)
7120 (> p (match-beginning 4)))))))
7121 tags pos)
7122 (cond
7123 (org-insert-heading-respect-content
7124 (org-end-of-subtree nil t)
7125 (when (featurep 'org-inlinetask)
7126 (while (and (not (eobp))
7127 (looking-at "\\(\\*+\\)[ \t]+")
7128 (>= (length (match-string 1))
7129 org-inlinetask-min-level))
7130 (org-end-of-subtree nil t)))
7131 (or (bolp) (newline))
7132 (or (org-previous-line-empty-p)
7133 (and blank (newline)))
7134 (open-line 1))
7135 ((org-at-heading-p)
7136 (when hide-previous
7137 (show-children)
7138 (org-show-entry))
7139 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7140 (setq tags (and (match-end 2) (match-string 2)))
7141 (and (match-end 1)
7142 (delete-region (match-beginning 1) (match-end 1)))
7143 (setq pos (point-at-bol))
7144 (or split (end-of-line 1))
7145 (delete-horizontal-space)
7146 (if (string-match "\\`\\*+\\'"
7147 (buffer-substring (point-at-bol) (point)))
7148 (insert " "))
7149 (newline (if blank 2 1))
7150 (when tags
7151 (save-excursion
7152 (goto-char pos)
7153 (end-of-line 1)
7154 (insert " " tags)
7155 (org-set-tags nil 'align))))
7157 (or split (end-of-line 1))
7158 (newline (if blank 2 1)))))))
7159 (insert head) (just-one-space)
7160 (setq pos (point))
7161 (end-of-line 1)
7162 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7163 (when (and org-insert-heading-respect-content hide-previous)
7164 (save-excursion
7165 (goto-char previous-pos)
7166 (hide-subtree)))
7167 (run-hooks 'org-insert-heading-hook)))))
7169 (defun org-get-heading (&optional no-tags no-todo)
7170 "Return the heading of the current entry, without the stars.
7171 When NO-TAGS is non-nil, don't include tags.
7172 When NO-TODO is non-nil, don't include TODO keywords."
7173 (save-excursion
7174 (org-back-to-heading t)
7175 (cond
7176 ((and no-tags no-todo)
7177 (looking-at org-complex-heading-regexp)
7178 (match-string 4))
7179 (no-tags
7180 (looking-at (concat org-outline-regexp
7181 "\\(.*?\\)"
7182 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7183 (match-string 1))
7184 (no-todo
7185 (looking-at org-todo-line-regexp)
7186 (match-string 3))
7187 (t (looking-at org-heading-regexp)
7188 (match-string 2)))))
7190 (defun org-heading-components ()
7191 "Return the components of the current heading.
7192 This is a list with the following elements:
7193 - the level as an integer
7194 - the reduced level, different if `org-odd-levels-only' is set.
7195 - the TODO keyword, or nil
7196 - the priority character, like ?A, or nil if no priority is given
7197 - the headline text itself, or the tags string if no headline text
7198 - the tags string, or nil."
7199 (save-excursion
7200 (org-back-to-heading t)
7201 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7202 (list (length (match-string 1))
7203 (org-reduced-level (length (match-string 1)))
7204 (org-match-string-no-properties 2)
7205 (and (match-end 3) (aref (match-string 3) 2))
7206 (org-match-string-no-properties 4)
7207 (org-match-string-no-properties 5)))))
7209 (defun org-get-entry ()
7210 "Get the entry text, after heading, entire subtree."
7211 (save-excursion
7212 (org-back-to-heading t)
7213 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7215 (defun org-insert-heading-after-current ()
7216 "Insert a new heading with same level as current, after current subtree."
7217 (interactive)
7218 (org-back-to-heading)
7219 (org-insert-heading)
7220 (org-move-subtree-down)
7221 (end-of-line 1))
7223 (defun org-insert-heading-respect-content ()
7224 (interactive)
7225 (let ((org-insert-heading-respect-content t))
7226 (org-insert-heading t)))
7228 (defun org-insert-todo-heading-respect-content (&optional force-state)
7229 (interactive "P")
7230 (let ((org-insert-heading-respect-content t))
7231 (org-insert-todo-heading force-state t)))
7233 (defun org-insert-todo-heading (arg &optional force-heading)
7234 "Insert a new heading with the same level and TODO state as current heading.
7235 If the heading has no TODO state, or if the state is DONE, use the first
7236 state (TODO by default). Also with prefix arg, force first state."
7237 (interactive "P")
7238 (when (or force-heading (not (org-insert-item 'checkbox)))
7239 (org-insert-heading force-heading)
7240 (save-excursion
7241 (org-back-to-heading)
7242 (outline-previous-heading)
7243 (looking-at org-todo-line-regexp))
7244 (let*
7245 ((new-mark-x
7246 (if (or arg
7247 (not (match-beginning 2))
7248 (member (match-string 2) org-done-keywords))
7249 (car org-todo-keywords-1)
7250 (match-string 2)))
7251 (new-mark
7253 (run-hook-with-args-until-success
7254 'org-todo-get-default-hook new-mark-x nil)
7255 new-mark-x)))
7256 (beginning-of-line 1)
7257 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7258 (if org-treat-insert-todo-heading-as-state-change
7259 (org-todo new-mark)
7260 (insert new-mark " "))))
7261 (when org-provide-todo-statistics
7262 (org-update-parent-todo-statistics))))
7264 (defun org-insert-subheading (arg)
7265 "Insert a new subheading and demote it.
7266 Works for outline headings and for plain lists alike."
7267 (interactive "P")
7268 (org-insert-heading arg)
7269 (cond
7270 ((org-at-heading-p) (org-do-demote))
7271 ((org-at-item-p) (org-indent-item))))
7273 (defun org-insert-todo-subheading (arg)
7274 "Insert a new subheading with TODO keyword or checkbox and demote it.
7275 Works for outline headings and for plain lists alike."
7276 (interactive "P")
7277 (org-insert-todo-heading arg)
7278 (cond
7279 ((org-at-heading-p) (org-do-demote))
7280 ((org-at-item-p) (org-indent-item))))
7282 ;;; Promotion and Demotion
7284 (defvar org-after-demote-entry-hook nil
7285 "Hook run after an entry has been demoted.
7286 The cursor will be at the beginning of the entry.
7287 When a subtree is being demoted, the hook will be called for each node.")
7289 (defvar org-after-promote-entry-hook nil
7290 "Hook run after an entry has been promoted.
7291 The cursor will be at the beginning of the entry.
7292 When a subtree is being promoted, the hook will be called for each node.")
7294 (defun org-promote-subtree ()
7295 "Promote the entire subtree.
7296 See also `org-promote'."
7297 (interactive)
7298 (save-excursion
7299 (org-with-limited-levels (org-map-tree 'org-promote)))
7300 (org-fix-position-after-promote))
7302 (defun org-demote-subtree ()
7303 "Demote the entire subtree. See `org-demote'.
7304 See also `org-promote'."
7305 (interactive)
7306 (save-excursion
7307 (org-with-limited-levels (org-map-tree 'org-demote)))
7308 (org-fix-position-after-promote))
7311 (defun org-do-promote ()
7312 "Promote the current heading higher up the tree.
7313 If the region is active in `transient-mark-mode', promote all headings
7314 in the region."
7315 (interactive)
7316 (save-excursion
7317 (if (org-region-active-p)
7318 (org-map-region 'org-promote (region-beginning) (region-end))
7319 (org-promote)))
7320 (org-fix-position-after-promote))
7322 (defun org-do-demote ()
7323 "Demote the current heading lower down the tree.
7324 If the region is active in `transient-mark-mode', demote all headings
7325 in the region."
7326 (interactive)
7327 (save-excursion
7328 (if (org-region-active-p)
7329 (org-map-region 'org-demote (region-beginning) (region-end))
7330 (org-demote)))
7331 (org-fix-position-after-promote))
7333 (defun org-fix-position-after-promote ()
7334 "Make sure that after pro/demotion cursor position is right."
7335 (let ((pos (point)))
7336 (when (save-excursion
7337 (beginning-of-line 1)
7338 (looking-at org-todo-line-regexp)
7339 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7340 (cond ((eobp) (insert " "))
7341 ((eolp) (insert " "))
7342 ((equal (char-after) ?\ ) (forward-char 1))))))
7344 (defun org-current-level ()
7345 "Return the level of the current entry, or nil if before the first headline.
7346 The level is the number of stars at the beginning of the headline."
7347 (save-excursion
7348 (org-with-limited-levels
7349 (if (ignore-errors (org-back-to-heading t))
7350 (funcall outline-level)))))
7352 (defun org-get-previous-line-level ()
7353 "Return the outline depth of the last headline before the current line.
7354 Returns 0 for the first headline in the buffer, and nil if before the
7355 first headline."
7356 (let ((current-level (org-current-level))
7357 (prev-level (when (> (line-number-at-pos) 1)
7358 (save-excursion
7359 (beginning-of-line 0)
7360 (org-current-level)))))
7361 (cond ((null current-level) nil) ; Before first headline
7362 ((null prev-level) 0) ; At first headline
7363 (prev-level))))
7365 (defun org-reduced-level (l)
7366 "Compute the effective level of a heading.
7367 This takes into account the setting of `org-odd-levels-only'."
7368 (cond
7369 ((zerop l) 0)
7370 (org-odd-levels-only (1+ (floor (/ l 2))))
7371 (t l)))
7373 (defun org-level-increment ()
7374 "Return the number of stars that will be added or removed at a
7375 time to headlines when structure editing, based on the value of
7376 `org-odd-levels-only'."
7377 (if org-odd-levels-only 2 1))
7379 (defun org-get-valid-level (level &optional change)
7380 "Rectify a level change under the influence of `org-odd-levels-only'
7381 LEVEL is a current level, CHANGE is by how much the level should be
7382 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7383 even level numbers will become the next higher odd number."
7384 (if org-odd-levels-only
7385 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7386 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7387 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7388 (max 1 (+ level (or change 0)))))
7390 (if (boundp 'define-obsolete-function-alias)
7391 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7392 (define-obsolete-function-alias 'org-get-legal-level
7393 'org-get-valid-level)
7394 (define-obsolete-function-alias 'org-get-legal-level
7395 'org-get-valid-level "23.1")))
7397 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7398 ;; ̀org-with-limited-levels'
7399 (defun org-promote ()
7400 "Promote the current heading higher up the tree.
7401 If the region is active in `transient-mark-mode', promote all headings
7402 in the region."
7403 (org-back-to-heading t)
7404 (let* ((level (save-match-data (funcall outline-level)))
7405 (after-change-functions (remove 'flyspell-after-change-function
7406 after-change-functions))
7407 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7408 (diff (abs (- level (length up-head) -1))))
7409 (cond ((and (= level 1) org-called-with-limited-levels
7410 org-allow-promoting-top-level-subtree)
7411 (replace-match "# " nil t))
7412 ((= level 1)
7413 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7414 (t (replace-match up-head nil t)))
7415 ;; Fixup tag positioning
7416 (unless (= level 1)
7417 (and org-auto-align-tags (org-set-tags nil t))
7418 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7419 (run-hooks 'org-after-promote-entry-hook)))
7421 (defun org-demote ()
7422 "Demote the current heading lower down the tree.
7423 If the region is active in `transient-mark-mode', demote all headings
7424 in the region."
7425 (org-back-to-heading t)
7426 (let* ((level (save-match-data (funcall outline-level)))
7427 (after-change-functions (remove 'flyspell-after-change-function
7428 after-change-functions))
7429 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7430 (diff (abs (- level (length down-head) -1))))
7431 (replace-match down-head nil t)
7432 ;; Fixup tag positioning
7433 (and org-auto-align-tags (org-set-tags nil t))
7434 (if org-adapt-indentation (org-fixup-indentation diff))
7435 (run-hooks 'org-after-demote-entry-hook)))
7437 (defun org-cycle-level ()
7438 "Cycle the level of an empty headline through possible states.
7439 This goes first to child, then to parent, level, then up the hierarchy.
7440 After top level, it switches back to sibling level."
7441 (interactive)
7442 (let ((org-adapt-indentation nil))
7443 (when (org-point-at-end-of-empty-headline)
7444 (setq this-command 'org-cycle-level) ; Only needed for caching
7445 (let ((cur-level (org-current-level))
7446 (prev-level (org-get-previous-line-level)))
7447 (cond
7448 ;; If first headline in file, promote to top-level.
7449 ((= prev-level 0)
7450 (loop repeat (/ (- cur-level 1) (org-level-increment))
7451 do (org-do-promote)))
7452 ;; If same level as prev, demote one.
7453 ((= prev-level cur-level)
7454 (org-do-demote))
7455 ;; If parent is top-level, promote to top level if not already.
7456 ((= prev-level 1)
7457 (loop repeat (/ (- cur-level 1) (org-level-increment))
7458 do (org-do-promote)))
7459 ;; If top-level, return to prev-level.
7460 ((= cur-level 1)
7461 (loop repeat (/ (- prev-level 1) (org-level-increment))
7462 do (org-do-demote)))
7463 ;; If less than prev-level, promote one.
7464 ((< cur-level prev-level)
7465 (org-do-promote))
7466 ;; If deeper than prev-level, promote until higher than
7467 ;; prev-level.
7468 ((> cur-level prev-level)
7469 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7470 do (org-do-promote))))
7471 t))))
7473 (defun org-map-tree (fun)
7474 "Call FUN for every heading underneath the current one."
7475 (org-back-to-heading)
7476 (let ((level (funcall outline-level)))
7477 (save-excursion
7478 (funcall fun)
7479 (while (and (progn
7480 (outline-next-heading)
7481 (> (funcall outline-level) level))
7482 (not (eobp)))
7483 (funcall fun)))))
7485 (defun org-map-region (fun beg end)
7486 "Call FUN for every heading between BEG and END."
7487 (let ((org-ignore-region t))
7488 (save-excursion
7489 (setq end (copy-marker end))
7490 (goto-char beg)
7491 (if (and (re-search-forward org-outline-regexp-bol nil t)
7492 (< (point) end))
7493 (funcall fun))
7494 (while (and (progn
7495 (outline-next-heading)
7496 (< (point) end))
7497 (not (eobp)))
7498 (funcall fun)))))
7500 (defvar org-property-end-re) ; silence byte-compiler
7501 (defun org-fixup-indentation (diff)
7502 "Change the indentation in the current entry by DIFF.
7503 However, if any line in the current entry has no indentation, or if it
7504 would end up with no indentation after the change, nothing at all is done."
7505 (save-excursion
7506 (let ((end (save-excursion (outline-next-heading)
7507 (point-marker)))
7508 (prohibit (if (> diff 0)
7509 "^\\S-"
7510 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7511 col)
7512 (unless (save-excursion (end-of-line 1)
7513 (re-search-forward prohibit end t))
7514 (while (and (< (point) end)
7515 (re-search-forward "^[ \t]+" end t))
7516 (goto-char (match-end 0))
7517 (setq col (current-column))
7518 (if (< diff 0) (replace-match ""))
7519 (org-indent-to-column (+ diff col))))
7520 (move-marker end nil))))
7522 (defun org-convert-to-odd-levels ()
7523 "Convert an org-mode file with all levels allowed to one with odd levels.
7524 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7525 level 5 etc."
7526 (interactive)
7527 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7528 (let ((outline-level 'org-outline-level)
7529 (org-odd-levels-only nil) n)
7530 (save-excursion
7531 (goto-char (point-min))
7532 (while (re-search-forward "^\\*\\*+ " nil t)
7533 (setq n (- (length (match-string 0)) 2))
7534 (while (>= (setq n (1- n)) 0)
7535 (org-demote))
7536 (end-of-line 1))))))
7538 (defun org-convert-to-oddeven-levels ()
7539 "Convert an org-mode file with only odd levels to one with odd/even levels.
7540 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7541 file contains a section with an even level, conversion would
7542 destroy the structure of the file. An error is signaled in this
7543 case."
7544 (interactive)
7545 (goto-char (point-min))
7546 ;; First check if there are no even levels
7547 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7548 (org-show-context t)
7549 (error "Not all levels are odd in this file. Conversion not possible"))
7550 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7551 (let ((outline-regexp org-outline-regexp)
7552 (outline-level 'org-outline-level)
7553 (org-odd-levels-only nil) n)
7554 (save-excursion
7555 (goto-char (point-min))
7556 (while (re-search-forward "^\\*\\*+ " nil t)
7557 (setq n (/ (1- (length (match-string 0))) 2))
7558 (while (>= (setq n (1- n)) 0)
7559 (org-promote))
7560 (end-of-line 1))))))
7562 (defun org-tr-level (n)
7563 "Make N odd if required."
7564 (if org-odd-levels-only (1+ (/ n 2)) n))
7566 ;;; Vertical tree motion, cutting and pasting of subtrees
7568 (defun org-move-subtree-up (&optional arg)
7569 "Move the current subtree up past ARG headlines of the same level."
7570 (interactive "p")
7571 (org-move-subtree-down (- (prefix-numeric-value arg))))
7573 (defun org-move-subtree-down (&optional arg)
7574 "Move the current subtree down past ARG headlines of the same level."
7575 (interactive "p")
7576 (setq arg (prefix-numeric-value arg))
7577 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7578 'org-get-last-sibling))
7579 (ins-point (make-marker))
7580 (cnt (abs arg))
7581 (col (current-column))
7582 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7583 ;; Select the tree
7584 (org-back-to-heading)
7585 (setq beg0 (point))
7586 (save-excursion
7587 (setq ne-beg (org-back-over-empty-lines))
7588 (setq beg (point)))
7589 (save-match-data
7590 (save-excursion (outline-end-of-heading)
7591 (setq folded (outline-invisible-p)))
7592 (outline-end-of-subtree))
7593 (outline-next-heading)
7594 (setq ne-end (org-back-over-empty-lines))
7595 (setq end (point))
7596 (goto-char beg0)
7597 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7598 ;; include less whitespace
7599 (save-excursion
7600 (goto-char beg)
7601 (forward-line (- ne-beg ne-end))
7602 (setq beg (point))))
7603 ;; Find insertion point, with error handling
7604 (while (> cnt 0)
7605 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7606 (progn (goto-char beg0)
7607 (error "Cannot move past superior level or buffer limit")))
7608 (setq cnt (1- cnt)))
7609 (if (> arg 0)
7610 ;; Moving forward - still need to move over subtree
7611 (progn (org-end-of-subtree t t)
7612 (save-excursion
7613 (org-back-over-empty-lines)
7614 (or (bolp) (newline)))))
7615 (setq ne-ins (org-back-over-empty-lines))
7616 (move-marker ins-point (point))
7617 (setq txt (buffer-substring beg end))
7618 (org-save-markers-in-region beg end)
7619 (delete-region beg end)
7620 (org-remove-empty-overlays-at beg)
7621 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7622 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7623 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7624 (let ((bbb (point)))
7625 (insert-before-markers txt)
7626 (org-reinstall-markers-in-region bbb)
7627 (move-marker ins-point bbb))
7628 (or (bolp) (insert "\n"))
7629 (setq ins-end (point))
7630 (goto-char ins-point)
7631 (org-skip-whitespace)
7632 (when (and (< arg 0)
7633 (org-first-sibling-p)
7634 (> ne-ins ne-beg))
7635 ;; Move whitespace back to beginning
7636 (save-excursion
7637 (goto-char ins-end)
7638 (let ((kill-whole-line t))
7639 (kill-line (- ne-ins ne-beg)) (point)))
7640 (insert (make-string (- ne-ins ne-beg) ?\n)))
7641 (move-marker ins-point nil)
7642 (if folded
7643 (hide-subtree)
7644 (org-show-entry)
7645 (show-children)
7646 (org-cycle-hide-drawers 'children))
7647 (org-clean-visibility-after-subtree-move)
7648 ;; move back to the initial column we were at
7649 (move-to-column col)))
7651 (defvar org-subtree-clip ""
7652 "Clipboard for cut and paste of subtrees.
7653 This is actually only a copy of the kill, because we use the normal kill
7654 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7656 (defvar org-subtree-clip-folded nil
7657 "Was the last copied subtree folded?
7658 This is used to fold the tree back after pasting.")
7660 (defun org-cut-subtree (&optional n)
7661 "Cut the current subtree into the clipboard.
7662 With prefix arg N, cut this many sequential subtrees.
7663 This is a short-hand for marking the subtree and then cutting it."
7664 (interactive "p")
7665 (org-copy-subtree n 'cut))
7667 (defun org-copy-subtree (&optional n cut force-store-markers)
7668 "Cut the current subtree into the clipboard.
7669 With prefix arg N, cut this many sequential subtrees.
7670 This is a short-hand for marking the subtree and then copying it.
7671 If CUT is non-nil, actually cut the subtree.
7672 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7673 of some markers in the region, even if CUT is non-nil. This is
7674 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7675 (interactive "p")
7676 (let (beg end folded (beg0 (point)))
7677 (if (org-called-interactively-p 'any)
7678 (org-back-to-heading nil) ; take what looks like a subtree
7679 (org-back-to-heading t)) ; take what is really there
7680 (setq beg (point))
7681 (skip-chars-forward " \t\r\n")
7682 (save-match-data
7683 (save-excursion (outline-end-of-heading)
7684 (setq folded (outline-invisible-p)))
7685 (condition-case nil
7686 (org-forward-heading-same-level (1- n) t)
7687 (error nil))
7688 (org-end-of-subtree t t))
7689 (setq end (point))
7690 (goto-char beg0)
7691 (when (> end beg)
7692 (setq org-subtree-clip-folded folded)
7693 (when (or cut force-store-markers)
7694 (org-save-markers-in-region beg end))
7695 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7696 (setq org-subtree-clip (current-kill 0))
7697 (message "%s: Subtree(s) with %d characters"
7698 (if cut "Cut" "Copied")
7699 (length org-subtree-clip)))))
7701 (defun org-paste-subtree (&optional level tree for-yank)
7702 "Paste the clipboard as a subtree, with modification of headline level.
7703 The entire subtree is promoted or demoted in order to match a new headline
7704 level.
7706 If the cursor is at the beginning of a headline, the same level as
7707 that headline is used to paste the tree
7709 If not, the new level is derived from the *visible* headings
7710 before and after the insertion point, and taken to be the inferior headline
7711 level of the two. So if the previous visible heading is level 3 and the
7712 next is level 4 (or vice versa), level 4 will be used for insertion.
7713 This makes sure that the subtree remains an independent subtree and does
7714 not swallow low level entries.
7716 You can also force a different level, either by using a numeric prefix
7717 argument, or by inserting the heading marker by hand. For example, if the
7718 cursor is after \"*****\", then the tree will be shifted to level 5.
7720 If optional TREE is given, use this text instead of the kill ring.
7722 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7723 move back over whitespace before inserting, and move point to the end of
7724 the inserted text when done."
7725 (interactive "P")
7726 (setq tree (or tree (and kill-ring (current-kill 0))))
7727 (unless (org-kill-is-subtree-p tree)
7728 (error "%s"
7729 (substitute-command-keys
7730 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7731 (org-with-limited-levels
7732 (let* ((visp (not (outline-invisible-p)))
7733 (txt tree)
7734 (^re_ "\\(\\*+\\)[ \t]*")
7735 (old-level (if (string-match org-outline-regexp-bol txt)
7736 (- (match-end 0) (match-beginning 0) 1)
7737 -1))
7738 (force-level (cond (level (prefix-numeric-value level))
7739 ((and (looking-at "[ \t]*$")
7740 (string-match
7741 "^\\*+$" (buffer-substring
7742 (point-at-bol) (point))))
7743 (- (match-end 1) (match-beginning 1)))
7744 ((and (bolp)
7745 (looking-at org-outline-regexp))
7746 (- (match-end 0) (point) 1))))
7747 (previous-level (save-excursion
7748 (condition-case nil
7749 (progn
7750 (outline-previous-visible-heading 1)
7751 (if (looking-at ^re_)
7752 (- (match-end 0) (match-beginning 0) 1)
7754 (error 1))))
7755 (next-level (save-excursion
7756 (condition-case nil
7757 (progn
7758 (or (looking-at org-outline-regexp)
7759 (outline-next-visible-heading 1))
7760 (if (looking-at ^re_)
7761 (- (match-end 0) (match-beginning 0) 1)
7763 (error 1))))
7764 (new-level (or force-level (max previous-level next-level)))
7765 (shift (if (or (= old-level -1)
7766 (= new-level -1)
7767 (= old-level new-level))
7769 (- new-level old-level)))
7770 (delta (if (> shift 0) -1 1))
7771 (func (if (> shift 0) 'org-demote 'org-promote))
7772 (org-odd-levels-only nil)
7773 beg end newend)
7774 ;; Remove the forced level indicator
7775 (if force-level
7776 (delete-region (point-at-bol) (point)))
7777 ;; Paste
7778 (beginning-of-line (if (bolp) 1 2))
7779 (setq beg (point))
7780 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7781 (insert-before-markers txt)
7782 (unless (string-match "\n\\'" txt) (insert "\n"))
7783 (setq newend (point))
7784 (org-reinstall-markers-in-region beg)
7785 (setq end (point))
7786 (goto-char beg)
7787 (skip-chars-forward " \t\n\r")
7788 (setq beg (point))
7789 (if (and (outline-invisible-p) visp)
7790 (save-excursion (outline-show-heading)))
7791 ;; Shift if necessary
7792 (unless (= shift 0)
7793 (save-restriction
7794 (narrow-to-region beg end)
7795 (while (not (= shift 0))
7796 (org-map-region func (point-min) (point-max))
7797 (setq shift (+ delta shift)))
7798 (goto-char (point-min))
7799 (setq newend (point-max))))
7800 (when (or (org-called-interactively-p 'interactive) for-yank)
7801 (message "Clipboard pasted as level %d subtree" new-level))
7802 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7803 kill-ring
7804 (eq org-subtree-clip (current-kill 0))
7805 org-subtree-clip-folded)
7806 ;; The tree was folded before it was killed/copied
7807 (hide-subtree))
7808 (and for-yank (goto-char newend)))))
7810 (defun org-kill-is-subtree-p (&optional txt)
7811 "Check if the current kill is an outline subtree, or a set of trees.
7812 Returns nil if kill does not start with a headline, or if the first
7813 headline level is not the largest headline level in the tree.
7814 So this will actually accept several entries of equal levels as well,
7815 which is OK for `org-paste-subtree'.
7816 If optional TXT is given, check this string instead of the current kill."
7817 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7818 (re (org-get-limited-outline-regexp))
7819 (^re (concat "^" re))
7820 (start-level (and kill
7821 (string-match
7822 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7823 kill)
7824 (- (match-end 2) (match-beginning 2) 1)))
7825 (start (1+ (or (match-beginning 2) -1))))
7826 (if (not start-level)
7827 (progn
7828 nil) ;; does not even start with a heading
7829 (catch 'exit
7830 (while (setq start (string-match ^re kill (1+ start)))
7831 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7832 (throw 'exit nil)))
7833 t))))
7835 (defvar org-markers-to-move nil
7836 "Markers that should be moved with a cut-and-paste operation.
7837 Those markers are stored together with their positions relative to
7838 the start of the region.")
7840 (defun org-save-markers-in-region (beg end)
7841 "Check markers in region.
7842 If these markers are between BEG and END, record their position relative
7843 to BEG, so that after moving the block of text, we can put the markers back
7844 into place.
7845 This function gets called just before an entry or tree gets cut from the
7846 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7847 called immediately, to move the markers with the entries."
7848 (setq org-markers-to-move nil)
7849 (when (featurep 'org-clock)
7850 (org-clock-save-markers-for-cut-and-paste beg end))
7851 (when (featurep 'org-agenda)
7852 (org-agenda-save-markers-for-cut-and-paste beg end)))
7854 (defun org-check-and-save-marker (marker beg end)
7855 "Check if MARKER is between BEG and END.
7856 If yes, remember the marker and the distance to BEG."
7857 (when (and (marker-buffer marker)
7858 (equal (marker-buffer marker) (current-buffer)))
7859 (if (and (>= marker beg) (< marker end))
7860 (push (cons marker (- marker beg)) org-markers-to-move))))
7862 (defun org-reinstall-markers-in-region (beg)
7863 "Move all remembered markers to their position relative to BEG."
7864 (mapc (lambda (x)
7865 (move-marker (car x) (+ beg (cdr x))))
7866 org-markers-to-move)
7867 (setq org-markers-to-move nil))
7869 (defun org-narrow-to-subtree ()
7870 "Narrow buffer to the current subtree."
7871 (interactive)
7872 (save-excursion
7873 (save-match-data
7874 (org-with-limited-levels
7875 (narrow-to-region
7876 (progn (org-back-to-heading t) (point))
7877 (progn (org-end-of-subtree t t)
7878 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7879 (point)))))))
7881 (defun org-narrow-to-block ()
7882 "Narrow buffer to the current block."
7883 (interactive)
7884 (let* ((case-fold-search t)
7885 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7886 "^[ \t]*#\\+end_.*")))
7887 (if blockp
7888 (narrow-to-region (car blockp) (cdr blockp))
7889 (error "Not in a block"))))
7891 (eval-when-compile
7892 (defvar org-property-drawer-re))
7894 (defvar org-property-start-re) ;; defined below
7895 (defun org-clone-subtree-with-time-shift (n &optional shift)
7896 "Clone the task (subtree) at point N times.
7897 The clones will be inserted as siblings.
7899 In interactive use, the user will be prompted for the number of
7900 clones to be produced, and for a time SHIFT, which may be a
7901 repeater as used in time stamps, for example `+3d'.
7903 When a valid repeater is given and the entry contains any time
7904 stamps, the clones will become a sequence in time, with time
7905 stamps in the subtree shifted for each clone produced. If SHIFT
7906 is nil or the empty string, time stamps will be left alone. The
7907 ID property of the original subtree is removed.
7909 If the original subtree did contain time stamps with a repeater,
7910 the following will happen:
7911 - the repeater will be removed in each clone
7912 - an additional clone will be produced, with the current, unshifted
7913 date(s) in the entry.
7914 - the original entry will be placed *after* all the clones, with
7915 repeater intact.
7916 - the start days in the repeater in the original entry will be shifted
7917 to past the last clone.
7918 In this way you can spell out a number of instances of a repeating task,
7919 and still retain the repeater to cover future instances of the task."
7920 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7921 (let (beg end template task idprop
7922 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7923 (drawer-re org-drawer-regexp))
7924 (if (not (and (integerp n) (> n 0)))
7925 (error "Invalid number of replications %s" n))
7926 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7927 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7928 shift)))
7929 (error "Invalid shift specification %s" shift))
7930 (when doshift
7931 (setq shift-n (string-to-number (match-string 1 shift))
7932 shift-what (cdr (assoc (match-string 2 shift)
7933 '(("d" . day) ("w" . week)
7934 ("m" . month) ("y" . year))))))
7935 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7936 (setq nmin 1 nmax n)
7937 (org-back-to-heading t)
7938 (setq beg (point))
7939 (setq idprop (org-entry-get nil "ID"))
7940 (org-end-of-subtree t t)
7941 (or (bolp) (insert "\n"))
7942 (setq end (point))
7943 (setq template (buffer-substring beg end))
7944 (when (and doshift
7945 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7946 (delete-region beg end)
7947 (setq end beg)
7948 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7949 (goto-char end)
7950 (loop for n from nmin to nmax do
7951 ;; prepare clone
7952 (with-temp-buffer
7953 (insert template)
7954 (org-mode)
7955 (goto-char (point-min))
7956 (org-show-subtree)
7957 (and idprop (if org-clone-delete-id
7958 (org-entry-delete nil "ID")
7959 (org-id-get-create t)))
7960 (unless (= n 0)
7961 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
7962 (kill-whole-line))
7963 (goto-char (point-min))
7964 (while (re-search-forward drawer-re nil t)
7965 (mapc (lambda (d)
7966 (org-remove-empty-drawer-at d (point))) org-drawers)))
7967 (goto-char (point-min))
7968 (when doshift
7969 (while (re-search-forward org-ts-regexp-both nil t)
7970 (org-timestamp-change (* n shift-n) shift-what))
7971 (unless (= n n-no-remove)
7972 (goto-char (point-min))
7973 (while (re-search-forward org-ts-regexp nil t)
7974 (save-excursion
7975 (goto-char (match-beginning 0))
7976 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
7977 (delete-region (match-beginning 1) (match-end 1)))))))
7978 (setq task (buffer-string)))
7979 (insert task))
7980 (goto-char beg)))
7982 ;;; Outline Sorting
7984 (defun org-sort (with-case)
7985 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7986 Optional argument WITH-CASE means sort case-sensitively."
7987 (interactive "P")
7988 (cond
7989 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7990 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7992 (org-call-with-arg 'org-sort-entries with-case))))
7994 (defun org-sort-remove-invisible (s)
7995 (remove-text-properties 0 (length s) org-rm-props s)
7996 (while (string-match org-bracket-link-regexp s)
7997 (setq s (replace-match (if (match-end 2)
7998 (match-string 3 s)
7999 (match-string 1 s)) t t s)))
8002 (defvar org-priority-regexp) ; defined later in the file
8004 (defvar org-after-sorting-entries-or-items-hook nil
8005 "Hook that is run after a bunch of entries or items have been sorted.
8006 When children are sorted, the cursor is in the parent line when this
8007 hook gets called. When a region or a plain list is sorted, the cursor
8008 will be in the first entry of the sorted region/list.")
8010 (defun org-sort-entries
8011 (&optional with-case sorting-type getkey-func compare-func property)
8012 "Sort entries on a certain level of an outline tree.
8013 If there is an active region, the entries in the region are sorted.
8014 Else, if the cursor is before the first entry, sort the top-level items.
8015 Else, the children of the entry at point are sorted.
8017 Sorting can be alphabetically, numerically, by date/time as given by
8018 a time stamp, by a property or by priority.
8020 The command prompts for the sorting type unless it has been given to the
8021 function through the SORTING-TYPE argument, which needs to be a character,
8022 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8023 precise meaning of each character:
8025 n Numerically, by converting the beginning of the entry/item to a number.
8026 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8027 o By order of TODO keywords.
8028 t By date/time, either the first active time stamp in the entry, or, if
8029 none exist, by the first inactive one.
8030 s By the scheduled date/time.
8031 d By deadline date/time.
8032 c By creation time, which is assumed to be the first inactive time stamp
8033 at the beginning of a line.
8034 p By priority according to the cookie.
8035 r By the value of a property.
8037 Capital letters will reverse the sort order.
8039 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8040 called with point at the beginning of the record. It must return either
8041 a string or a number that should serve as the sorting key for that record.
8043 Comparing entries ignores case by default. However, with an optional argument
8044 WITH-CASE, the sorting considers case as well."
8045 (interactive "P")
8046 (let ((case-func (if with-case 'identity 'downcase))
8047 (cmstr
8048 ;; The clock marker is lost when using `sort-subr', let's
8049 ;; store the clocking string.
8050 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8051 (save-excursion
8052 (goto-char org-clock-marker)
8053 (looking-back "^.*") (match-string-no-properties 0))))
8054 start beg end stars re re2
8055 txt what tmp)
8056 ;; Find beginning and end of region to sort
8057 (cond
8058 ((org-region-active-p)
8059 ;; we will sort the region
8060 (setq end (region-end)
8061 what "region")
8062 (goto-char (region-beginning))
8063 (if (not (org-at-heading-p)) (outline-next-heading))
8064 (setq start (point)))
8065 ((or (org-at-heading-p)
8066 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8067 ;; we will sort the children of the current headline
8068 (org-back-to-heading)
8069 (setq start (point)
8070 end (progn (org-end-of-subtree t t)
8071 (or (bolp) (insert "\n"))
8072 (org-back-over-empty-lines)
8073 (point))
8074 what "children")
8075 (goto-char start)
8076 (show-subtree)
8077 (outline-next-heading))
8079 ;; we will sort the top-level entries in this file
8080 (goto-char (point-min))
8081 (or (org-at-heading-p) (outline-next-heading))
8082 (setq start (point))
8083 (goto-char (point-max))
8084 (beginning-of-line 1)
8085 (when (looking-at ".*?\\S-")
8086 ;; File ends in a non-white line
8087 (end-of-line 1)
8088 (insert "\n"))
8089 (setq end (point-max))
8090 (setq what "top-level")
8091 (goto-char start)
8092 (show-all)))
8094 (setq beg (point))
8095 (if (>= beg end) (error "Nothing to sort"))
8097 (looking-at "\\(\\*+\\)")
8098 (setq stars (match-string 1)
8099 re (concat "^" (regexp-quote stars) " +")
8100 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8101 txt (buffer-substring beg end))
8102 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8103 (if (and (not (equal stars "*")) (string-match re2 txt))
8104 (error "Region to sort contains a level above the first entry"))
8106 (unless sorting-type
8107 (message
8108 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8109 [t]ime [s]cheduled [d]eadline [c]reated
8110 A/N/P/R/O/F/T/S/D/C means reversed:"
8111 what)
8112 (setq sorting-type (read-char-exclusive))
8114 (and (= (downcase sorting-type) ?f)
8115 (setq getkey-func
8116 (org-icompleting-read "Sort using function: "
8117 obarray 'fboundp t nil nil))
8118 (setq getkey-func (intern getkey-func)))
8120 (and (= (downcase sorting-type) ?r)
8121 (setq property
8122 (org-icompleting-read "Property: "
8123 (mapcar 'list (org-buffer-property-keys t))
8124 nil t))))
8126 (message "Sorting entries...")
8128 (save-restriction
8129 (narrow-to-region start end)
8130 (let ((dcst (downcase sorting-type))
8131 (case-fold-search nil)
8132 (now (current-time)))
8133 (sort-subr
8134 (/= dcst sorting-type)
8135 ;; This function moves to the beginning character of the "record" to
8136 ;; be sorted.
8137 (lambda nil
8138 (if (re-search-forward re nil t)
8139 (goto-char (match-beginning 0))
8140 (goto-char (point-max))))
8141 ;; This function moves to the last character of the "record" being
8142 ;; sorted.
8143 (lambda nil
8144 (save-match-data
8145 (condition-case nil
8146 (outline-forward-same-level 1)
8147 (error
8148 (goto-char (point-max))))))
8149 ;; This function returns the value that gets sorted against.
8150 (lambda nil
8151 (cond
8152 ((= dcst ?n)
8153 (if (looking-at org-complex-heading-regexp)
8154 (string-to-number (match-string 4))
8155 nil))
8156 ((= dcst ?a)
8157 (if (looking-at org-complex-heading-regexp)
8158 (funcall case-func (match-string 4))
8159 nil))
8160 ((= dcst ?t)
8161 (let ((end (save-excursion (outline-next-heading) (point))))
8162 (if (or (re-search-forward org-ts-regexp end t)
8163 (re-search-forward org-ts-regexp-both end t))
8164 (org-time-string-to-seconds (match-string 0))
8165 (org-float-time now))))
8166 ((= dcst ?c)
8167 (let ((end (save-excursion (outline-next-heading) (point))))
8168 (if (re-search-forward
8169 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8170 end t)
8171 (org-time-string-to-seconds (match-string 0))
8172 (org-float-time now))))
8173 ((= dcst ?s)
8174 (let ((end (save-excursion (outline-next-heading) (point))))
8175 (if (re-search-forward org-scheduled-time-regexp end t)
8176 (org-time-string-to-seconds (match-string 1))
8177 (org-float-time now))))
8178 ((= dcst ?d)
8179 (let ((end (save-excursion (outline-next-heading) (point))))
8180 (if (re-search-forward org-deadline-time-regexp end t)
8181 (org-time-string-to-seconds (match-string 1))
8182 (org-float-time now))))
8183 ((= dcst ?p)
8184 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8185 (string-to-char (match-string 2))
8186 org-default-priority))
8187 ((= dcst ?r)
8188 (or (org-entry-get nil property) ""))
8189 ((= dcst ?o)
8190 (if (looking-at org-complex-heading-regexp)
8191 (- 9999 (length (member (match-string 2)
8192 org-todo-keywords-1)))))
8193 ((= dcst ?f)
8194 (if getkey-func
8195 (progn
8196 (setq tmp (funcall getkey-func))
8197 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8198 tmp)
8199 (error "Invalid key function `%s'" getkey-func)))
8200 (t (error "Invalid sorting type `%c'" sorting-type))))
8202 (cond
8203 ((= dcst ?a) 'string<)
8204 ((= dcst ?f) compare-func)
8205 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8206 (run-hooks 'org-after-sorting-entries-or-items-hook)
8207 ;; Reset the clock marker if needed
8208 (when cmstr
8209 (save-excursion
8210 (goto-char start)
8211 (search-forward cmstr nil t)
8212 (move-marker org-clock-marker (point))))
8213 (message "Sorting entries...done")))
8215 (defun org-do-sort (table what &optional with-case sorting-type)
8216 "Sort TABLE of WHAT according to SORTING-TYPE.
8217 The user will be prompted for the SORTING-TYPE if the call to this
8218 function does not specify it. WHAT is only for the prompt, to indicate
8219 what is being sorted. The sorting key will be extracted from
8220 the car of the elements of the table.
8221 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8222 (unless sorting-type
8223 (message
8224 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8225 what)
8226 (setq sorting-type (read-char-exclusive)))
8227 (let ((dcst (downcase sorting-type))
8228 extractfun comparefun)
8229 ;; Define the appropriate functions
8230 (cond
8231 ((= dcst ?n)
8232 (setq extractfun 'string-to-number
8233 comparefun (if (= dcst sorting-type) '< '>)))
8234 ((= dcst ?a)
8235 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8236 (lambda(x) (downcase (org-sort-remove-invisible x))))
8237 comparefun (if (= dcst sorting-type)
8238 'string<
8239 (lambda (a b) (and (not (string< a b))
8240 (not (string= a b)))))))
8241 ((= dcst ?t)
8242 (setq extractfun
8243 (lambda (x)
8244 (if (or (string-match org-ts-regexp x)
8245 (string-match org-ts-regexp-both x))
8246 (org-float-time
8247 (org-time-string-to-time (match-string 0 x)))
8249 comparefun (if (= dcst sorting-type) '< '>)))
8250 (t (error "Invalid sorting type `%c'" sorting-type)))
8252 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8253 table)
8254 (lambda (a b) (funcall comparefun (car a) (car b))))))
8257 ;;; The orgstruct minor mode
8259 ;; Define a minor mode which can be used in other modes in order to
8260 ;; integrate the org-mode structure editing commands.
8262 ;; This is really a hack, because the org-mode structure commands use
8263 ;; keys which normally belong to the major mode. Here is how it
8264 ;; works: The minor mode defines all the keys necessary to operate the
8265 ;; structure commands, but wraps the commands into a function which
8266 ;; tests if the cursor is currently at a headline or a plain list
8267 ;; item. If that is the case, the structure command is used,
8268 ;; temporarily setting many Org-mode variables like regular
8269 ;; expressions for filling etc. However, when any of those keys is
8270 ;; used at a different location, function uses `key-binding' to look
8271 ;; up if the key has an associated command in another currently active
8272 ;; keymap (minor modes, major mode, global), and executes that
8273 ;; command. There might be problems if any of the keys is otherwise
8274 ;; used as a prefix key.
8276 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8277 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8278 ;; addresses this by checking explicitly for both bindings.
8280 (defvar orgstruct-mode-map (make-sparse-keymap)
8281 "Keymap for the minor `orgstruct-mode'.")
8283 (defvar org-local-vars nil
8284 "List of local variables, for use by `orgstruct-mode'.")
8286 ;;;###autoload
8287 (define-minor-mode orgstruct-mode
8288 "Toggle the minor mode `orgstruct-mode'.
8289 This mode is for using Org-mode structure commands in other
8290 modes. The following keys behave as if Org-mode were active, if
8291 the cursor is on a headline, or on a plain list item (both as
8292 defined by Org-mode).
8294 M-up Move entry/item up
8295 M-down Move entry/item down
8296 M-left Promote
8297 M-right Demote
8298 M-S-up Move entry/item up
8299 M-S-down Move entry/item down
8300 M-S-left Promote subtree
8301 M-S-right Demote subtree
8302 M-q Fill paragraph and items like in Org-mode
8303 C-c ^ Sort entries
8304 C-c - Cycle list bullet
8305 TAB Cycle item visibility
8306 M-RET Insert new heading/item
8307 S-M-RET Insert new TODO heading / Checkbox item
8308 C-c C-c Set tags / toggle checkbox"
8309 nil " OrgStruct" nil
8310 (org-load-modules-maybe)
8311 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8313 ;;;###autoload
8314 (defun turn-on-orgstruct ()
8315 "Unconditionally turn on `orgstruct-mode'."
8316 (orgstruct-mode 1))
8318 (defvar org-fb-vars nil)
8319 (make-variable-buffer-local 'org-fb-vars)
8320 (defun orgstruct++-mode (&optional arg)
8321 "Toggle `orgstruct-mode', the enhanced version of it.
8322 In addition to setting orgstruct-mode, this also exports all
8323 indentation and autofilling variables from org-mode into the
8324 buffer. It will also recognize item context in multiline items."
8325 (interactive "P")
8326 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8327 (if (< arg 1)
8328 (progn (orgstruct-mode -1)
8329 (mapc (lambda(v)
8330 (org-set-local (car v)
8331 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8332 org-fb-vars))
8333 (orgstruct-mode 1)
8334 (setq org-fb-vars nil)
8335 (let (var val)
8336 (mapc
8337 (lambda (x)
8338 (when (string-match
8339 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8340 (symbol-name (car x)))
8341 (setq var (car x) val (nth 1 x))
8342 (push (list var `(quote ,(eval var))) org-fb-vars)
8343 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8344 org-local-vars)
8345 (org-set-local 'orgstruct-is-++ t))))
8347 (defvar orgstruct-is-++ nil
8348 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8349 (make-variable-buffer-local 'orgstruct-is-++)
8351 ;;;###autoload
8352 (defun turn-on-orgstruct++ ()
8353 "Unconditionally turn on `orgstruct++-mode'."
8354 (orgstruct++-mode 1))
8356 (defun orgstruct-error ()
8357 "Error when there is no default binding for a structure key."
8358 (interactive)
8359 (error "This key has no function outside structure elements"))
8361 (defun orgstruct-setup ()
8362 "Setup orgstruct keymaps."
8363 (let ((nfunc 0)
8364 (bindings
8365 (list
8366 '([(meta up)] org-metaup)
8367 '([(meta down)] org-metadown)
8368 '([(meta left)] org-metaleft)
8369 '([(meta right)] org-metaright)
8370 '([(meta shift up)] org-shiftmetaup)
8371 '([(meta shift down)] org-shiftmetadown)
8372 '([(meta shift left)] org-shiftmetaleft)
8373 '([(meta shift right)] org-shiftmetaright)
8374 '([?\e (up)] org-metaup)
8375 '([?\e (down)] org-metadown)
8376 '([?\e (left)] org-metaleft)
8377 '([?\e (right)] org-metaright)
8378 '([?\e (shift up)] org-shiftmetaup)
8379 '([?\e (shift down)] org-shiftmetadown)
8380 '([?\e (shift left)] org-shiftmetaleft)
8381 '([?\e (shift right)] org-shiftmetaright)
8382 '([(shift up)] org-shiftup)
8383 '([(shift down)] org-shiftdown)
8384 '([(shift left)] org-shiftleft)
8385 '([(shift right)] org-shiftright)
8386 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8387 '("\M-q" fill-paragraph)
8388 '("\C-c^" org-sort)
8389 '("\C-c-" org-cycle-list-bullet)))
8390 elt key fun cmd)
8391 (while (setq elt (pop bindings))
8392 (setq nfunc (1+ nfunc))
8393 (setq key (org-key (car elt))
8394 fun (nth 1 elt)
8395 cmd (orgstruct-make-binding fun nfunc key))
8396 (org-defkey orgstruct-mode-map key cmd))
8398 ;; Prevent an error for users who forgot to make autoloads
8399 (require 'org-element)
8401 ;; Special treatment needed for TAB and RET
8402 (org-defkey orgstruct-mode-map [(tab)]
8403 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8404 (org-defkey orgstruct-mode-map "\C-i"
8405 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8407 (org-defkey orgstruct-mode-map "\M-\C-m"
8408 (orgstruct-make-binding 'org-insert-heading 105
8409 "\M-\C-m" [(meta return)]))
8410 (org-defkey orgstruct-mode-map [(meta return)]
8411 (orgstruct-make-binding 'org-insert-heading 106
8412 [(meta return)] "\M-\C-m"))
8414 (org-defkey orgstruct-mode-map [(shift meta return)]
8415 (orgstruct-make-binding 'org-insert-todo-heading 107
8416 [(meta return)] "\M-\C-m"))
8418 (org-defkey orgstruct-mode-map "\e\C-m"
8419 (orgstruct-make-binding 'org-insert-heading 108
8420 "\e\C-m" [?\e (return)]))
8421 (org-defkey orgstruct-mode-map [?\e (return)]
8422 (orgstruct-make-binding 'org-insert-heading 109
8423 [?\e (return)] "\e\C-m"))
8424 (org-defkey orgstruct-mode-map [?\e (shift return)]
8425 (orgstruct-make-binding 'org-insert-todo-heading 110
8426 [?\e (return)] "\e\C-m"))
8428 (unless org-local-vars
8429 (setq org-local-vars (org-get-local-variables)))
8433 (defun orgstruct-make-binding (fun n &rest keys)
8434 "Create a function for binding in the structure minor mode.
8435 FUN is the command to call inside a table. N is used to create a unique
8436 command name. KEYS are keys that should be checked in for a command
8437 to execute outside of tables."
8438 (eval
8439 (list 'defun
8440 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8441 '(arg)
8442 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8443 "Outside of structure, run the binding of `"
8444 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8445 "'.")
8446 '(interactive "p")
8447 (list 'if
8448 `(org-context-p 'headline 'item
8449 (and orgstruct-is-++
8450 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8451 'item-body))
8452 (list 'org-run-like-in-org-mode (list 'quote fun))
8453 (list 'let '(orgstruct-mode)
8454 (list 'call-interactively
8455 (append '(or)
8456 (mapcar (lambda (k)
8457 (list 'key-binding k))
8458 keys)
8459 '('orgstruct-error))))))))
8461 (defun org-contextualize-keys (alist contexts)
8462 "Return valid elements in ALIST depending on CONTEXTS.
8464 `org-agenda-custom-commands' or `org-capture-templates' are the
8465 values used for ALIST, and `org-agenda-custom-commands-contexts'
8466 or `org-capture-templates-contexts' are the associated contexts
8467 definitions."
8468 (let ((contexts
8469 ;; normalize contexts
8470 (mapcar
8471 (lambda(c) (cond ((listp (cadr c))
8472 (list (car c) (car c) (cadr c)))
8473 ((string= "" (cadr c))
8474 (list (car c) (car c) (caddr c)))
8475 (t c))) contexts))
8476 (a alist) c r s)
8477 ;; loop over all commands or templates
8478 (while (setq c (pop a))
8479 (let (vrules repl)
8480 (cond
8481 ((not (assoc (car c) contexts))
8482 (push c r))
8483 ((and (assoc (car c) contexts)
8484 (setq vrules (org-contextualize-validate-key
8485 (car c) contexts)))
8486 (mapc (lambda (vr)
8487 (when (not (equal (car vr) (cadr vr)))
8488 (setq repl vr))) vrules)
8489 (if (not repl) (push c r)
8490 (push (cadr repl) s)
8491 (push
8492 (cons (car c)
8493 (cdr (or (assoc (cadr repl) alist)
8494 (error "Undefined key `%s' as contextual replacement for `%s'"
8495 (cadr repl) (car c)))))
8496 r))))))
8497 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8498 (delq
8500 (delete-dups
8501 (mapcar (lambda (x)
8502 (let ((tpl (car x)))
8503 (when (not (delq
8505 (mapcar (lambda(y)
8506 (equal y tpl)) s))) x)))
8507 (reverse r))))))
8509 (defun org-contextualize-validate-key (key contexts)
8510 "Check CONTEXTS for agenda or capture KEY."
8511 (let (r rr res)
8512 (while (setq r (pop contexts))
8513 (mapc
8514 (lambda (rr)
8515 (when
8516 (and (equal key (car r))
8517 (if (functionp rr) (funcall rr)
8518 (or (and (eq (car rr) 'in-file)
8519 (buffer-file-name)
8520 (string-match (cdr rr) (buffer-file-name)))
8521 (and (eq (car rr) 'in-mode)
8522 (string-match (cdr rr) (symbol-name major-mode)))
8523 (when (and (eq (car rr) 'not-in-file)
8524 (buffer-file-name))
8525 (not (string-match (cdr rr) (buffer-file-name))))
8526 (when (eq (car rr) 'not-in-mode)
8527 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8528 (push r res)))
8529 (car (last r))))
8530 (delete-dups (delq nil res))))
8532 (defun org-context-p (&rest contexts)
8533 "Check if local context is any of CONTEXTS.
8534 Possible values in the list of contexts are `table', `headline', and `item'."
8535 (let ((pos (point)))
8536 (goto-char (point-at-bol))
8537 (prog1 (or (and (memq 'table contexts)
8538 (looking-at "[ \t]*|"))
8539 (and (memq 'headline contexts)
8540 (looking-at org-outline-regexp))
8541 (and (memq 'item contexts)
8542 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8543 (and (memq 'item-body contexts)
8544 (org-in-item-p)))
8545 (goto-char pos))))
8547 (defun org-get-local-variables ()
8548 "Return a list of all local variables in an Org mode buffer."
8549 (let (varlist)
8550 (with-current-buffer (get-buffer-create "*Org tmp*")
8551 (erase-buffer)
8552 (org-mode)
8553 (setq varlist (buffer-local-variables)))
8554 (kill-buffer "*Org tmp*")
8555 (delq nil
8556 (mapcar
8557 (lambda (x)
8558 (setq x
8559 (if (symbolp x)
8560 (list x)
8561 (list (car x) (list 'quote (cdr x)))))
8562 (if (string-match
8563 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8564 (symbol-name (car x)))
8565 x nil))
8566 varlist))))
8568 (defun org-clone-local-variables (from-buffer &optional regexp)
8569 "Clone local variables from FROM-BUFFER.
8570 Optional argument REGEXP selects variables to clone."
8571 (mapc
8572 (lambda (pair)
8573 (and (symbolp (car pair))
8574 (or (null regexp)
8575 (string-match regexp (symbol-name (car pair))))
8576 (set (make-local-variable (car pair))
8577 (cdr pair))))
8578 (buffer-local-variables from-buffer)))
8580 ;;;###autoload
8581 (defun org-run-like-in-org-mode (cmd)
8582 "Run a command, pretending that the current buffer is in Org-mode.
8583 This will temporarily bind local variables that are typically bound in
8584 Org-mode to the values they have in Org-mode, and then interactively
8585 call CMD."
8586 (org-load-modules-maybe)
8587 (unless org-local-vars
8588 (setq org-local-vars (org-get-local-variables)))
8589 (eval (list 'let org-local-vars
8590 (list 'call-interactively (list 'quote cmd)))))
8592 ;;;; Archiving
8594 (defun org-get-category (&optional pos force-refresh)
8595 "Get the category applying to position POS."
8596 (save-match-data
8597 (if force-refresh (org-refresh-category-properties))
8598 (let ((pos (or pos (point))))
8599 (or (get-text-property pos 'org-category)
8600 (progn (org-refresh-category-properties)
8601 (get-text-property pos 'org-category))))))
8603 (defun org-refresh-category-properties ()
8604 "Refresh category text properties in the buffer."
8605 (let ((case-fold-search t)
8606 (inhibit-read-only t)
8607 (def-cat (cond
8608 ((null org-category)
8609 (if buffer-file-name
8610 (file-name-sans-extension
8611 (file-name-nondirectory buffer-file-name))
8612 "???"))
8613 ((symbolp org-category) (symbol-name org-category))
8614 (t org-category)))
8615 beg end cat pos optionp)
8616 (org-unmodified
8617 (save-excursion
8618 (save-restriction
8619 (widen)
8620 (goto-char (point-min))
8621 (put-text-property (point) (point-max) 'org-category def-cat)
8622 (while (re-search-forward
8623 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8624 (setq pos (match-end 0)
8625 optionp (equal (char-after (match-beginning 0)) ?#)
8626 cat (org-trim (match-string 2)))
8627 (if optionp
8628 (setq beg (point-at-bol) end (point-max))
8629 (org-back-to-heading t)
8630 (setq beg (point) end (org-end-of-subtree t t)))
8631 (put-text-property beg end 'org-category cat)
8632 (put-text-property beg end 'org-category-position beg)
8633 (goto-char pos)))))))
8636 ;;;; Link Stuff
8638 ;;; Link abbreviations
8640 (defun org-link-expand-abbrev (link)
8641 "Apply replacements as defined in `org-link-abbrev-alist'."
8642 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8643 (let* ((key (match-string 1 link))
8644 (as (or (assoc key org-link-abbrev-alist-local)
8645 (assoc key org-link-abbrev-alist)))
8646 (tag (and (match-end 2) (match-string 3 link)))
8647 rpl)
8648 (if (not as)
8649 link
8650 (setq rpl (cdr as))
8651 (cond
8652 ((symbolp rpl) (funcall rpl tag))
8653 ((string-match "%(\\([^)]+\\))" rpl)
8654 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8655 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8656 ((string-match "%h" rpl)
8657 (replace-match (url-hexify-string (or tag "")) t t rpl))
8658 (t (concat rpl tag)))))
8659 link))
8661 ;;; Storing and inserting links
8663 (defvar org-insert-link-history nil
8664 "Minibuffer history for links inserted with `org-insert-link'.")
8666 (defvar org-stored-links nil
8667 "Contains the links stored with `org-store-link'.")
8669 (defvar org-store-link-plist nil
8670 "Plist with info about the most recently link created with `org-store-link'.")
8672 (defvar org-link-protocols nil
8673 "Link protocols added to Org-mode using `org-add-link-type'.")
8675 (defvar org-store-link-functions nil
8676 "List of functions that are called to create and store a link.
8677 Each function will be called in turn until one returns a non-nil
8678 value. Each function should check if it is responsible for creating
8679 this link (for example by looking at the major mode).
8680 If not, it must exit and return nil.
8681 If yes, it should return a non-nil value after a calling
8682 `org-store-link-props' with a list of properties and values.
8683 Special properties are:
8685 :type The link prefix, like \"http\". This must be given.
8686 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8687 This is obligatory as well.
8688 :description Optional default description for the second pair
8689 of brackets in an Org-mode link. The user can still change
8690 this when inserting this link into an Org-mode buffer.
8692 In addition to these, any additional properties can be specified
8693 and then used in capture templates.")
8695 (defun org-add-link-type (type &optional follow export)
8696 "Add TYPE to the list of `org-link-types'.
8697 Re-compute all regular expressions depending on `org-link-types'
8699 FOLLOW and EXPORT are two functions.
8701 FOLLOW should take the link path as the single argument and do whatever
8702 is necessary to follow the link, for example find a file or display
8703 a mail message.
8705 EXPORT should format the link path for export to one of the export formats.
8706 It should be a function accepting three arguments:
8708 path the path of the link, the text after the prefix (like \"http:\")
8709 desc the description of the link, if any, or a description added by
8710 org-export-normalize-links if there is none
8711 format the export format, a symbol like `html' or `latex' or `ascii'..
8713 The function may use the FORMAT information to return different values
8714 depending on the format. The return value will be put literally into
8715 the exported file. If the return value is nil, this means Org should
8716 do what it normally does with links which do not have EXPORT defined.
8718 Org-mode has a built-in default for exporting links. If you are happy with
8719 this default, there is no need to define an export function for the link
8720 type. For a simple example of an export function, see `org-bbdb.el'."
8721 (add-to-list 'org-link-types type t)
8722 (org-make-link-regexps)
8723 (if (assoc type org-link-protocols)
8724 (setcdr (assoc type org-link-protocols) (list follow export))
8725 (push (list type follow export) org-link-protocols)))
8727 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8728 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8730 ;;;###autoload
8731 (defun org-store-link (arg)
8732 "\\<org-mode-map>Store an org-link to the current location.
8733 This link is added to `org-stored-links' and can later be inserted
8734 into an org-buffer with \\[org-insert-link].
8736 For some link types, a prefix arg is interpreted:
8737 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8738 For file links, arg negates `org-context-in-file-links'."
8739 (interactive "P")
8740 (org-load-modules-maybe)
8741 (setq org-store-link-plist nil) ; reset
8742 (org-with-limited-levels
8743 (let (link cpltxt desc description search txt custom-id agenda-link)
8744 (cond
8746 ((run-hook-with-args-until-success 'org-store-link-functions)
8747 (setq link (plist-get org-store-link-plist :link)
8748 desc (or (plist-get org-store-link-plist :description) link)))
8750 ((org-src-edit-buffer-p)
8751 (let (label gc)
8752 (while (or (not label)
8753 (save-excursion
8754 (save-restriction
8755 (widen)
8756 (goto-char (point-min))
8757 (re-search-forward
8758 (regexp-quote (format org-coderef-label-format label))
8759 nil t))))
8760 (when label (message "Label exists already") (sit-for 2))
8761 (setq label (read-string "Code line label: " label)))
8762 (end-of-line 1)
8763 (setq link (format org-coderef-label-format label))
8764 (setq gc (- 79 (length link)))
8765 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8766 (insert link)
8767 (setq link (concat "(" label ")") desc nil)))
8769 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8770 ;; We are in the agenda, link to referenced location
8771 (let ((m (or (get-text-property (point) 'org-hd-marker)
8772 (get-text-property (point) 'org-marker))))
8773 (when m
8774 (org-with-point-at m
8775 (setq agenda-link
8776 (if (org-called-interactively-p 'any)
8777 (call-interactively 'org-store-link)
8778 (org-store-link nil)))))))
8780 ((eq major-mode 'calendar-mode)
8781 (let ((cd (calendar-cursor-to-date)))
8782 (setq link
8783 (format-time-string
8784 (car org-time-stamp-formats)
8785 (apply 'encode-time
8786 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8787 nil nil nil))))
8788 (org-store-link-props :type "calendar" :date cd)))
8790 ((eq major-mode 'help-mode)
8791 (setq link (concat "help:" (save-excursion
8792 (goto-char (point-min))
8793 (looking-at "^[^ ]+")
8794 (match-string 0))))
8795 (org-store-link-props :type "help"))
8797 ((eq major-mode 'w3-mode)
8798 (setq cpltxt (if (and (buffer-name)
8799 (not (string-match "Untitled" (buffer-name))))
8800 (buffer-name)
8801 (url-view-url t))
8802 link (url-view-url t))
8803 (org-store-link-props :type "w3" :url (url-view-url t)))
8805 ((eq major-mode 'w3m-mode)
8806 (setq cpltxt (or w3m-current-title w3m-current-url)
8807 link w3m-current-url)
8808 (org-store-link-props :type "w3m" :url (url-view-url t)))
8810 ((setq search (run-hook-with-args-until-success
8811 'org-create-file-search-functions))
8812 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8813 "::" search))
8814 (setq cpltxt (or description link)))
8816 ((eq major-mode 'image-mode)
8817 (setq cpltxt (concat "file:"
8818 (abbreviate-file-name buffer-file-name))
8819 link cpltxt)
8820 (org-store-link-props :type "image" :file buffer-file-name))
8822 ((eq major-mode 'dired-mode)
8823 ;; link to the file in the current line
8824 (let ((file (dired-get-filename nil t)))
8825 (setq file (if file
8826 (abbreviate-file-name
8827 (expand-file-name (dired-get-filename nil t)))
8828 ;; otherwise, no file so use current directory.
8829 default-directory))
8830 (setq cpltxt (concat "file:" file)
8831 link cpltxt)))
8833 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8834 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8835 (cond
8836 ((org-in-regexp "<<\\(.*?\\)>>")
8837 (setq cpltxt
8838 (concat "file:"
8839 (abbreviate-file-name
8840 (buffer-file-name (buffer-base-buffer)))
8841 "::" (match-string 1))
8842 link cpltxt))
8843 ((and (featurep 'org-id)
8844 (or (eq org-link-to-org-use-id t)
8845 (and (org-called-interactively-p 'any)
8846 (or (eq org-link-to-org-use-id 'create-if-interactive)
8847 (and (eq org-link-to-org-use-id
8848 'create-if-interactive-and-no-custom-id)
8849 (not custom-id))))
8850 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8851 ;; We can make a link using the ID.
8852 (setq link (condition-case nil
8853 (prog1 (org-id-store-link)
8854 (setq desc (plist-get org-store-link-plist :description)))
8855 (error
8856 ;; probably before first headline, link to file only
8857 (concat "file:"
8858 (abbreviate-file-name
8859 (buffer-file-name (buffer-base-buffer))))))))
8861 ;; Just link to current headline
8862 (setq cpltxt (concat "file:"
8863 (abbreviate-file-name
8864 (buffer-file-name (buffer-base-buffer)))))
8865 ;; Add a context search string
8866 (when (org-xor org-context-in-file-links arg)
8867 (setq txt (cond
8868 ((org-at-heading-p) nil)
8869 ((org-region-active-p)
8870 (buffer-substring (region-beginning) (region-end)))))
8871 (when (or (null txt) (string-match "\\S-" txt))
8872 (setq cpltxt
8873 (concat cpltxt "::"
8874 (condition-case nil
8875 (org-make-org-heading-search-string txt)
8876 (error "")))
8877 desc (or (nth 4 (ignore-errors
8878 (org-heading-components))) "NONE"))))
8879 (if (string-match "::\\'" cpltxt)
8880 (setq cpltxt (substring cpltxt 0 -2)))
8881 (setq link cpltxt))))
8883 ((buffer-file-name (buffer-base-buffer))
8884 ;; Just link to this file here.
8885 (setq cpltxt (concat "file:"
8886 (abbreviate-file-name
8887 (buffer-file-name (buffer-base-buffer)))))
8888 ;; Add a context string
8889 (when (org-xor org-context-in-file-links arg)
8890 (setq txt (if (org-region-active-p)
8891 (buffer-substring (region-beginning) (region-end))
8892 (buffer-substring (point-at-bol) (point-at-eol))))
8893 ;; Only use search option if there is some text.
8894 (when (string-match "\\S-" txt)
8895 (setq cpltxt
8896 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8897 desc "NONE")))
8898 (setq link cpltxt))
8900 ((org-called-interactively-p 'interactive)
8901 (error "Cannot link to a buffer which is not visiting a file"))
8903 (t (setq link nil)))
8905 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8906 (setq link (or link cpltxt)
8907 desc (or desc cpltxt))
8908 (if (equal desc "NONE") (setq desc nil))
8910 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8911 (progn
8912 (setq org-stored-links
8913 (cons (list link desc) org-stored-links))
8914 (message "Stored: %s" (or desc link))
8915 (when custom-id
8916 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8917 "::#" custom-id))
8918 (setq org-stored-links
8919 (cons (list link desc) org-stored-links))))
8920 (or agenda-link (and link (org-make-link-string link desc)))))))
8922 (defun org-store-link-props (&rest plist)
8923 "Store link properties, extract names and addresses."
8924 (let (x adr)
8925 (when (setq x (plist-get plist :from))
8926 (setq adr (mail-extract-address-components x))
8927 (setq plist (plist-put plist :fromname (car adr)))
8928 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8929 (when (setq x (plist-get plist :to))
8930 (setq adr (mail-extract-address-components x))
8931 (setq plist (plist-put plist :toname (car adr)))
8932 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8933 (let ((from (plist-get plist :from))
8934 (to (plist-get plist :to)))
8935 (when (and from to org-from-is-user-regexp)
8936 (setq plist
8937 (plist-put plist :fromto
8938 (if (string-match org-from-is-user-regexp from)
8939 (concat "to %t")
8940 (concat "from %f"))))))
8941 (setq org-store-link-plist plist))
8943 (defun org-add-link-props (&rest plist)
8944 "Add these properties to the link property list."
8945 (let (key value)
8946 (while plist
8947 (setq key (pop plist) value (pop plist))
8948 (setq org-store-link-plist
8949 (plist-put org-store-link-plist key value)))))
8951 (defun org-email-link-description (&optional fmt)
8952 "Return the description part of an email link.
8953 This takes information from `org-store-link-plist' and formats it
8954 according to FMT (default from `org-email-link-description-format')."
8955 (setq fmt (or fmt org-email-link-description-format))
8956 (let* ((p org-store-link-plist)
8957 (to (plist-get p :toaddress))
8958 (from (plist-get p :fromaddress))
8959 (table
8960 (list
8961 (cons "%c" (plist-get p :fromto))
8962 (cons "%F" (plist-get p :from))
8963 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8964 (cons "%T" (plist-get p :to))
8965 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8966 (cons "%s" (plist-get p :subject))
8967 (cons "%d" (plist-get p :date))
8968 (cons "%m" (plist-get p :message-id)))))
8969 (when (string-match "%c" fmt)
8970 ;; Check if the user wrote this message
8971 (if (and org-from-is-user-regexp from to
8972 (save-match-data (string-match org-from-is-user-regexp from)))
8973 (setq fmt (replace-match "to %t" t t fmt))
8974 (setq fmt (replace-match "from %f" t t fmt))))
8975 (org-replace-escapes fmt table)))
8977 (defun org-make-org-heading-search-string (&optional string heading)
8978 "Make search string for STRING or current headline."
8979 (interactive)
8980 (let ((s (or string (org-get-heading)))
8981 (lines org-context-in-file-links))
8982 (unless (and string (not heading))
8983 ;; We are using a headline, clean up garbage in there.
8984 (if (string-match org-todo-regexp s)
8985 (setq s (replace-match "" t t s)))
8986 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8987 (setq s (replace-match "" t t s)))
8988 (setq s (org-trim s))
8989 (if (string-match (concat "^\\(" org-quote-string "\\|"
8990 org-comment-string "\\)") s)
8991 (setq s (replace-match "" t t s)))
8992 (while (string-match org-ts-regexp s)
8993 (setq s (replace-match "" t t s))))
8994 (or string (setq s (concat "*" s))) ; Add * for headlines
8995 (when (and string (integerp lines) (> lines 0))
8996 (let ((slines (org-split-string s "\n")))
8997 (when (< lines (length slines))
8998 (setq s (mapconcat
8999 'identity
9000 (reverse (nthcdr (- (length slines) lines)
9001 (reverse slines))) "\n")))))
9002 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9004 (defun org-make-link-string (link &optional description)
9005 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9006 (unless (string-match "\\S-" link)
9007 (error "Empty link"))
9008 (when (and description
9009 (stringp description)
9010 (not (string-match "\\S-" description)))
9011 (setq description nil))
9012 (when (stringp description)
9013 ;; Remove brackets from the description, they are fatal.
9014 (while (string-match "\\[" description)
9015 (setq description (replace-match "{" t t description)))
9016 (while (string-match "\\]" description)
9017 (setq description (replace-match "}" t t description))))
9018 (when (equal link description)
9019 ;; No description needed, it is identical
9020 (setq description nil))
9021 (when (and (not description)
9022 (not (string-match (org-image-file-name-regexp) link))
9023 (not (equal link (org-link-escape link))))
9024 (setq description (org-extract-attributes link)))
9025 (setq link
9026 (cond ((string-match (org-image-file-name-regexp) link) link)
9027 ((string-match org-link-types-re link)
9028 (concat (match-string 1 link)
9029 (org-link-escape (substring link (match-end 1)))))
9030 (t (org-link-escape link))))
9031 (concat "[[" link "]"
9032 (if description (concat "[" description "]") "")
9033 "]"))
9035 (defconst org-link-escape-chars
9036 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9037 "List of characters that should be escaped in link.
9038 This is the list that is used for internal purposes.")
9040 (defconst org-link-escape-chars-browser
9041 '(?\ )
9042 "List of escapes for characters that are problematic in links.
9043 This is the list that is used before handing over to the browser.")
9045 (defun org-link-escape (text &optional table merge)
9046 "Return percent escaped representation of TEXT.
9047 TEXT is a string with the text to escape.
9048 Optional argument TABLE is a list with characters that should be
9049 escaped. When nil, `org-link-escape-chars' is used.
9050 If optional argument MERGE is set, merge TABLE into
9051 `org-link-escape-chars'."
9052 (cond
9053 ((and table merge)
9054 (mapc (lambda (defchr)
9055 (unless (member defchr table)
9056 (setq table (cons defchr table)))) org-link-escape-chars))
9057 ((null table)
9058 (setq table org-link-escape-chars)))
9059 (mapconcat
9060 (lambda (char)
9061 (if (or (member char table)
9062 (and (or (< char 32) (= char 37) (> char 126))
9063 org-url-hexify-p))
9064 (mapconcat (lambda (sequence-element)
9065 (format "%%%.2X" sequence-element))
9066 (or (encode-coding-char char 'utf-8)
9067 (error "Unable to percent escape character: %s"
9068 (char-to-string char))) "")
9069 (char-to-string char))) text ""))
9071 (defun org-link-unescape (str)
9072 "Unhex hexified Unicode strings as returned from the JavaScript function
9073 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9074 (unless (and (null str) (string= "" str))
9075 (let ((pos 0) (case-fold-search t) unhexed)
9076 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9077 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9078 (setq str (replace-match unhexed t t str))
9079 (setq pos (+ pos (length unhexed))))))
9080 str)
9082 (defun org-link-unescape-compound (hex)
9083 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9084 Note: this function also decodes single byte encodings like
9085 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9086 (save-match-data
9087 (let* ((bytes (cdr (split-string hex "%")))
9088 (ret "")
9089 (eat 0)
9090 (sum 0))
9091 (while bytes
9092 (let* ((val (string-to-number (pop bytes) 16))
9093 (shift-xor
9094 (if (= 0 eat)
9095 (cond
9096 ((>= val 252) (cons 6 252))
9097 ((>= val 248) (cons 5 248))
9098 ((>= val 240) (cons 4 240))
9099 ((>= val 224) (cons 3 224))
9100 ((>= val 192) (cons 2 192))
9101 (t (cons 0 0)))
9102 (cons 6 128))))
9103 (if (>= val 192) (setq eat (car shift-xor)))
9104 (setq val (logxor val (cdr shift-xor)))
9105 (setq sum (+ (lsh sum (car shift-xor)) val))
9106 (if (> eat 0) (setq eat (- eat 1)))
9107 (cond
9108 ((= 0 eat) ;multi byte
9109 (setq ret (concat ret (org-char-to-string sum)))
9110 (setq sum 0))
9111 ((not bytes) ; single byte(s)
9112 (setq ret (org-link-unescape-single-byte-sequence hex))))
9113 )) ;; end (while bytes
9114 ret )))
9116 (defun org-link-unescape-single-byte-sequence (hex)
9117 "Unhexify hex-encoded single byte character sequences."
9118 (mapconcat (lambda (byte)
9119 (char-to-string (string-to-number byte 16)))
9120 (cdr (split-string hex "%")) ""))
9122 (defun org-xor (a b)
9123 "Exclusive or."
9124 (if a (not b) b))
9126 (defun org-fixup-message-id-for-http (s)
9127 "Replace special characters in a message id, so it can be used in an http query."
9128 (when (string-match "%" s)
9129 (setq s (mapconcat (lambda (c)
9130 (if (eq c ?%)
9131 "%25"
9132 (char-to-string c)))
9133 s "")))
9134 (while (string-match "<" s)
9135 (setq s (replace-match "%3C" t t s)))
9136 (while (string-match ">" s)
9137 (setq s (replace-match "%3E" t t s)))
9138 (while (string-match "@" s)
9139 (setq s (replace-match "%40" t t s)))
9142 (defun org-link-prettify (link)
9143 "Return a human-readable representation of LINK.
9144 The car of LINK must be a raw link the cdr of LINK must be either
9145 a link description or nil."
9146 (let ((desc (or (cadr link) "<no description>")))
9147 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9148 "<" (car link) ">")))
9150 ;;;###autoload
9151 (defun org-insert-link-global ()
9152 "Insert a link like Org-mode does.
9153 This command can be called in any mode to insert a link in Org-mode syntax."
9154 (interactive)
9155 (org-load-modules-maybe)
9156 (org-run-like-in-org-mode 'org-insert-link))
9158 (defun org-insert-all-links (&optional keep)
9159 "Insert all links in `org-stored-links'."
9160 (interactive "P")
9161 (let ((links (copy-sequence org-stored-links)) l)
9162 (while (setq l (if keep (pop links) (pop org-stored-links)))
9163 (insert "- ")
9164 (org-insert-link nil (car l) (cadr l))
9165 (insert "\n"))))
9167 (defun org-link-fontify-links-to-this-file ()
9168 "Fontify links to the current file in `org-stored-links'."
9169 (let ((f (buffer-file-name)) a b)
9170 (setq a (mapcar (lambda(l)
9171 (let ((ll (car l)))
9172 (when (and (string-match "^file:\\(.+\\)::" ll)
9173 (equal f (expand-file-name (match-string 1 ll))))
9174 ll)))
9175 org-stored-links))
9176 (when (featurep 'org-id)
9177 (setq b (mapcar (lambda(l)
9178 (let ((ll (car l)))
9179 (when (and (string-match "^id:\\(.+\\)$" ll)
9180 (equal f (expand-file-name
9181 (or (org-id-find-id-file
9182 (match-string 1 ll)) ""))))
9183 ll)))
9184 org-stored-links)))
9185 (mapcar (lambda(l)
9186 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9187 (delq nil (append a b)))))
9189 (defvar org-link-links-in-this-file nil)
9190 (defun org-insert-link (&optional complete-file link-location default-description)
9191 "Insert a link. At the prompt, enter the link.
9193 Completion can be used to insert any of the link protocol prefixes like
9194 http or ftp in use.
9196 The history can be used to select a link previously stored with
9197 `org-store-link'. When the empty string is entered (i.e. if you just
9198 press RET at the prompt), the link defaults to the most recently
9199 stored link. As SPC triggers completion in the minibuffer, you need to
9200 use M-SPC or C-q SPC to force the insertion of a space character.
9202 You will also be prompted for a description, and if one is given, it will
9203 be displayed in the buffer instead of the link.
9205 If there is already a link at point, this command will allow you to edit link
9206 and description parts.
9208 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9209 be selected using completion. The path to the file will be relative to the
9210 current directory if the file is in the current directory or a subdirectory.
9211 Otherwise, the link will be the absolute path as completed in the minibuffer
9212 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9213 option `org-link-file-path-type'.
9215 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9216 the current directory or below.
9218 With three \\[universal-argument] prefixes, negate the meaning of
9219 `org-keep-stored-link-after-insertion'.
9221 If `org-make-link-description-function' is non-nil, this function will be
9222 called with the link target, and the result will be the default
9223 link description.
9225 If the LINK-LOCATION parameter is non-nil, this value will be
9226 used as the link location instead of reading one interactively.
9228 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9229 be used as the default description."
9230 (interactive "P")
9231 (let* ((wcf (current-window-configuration))
9232 (region (if (org-region-active-p)
9233 (buffer-substring (region-beginning) (region-end))))
9234 (remove (and region (list (region-beginning) (region-end))))
9235 (desc region)
9236 tmphist ; byte-compile incorrectly complains about this
9237 (link link-location)
9238 (abbrevs org-link-abbrev-alist-local)
9239 entry file all-prefixes auto-desc)
9240 (cond
9241 (link-location) ; specified by arg, just use it.
9242 ((org-in-regexp org-bracket-link-regexp 1)
9243 ;; We do have a link at point, and we are going to edit it.
9244 (setq remove (list (match-beginning 0) (match-end 0)))
9245 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9246 (setq link (read-string "Link: "
9247 (org-link-unescape
9248 (org-match-string-no-properties 1)))))
9249 ((or (org-in-regexp org-angle-link-re)
9250 (org-in-regexp org-plain-link-re))
9251 ;; Convert to bracket link
9252 (setq remove (list (match-beginning 0) (match-end 0))
9253 link (read-string "Link: "
9254 (org-remove-angle-brackets (match-string 0)))))
9255 ((member complete-file '((4) (16)))
9256 ;; Completing read for file names.
9257 (setq link (org-file-complete-link complete-file)))
9259 ;; Read link, with completion for stored links.
9260 (org-link-fontify-links-to-this-file)
9261 (org-switch-to-buffer-other-window "*Org Links*")
9262 (with-current-buffer "*Org Links*"
9263 (erase-buffer)
9264 (insert "Insert a link.
9265 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9266 (when org-stored-links
9267 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9268 (insert (mapconcat 'org-link-prettify
9269 (reverse org-stored-links) "\n")))
9270 (goto-char (point-min)))
9271 (let ((cw (selected-window)))
9272 (select-window (get-buffer-window "*Org Links*" 'visible))
9273 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9274 (unless (pos-visible-in-window-p (point-max))
9275 (org-fit-window-to-buffer))
9276 (and (window-live-p cw) (select-window cw)))
9277 ;; Fake a link history, containing the stored links.
9278 (setq tmphist (append (mapcar 'car org-stored-links)
9279 org-insert-link-history))
9280 (setq all-prefixes (append (mapcar 'car abbrevs)
9281 (mapcar 'car org-link-abbrev-alist)
9282 org-link-types))
9283 (unwind-protect
9284 (progn
9285 (setq link
9286 (let ((org-completion-use-ido nil)
9287 (org-completion-use-iswitchb nil))
9288 (org-completing-read
9289 "Link: "
9290 (append
9291 (mapcar (lambda (x) (list (concat x ":")))
9292 all-prefixes)
9293 (mapcar 'car org-stored-links)
9294 (mapcar 'cadr org-stored-links))
9295 nil nil nil
9296 'tmphist
9297 (caar org-stored-links))))
9298 (if (not (string-match "\\S-" link))
9299 (error "No link selected"))
9300 (mapc (lambda(l)
9301 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9302 org-stored-links)
9303 (if (or (member link all-prefixes)
9304 (and (equal ":" (substring link -1))
9305 (member (substring link 0 -1) all-prefixes)
9306 (setq link (substring link 0 -1))))
9307 (setq link (org-link-try-special-completion link))))
9308 (set-window-configuration wcf)
9309 (kill-buffer "*Org Links*"))
9310 (setq entry (assoc link org-stored-links))
9311 (or entry (push link org-insert-link-history))
9312 (setq desc (or desc (nth 1 entry)))))
9314 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9315 (not org-keep-stored-link-after-insertion))
9316 (setq org-stored-links (delq (assoc link org-stored-links)
9317 org-stored-links)))
9319 (if (string-match org-plain-link-re link)
9320 ;; URL-like link, normalize the use of angular brackets.
9321 (setq link (org-remove-angle-brackets link)))
9323 ;; Check if we are linking to the current file with a search
9324 ;; option If yes, simplify the link by using only the search
9325 ;; option.
9326 (when (and buffer-file-name
9327 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9328 (let* ((path (match-string 1 link))
9329 (case-fold-search nil)
9330 (search (match-string 2 link)))
9331 (save-match-data
9332 (if (equal (file-truename buffer-file-name) (file-truename path))
9333 ;; We are linking to this same file, with a search option
9334 (setq link search)))))
9336 ;; Check if we can/should use a relative path. If yes, simplify the link
9337 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9338 (let* ((type (match-string 1 link))
9339 (path (match-string 2 link))
9340 (origpath path)
9341 (case-fold-search nil))
9342 (cond
9343 ((or (eq org-link-file-path-type 'absolute)
9344 (equal complete-file '(16)))
9345 (setq path (abbreviate-file-name (expand-file-name path))))
9346 ((eq org-link-file-path-type 'noabbrev)
9347 (setq path (expand-file-name path)))
9348 ((eq org-link-file-path-type 'relative)
9349 (setq path (file-relative-name path)))
9351 (save-match-data
9352 (if (string-match (concat "^" (regexp-quote
9353 (expand-file-name
9354 (file-name-as-directory
9355 default-directory))))
9356 (expand-file-name path))
9357 ;; We are linking a file with relative path name.
9358 (setq path (substring (expand-file-name path)
9359 (match-end 0)))
9360 (setq path (abbreviate-file-name (expand-file-name path)))))))
9361 (setq link (concat type path))
9362 (if (equal desc origpath)
9363 (setq desc path))))
9365 (if org-make-link-description-function
9366 (setq desc
9367 (or (condition-case nil
9368 (funcall org-make-link-description-function link desc)
9369 (error (progn (message "Can't get link description from `%s'"
9370 (symbol-name org-make-link-description-function))
9371 (sit-for 2) nil)))
9372 (read-string "Description: " default-description)))
9373 (if default-description (setq desc default-description)
9374 (setq desc (or (and auto-desc desc)
9375 (read-string "Description: " desc)))))
9377 (unless (string-match "\\S-" desc) (setq desc nil))
9378 (if remove (apply 'delete-region remove))
9379 (insert (org-make-link-string link desc))))
9381 (defun org-link-try-special-completion (type)
9382 "If there is completion support for link type TYPE, offer it."
9383 (let ((fun (intern (concat "org-" type "-complete-link"))))
9384 (if (functionp fun)
9385 (funcall fun)
9386 (read-string "Link (no completion support): " (concat type ":")))))
9388 (defun org-file-complete-link (&optional arg)
9389 "Create a file link using completion."
9390 (let (file link)
9391 (setq file (read-file-name "File: "))
9392 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9393 (pwd1 (file-name-as-directory (abbreviate-file-name
9394 (expand-file-name ".")))))
9395 (cond
9396 ((equal arg '(16))
9397 (setq link (concat
9398 "file:"
9399 (abbreviate-file-name (expand-file-name file)))))
9400 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9401 (setq link (concat "file:" (match-string 1 file))))
9402 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9403 (expand-file-name file))
9404 (setq link (concat
9405 "file:" (match-string 1 (expand-file-name file)))))
9406 (t (setq link (concat "file:" file)))))
9407 link))
9409 (defun org-completing-read (&rest args)
9410 "Completing-read with SPACE being a normal character."
9411 (let ((enable-recursive-minibuffers t)
9412 (minibuffer-local-completion-map
9413 (copy-keymap minibuffer-local-completion-map)))
9414 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9415 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9416 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9417 (apply 'org-icompleting-read args)))
9419 (defun org-completing-read-no-i (&rest args)
9420 (let (org-completion-use-ido org-completion-use-iswitchb)
9421 (apply 'org-completing-read args)))
9423 (defun org-iswitchb-completing-read (prompt choices &rest args)
9424 "Use iswitch as a completing-read replacement to choose from choices.
9425 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9426 from."
9427 (let* ((iswitchb-use-virtual-buffers nil)
9428 (iswitchb-make-buflist-hook
9429 (lambda ()
9430 (setq iswitchb-temp-buflist choices))))
9431 (iswitchb-read-buffer prompt)))
9433 (defun org-icompleting-read (&rest args)
9434 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9435 (org-without-partial-completion
9436 (if (and org-completion-use-ido
9437 (fboundp 'ido-completing-read)
9438 (boundp 'ido-mode) ido-mode
9439 (listp (second args)))
9440 (let ((ido-enter-matching-directory nil))
9441 (apply 'ido-completing-read (concat (car args))
9442 (if (consp (car (nth 1 args)))
9443 (mapcar 'car (nth 1 args))
9444 (nth 1 args))
9445 (cddr args)))
9446 (if (and org-completion-use-iswitchb
9447 (boundp 'iswitchb-mode) iswitchb-mode
9448 (listp (second args)))
9449 (apply 'org-iswitchb-completing-read (concat (car args))
9450 (if (consp (car (nth 1 args)))
9451 (mapcar 'car (nth 1 args))
9452 (nth 1 args))
9453 (cddr args))
9454 (apply 'completing-read args)))))
9456 (defun org-extract-attributes (s)
9457 "Extract the attributes cookie from a string and set as text property."
9458 (let (a attr (start 0) key value)
9459 (save-match-data
9460 (when (string-match "{{\\([^}]+\\)}}$" s)
9461 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9462 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9463 (setq key (match-string 1 a) value (match-string 2 a)
9464 start (match-end 0)
9465 attr (plist-put attr (intern key) value))))
9466 (org-add-props s nil 'org-attr attr))
9469 (defun org-extract-attributes-from-string (tag)
9470 (let (key value attr)
9471 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9472 (setq key (match-string 1 tag) value (match-string 2 tag)
9473 tag (replace-match "" t t tag)
9474 attr (plist-put attr (intern key) value)))
9475 (cons tag attr)))
9477 (defun org-attributes-to-string (plist)
9478 "Format a property list into an HTML attribute list."
9479 (let ((s "") key value)
9480 (while plist
9481 (setq key (pop plist) value (pop plist))
9482 (and value
9483 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9486 ;;; Opening/following a link
9488 (defvar org-link-search-failed nil)
9490 (defvar org-open-link-functions nil
9491 "Hook for functions finding a plain text link.
9492 These functions must take a single argument, the link content.
9493 They will be called for links that look like [[link text][description]]
9494 when LINK TEXT does not have a protocol like \"http:\" and does not look
9495 like a filename (e.g. \"./blue.png\").
9497 These functions will be called *before* Org attempts to resolve the
9498 link by doing text searches in the current buffer - so if you want a
9499 link \"[[target]]\" to still find \"<<target>>\", your function should
9500 handle this as a special case.
9502 When the function does handle the link, it must return a non-nil value.
9503 If it decides that it is not responsible for this link, it must return
9504 nil to indicate that that Org-mode can continue with other options
9505 like exact and fuzzy text search.")
9507 (defun org-next-link ()
9508 "Move forward to the next link.
9509 If the link is in hidden text, expose it."
9510 (interactive)
9511 (when (and org-link-search-failed (eq this-command last-command))
9512 (goto-char (point-min))
9513 (message "Link search wrapped back to beginning of buffer"))
9514 (setq org-link-search-failed nil)
9515 (let* ((pos (point))
9516 (ct (org-context))
9517 (a (assoc :link ct)))
9518 (if a (goto-char (nth 2 a)))
9519 (if (re-search-forward org-any-link-re nil t)
9520 (progn
9521 (goto-char (match-beginning 0))
9522 (if (outline-invisible-p) (org-show-context)))
9523 (goto-char pos)
9524 (setq org-link-search-failed t)
9525 (error "No further link found"))))
9527 (defun org-previous-link ()
9528 "Move backward to the previous link.
9529 If the link is in hidden text, expose it."
9530 (interactive)
9531 (when (and org-link-search-failed (eq this-command last-command))
9532 (goto-char (point-max))
9533 (message "Link search wrapped back to end of buffer"))
9534 (setq org-link-search-failed nil)
9535 (let* ((pos (point))
9536 (ct (org-context))
9537 (a (assoc :link ct)))
9538 (if a (goto-char (nth 1 a)))
9539 (if (re-search-backward org-any-link-re nil t)
9540 (progn
9541 (goto-char (match-beginning 0))
9542 (if (outline-invisible-p) (org-show-context)))
9543 (goto-char pos)
9544 (setq org-link-search-failed t)
9545 (error "No further link found"))))
9547 (defun org-translate-link (s)
9548 "Translate a link string if a translation function has been defined."
9549 (if (and org-link-translation-function
9550 (fboundp org-link-translation-function)
9551 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9552 (progn
9553 (setq s (funcall org-link-translation-function
9554 (match-string 1 s) (match-string 2 s)))
9555 (concat (car s) ":" (cdr s)))
9558 (defun org-translate-link-from-planner (type path)
9559 "Translate a link from Emacs Planner syntax so that Org can follow it.
9560 This is still an experimental function, your mileage may vary."
9561 (cond
9562 ((member type '("http" "https" "news" "ftp"))
9563 ;; standard Internet links are the same.
9564 nil)
9565 ((and (equal type "irc") (string-match "^//" path))
9566 ;; Planner has two / at the beginning of an irc link, we have 1.
9567 ;; We should have zero, actually....
9568 (setq path (substring path 1)))
9569 ((and (equal type "lisp") (string-match "^/" path))
9570 ;; Planner has a slash, we do not.
9571 (setq type "elisp" path (substring path 1)))
9572 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9573 ;; A typical message link. Planner has the id after the final slash,
9574 ;; we separate it with a hash mark
9575 (setq path (concat (match-string 1 path) "#"
9576 (org-remove-angle-brackets (match-string 2 path)))))
9578 (cons type path))
9580 (defun org-find-file-at-mouse (ev)
9581 "Open file link or URL at mouse."
9582 (interactive "e")
9583 (mouse-set-point ev)
9584 (org-open-at-point 'in-emacs))
9586 (defun org-open-at-mouse (ev)
9587 "Open file link or URL at mouse.
9588 See the docstring of `org-open-file' for details."
9589 (interactive "e")
9590 (mouse-set-point ev)
9591 (if (eq major-mode 'org-agenda-mode)
9592 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9593 (org-open-at-point))
9595 (defvar org-window-config-before-follow-link nil
9596 "The window configuration before following a link.
9597 This is saved in case the need arises to restore it.")
9599 (defvar org-open-link-marker (make-marker)
9600 "Marker pointing to the location where `org-open-at-point; was called.")
9602 ;;;###autoload
9603 (defun org-open-at-point-global ()
9604 "Follow a link like Org-mode does.
9605 This command can be called in any mode to follow a link that has
9606 Org-mode syntax."
9607 (interactive)
9608 (org-run-like-in-org-mode 'org-open-at-point))
9610 ;;;###autoload
9611 (defun org-open-link-from-string (s &optional arg reference-buffer)
9612 "Open a link in the string S, as if it was in Org-mode."
9613 (interactive "sLink: \nP")
9614 (let ((reference-buffer (or reference-buffer (current-buffer))))
9615 (with-temp-buffer
9616 (let ((org-inhibit-startup (not reference-buffer)))
9617 (org-mode)
9618 (insert s)
9619 (goto-char (point-min))
9620 (when reference-buffer
9621 (setq org-link-abbrev-alist-local
9622 (with-current-buffer reference-buffer
9623 org-link-abbrev-alist-local)))
9624 (org-open-at-point arg reference-buffer)))))
9626 (defvar org-open-at-point-functions nil
9627 "Hook that is run when following a link at point.
9629 Functions in this hook must return t if they identify and follow
9630 a link at point. If they don't find anything interesting at point,
9631 they must return nil.")
9633 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9634 (defun org-open-at-point (&optional arg reference-buffer)
9635 "Open link at or after point.
9636 If there is no link at point, this function will search forward up to
9637 the end of the current line.
9638 Normally, files will be opened by an appropriate application. If the
9639 optional prefix argument ARG is non-nil, Emacs will visit the file.
9640 With a double prefix argument, try to open outside of Emacs, in the
9641 application the system uses for this file type."
9642 (interactive "P")
9643 ;; if in a code block, then open the block's results
9644 (unless (call-interactively #'org-babel-open-src-block-result)
9645 (org-load-modules-maybe)
9646 (move-marker org-open-link-marker (point))
9647 (setq org-window-config-before-follow-link (current-window-configuration))
9648 (org-remove-occur-highlights nil nil t)
9649 (cond
9650 ((and (org-at-heading-p)
9651 (not (org-at-timestamp-p t))
9652 (not (org-in-regexp
9653 (concat org-plain-link-re "\\|"
9654 org-bracket-link-regexp "\\|"
9655 org-angle-link-re "\\|"
9656 "[ \t]:[^ \t\n]+:[ \t]*$")))
9657 (not (get-text-property (point) 'org-linked-text)))
9658 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9659 (lk (car lkall))
9660 (lkend (cdr lkall)))
9661 (when lk
9662 (prog1 (search-forward lk nil lkend)
9663 (goto-char (match-beginning 0))
9664 (org-open-at-point))))
9665 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9666 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9667 ((and (org-at-timestamp-p t)
9668 (not (org-in-regexp org-bracket-link-regexp)))
9669 (org-follow-timestamp-link))
9670 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9671 (not (org-in-regexp org-any-link-re)))
9672 (org-footnote-action))
9674 (let (type path link line search (pos (point)))
9675 (catch 'match
9676 (save-excursion
9677 (skip-chars-forward "^]\n\r")
9678 (when (org-in-regexp org-bracket-link-regexp 1)
9679 (setq link (org-extract-attributes
9680 (org-link-unescape (org-match-string-no-properties 1))))
9681 (while (string-match " *\n *" link)
9682 (setq link (replace-match " " t t link)))
9683 (setq link (org-link-expand-abbrev link))
9684 (cond
9685 ((or (file-name-absolute-p link)
9686 (string-match "^\\.\\.?/" link))
9687 (setq type "file" path link))
9688 ((string-match org-link-re-with-space3 link)
9689 (setq type (match-string 1 link) path (match-string 2 link)))
9690 ((string-match "^help:+\\(.+\\)" link)
9691 (setq type "help" path (match-string 1 link)))
9692 (t (setq type "thisfile" path link)))
9693 (throw 'match t)))
9695 (when (get-text-property (point) 'org-linked-text)
9696 (setq type "thisfile"
9697 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9698 (1+ (point)) (point))
9699 path (buffer-substring
9700 (or (previous-single-property-change pos 'org-linked-text)
9701 (point-min))
9702 (or (next-single-property-change pos 'org-linked-text)
9703 (point-max))))
9704 (throw 'match t))
9706 (save-excursion
9707 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9708 (when (or (org-in-regexp org-angle-link-re)
9709 (and plinkpos (goto-char (car plinkpos))
9710 (save-match-data (not (looking-back "\\[\\[")))))
9711 (setq type (match-string 1)
9712 path (org-link-unescape (match-string 2)))
9713 (throw 'match t))))
9714 (save-excursion
9715 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9716 (setq type "tags"
9717 path (match-string 1))
9718 (while (string-match ":" path)
9719 (setq path (replace-match "+" t t path)))
9720 (throw 'match t)))
9721 (when (org-in-regexp "<\\([^><\n]+\\)>")
9722 (setq type "tree-match"
9723 path (match-string 1))
9724 (throw 'match t)))
9725 (unless path
9726 (user-error "No link found"))
9728 ;; switch back to reference buffer
9729 ;; needed when if called in a temporary buffer through
9730 ;; org-open-link-from-string
9731 (with-current-buffer (or reference-buffer (current-buffer))
9733 ;; Remove any trailing spaces in path
9734 (if (string-match " +\\'" path)
9735 (setq path (replace-match "" t t path)))
9736 (if (and org-link-translation-function
9737 (fboundp org-link-translation-function))
9738 ;; Check if we need to translate the link
9739 (let ((tmp (funcall org-link-translation-function type path)))
9740 (setq type (car tmp) path (cdr tmp))))
9742 (cond
9744 ((assoc type org-link-protocols)
9745 (funcall (nth 1 (assoc type org-link-protocols)) path))
9747 ((equal type "help")
9748 (let ((f-or-v (intern path)))
9749 (cond ((fboundp f-or-v)
9750 (describe-function f-or-v))
9751 ((boundp f-or-v)
9752 (describe-variable f-or-v))
9753 (t (error "Not a known function or variable")))))
9755 ((equal type "mailto")
9756 (let ((cmd (car org-link-mailto-program))
9757 (args (cdr org-link-mailto-program)) args1
9758 (address path) (subject "") a)
9759 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9760 (setq address (match-string 1 path)
9761 subject (org-link-escape (match-string 2 path))))
9762 (while args
9763 (cond
9764 ((not (stringp (car args))) (push (pop args) args1))
9765 (t (setq a (pop args))
9766 (if (string-match "%a" a)
9767 (setq a (replace-match address t t a)))
9768 (if (string-match "%s" a)
9769 (setq a (replace-match subject t t a)))
9770 (push a args1))))
9771 (apply cmd (nreverse args1))))
9773 ((member type '("http" "https" "ftp" "news"))
9774 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9775 (org-link-escape
9776 path org-link-escape-chars-browser)
9777 path))))
9779 ((string= type "doi")
9780 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9781 (org-link-escape
9782 path org-link-escape-chars-browser)
9783 path))))
9785 ((member type '("message"))
9786 (browse-url (concat type ":" path)))
9788 ((string= type "tags")
9789 (org-tags-view arg path))
9791 ((string= type "tree-match")
9792 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9794 ((string= type "file")
9795 (if (string-match "::\\([0-9]+\\)\\'" path)
9796 (setq line (string-to-number (match-string 1 path))
9797 path (substring path 0 (match-beginning 0)))
9798 (if (string-match "::\\(.+\\)\\'" path)
9799 (setq search (match-string 1 path)
9800 path (substring path 0 (match-beginning 0)))))
9801 (if (string-match "[*?{]" (file-name-nondirectory path))
9802 (dired path)
9803 (org-open-file path arg line search)))
9805 ((string= type "shell")
9806 (let ((buf (generate-new-buffer "*Org Shell Output"))
9807 (cmd path))
9808 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9809 (string-match org-confirm-shell-link-not-regexp cmd))
9810 (not org-confirm-shell-link-function)
9811 (funcall org-confirm-shell-link-function
9812 (format "Execute \"%s\" in shell? "
9813 (org-add-props cmd nil
9814 'face 'org-warning))))
9815 (progn
9816 (message "Executing %s" cmd)
9817 (shell-command cmd buf)
9818 (if (featurep 'midnight)
9819 (setq clean-buffer-list-kill-buffer-names
9820 (cons buf clean-buffer-list-kill-buffer-names))))
9821 (error "Abort"))))
9823 ((string= type "elisp")
9824 (let ((cmd path))
9825 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9826 (string-match org-confirm-elisp-link-not-regexp cmd))
9827 (not org-confirm-elisp-link-function)
9828 (funcall org-confirm-elisp-link-function
9829 (format "Execute \"%s\" as elisp? "
9830 (org-add-props cmd nil
9831 'face 'org-warning))))
9832 (message "%s => %s" cmd
9833 (if (equal (string-to-char cmd) ?\()
9834 (eval (read cmd))
9835 (call-interactively (read cmd))))
9836 (error "Abort"))))
9838 ((and (string= type "thisfile")
9839 (run-hook-with-args-until-success
9840 'org-open-link-functions path)))
9842 ((string= type "thisfile")
9843 (if arg
9844 (switch-to-buffer-other-window
9845 (org-get-buffer-for-internal-link (current-buffer)))
9846 (org-mark-ring-push))
9847 (let ((cmd `(org-link-search
9848 ,path
9849 ,(cond ((equal arg '(4)) ''occur)
9850 ((equal arg '(16)) ''org-occur))
9851 ,pos)))
9852 (condition-case nil (let ((org-link-search-inhibit-query t))
9853 (eval cmd))
9854 (error (progn (widen) (eval cmd))))))
9856 (t (browse-url-at-point)))))))
9857 (move-marker org-open-link-marker nil)
9858 (run-hook-with-args 'org-follow-link-hook)))
9860 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
9861 "Offer links in the current entry and return the selected link.
9862 If there is only one link, return it.
9863 If NTH is an integer, return the NTH link found.
9864 If ZERO is a string, check also this string for a link, and if
9865 there is one, return it."
9866 (with-current-buffer buffer
9867 (save-excursion
9868 (save-restriction
9869 (widen)
9870 (goto-char marker)
9871 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9872 "\\(" org-angle-link-re "\\)\\|"
9873 "\\(" org-plain-link-re "\\)"))
9874 (cnt ?0)
9875 (in-emacs (if (integerp nth) nil nth))
9876 have-zero end links link c)
9877 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9878 (push (match-string 0 zero) links)
9879 (setq cnt (1- cnt) have-zero t))
9880 (save-excursion
9881 (org-back-to-heading t)
9882 (setq end (save-excursion (outline-next-heading) (point)))
9883 (while (re-search-forward re end t)
9884 (push (match-string 0) links))
9885 (setq links (org-uniquify (reverse links))))
9886 (cond
9887 ((null links)
9888 (message "No links"))
9889 ((equal (length links) 1)
9890 (setq link (car links)))
9891 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9892 (setq link (nth (if have-zero nth (1- nth)) links)))
9893 (t ; we have to select a link
9894 (save-excursion
9895 (save-window-excursion
9896 (delete-other-windows)
9897 (with-output-to-temp-buffer "*Select Link*"
9898 (mapc (lambda (l)
9899 (if (not (string-match org-bracket-link-regexp l))
9900 (princ (format "[%c] %s\n" (incf cnt)
9901 (org-remove-angle-brackets l)))
9902 (if (match-end 3)
9903 (princ (format "[%c] %s (%s)\n" (incf cnt)
9904 (match-string 3 l) (match-string 1 l)))
9905 (princ (format "[%c] %s\n" (incf cnt)
9906 (match-string 1 l))))))
9907 links))
9908 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9909 (message "Select link to open, RET to open all:")
9910 (setq c (read-char-exclusive))
9911 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9912 (when (equal c ?q) (error "Abort"))
9913 (if (equal c ?\C-m)
9914 (setq link links)
9915 (setq nth (- c ?0))
9916 (if have-zero (setq nth (1+ nth)))
9917 (unless (and (integerp nth) (>= (length links) nth))
9918 (error "Invalid link selection"))
9919 (setq link (nth (1- nth) links)))))
9920 (cons link end))))))
9922 ;; Add special file links that specify the way of opening
9924 (org-add-link-type "file+sys" 'org-open-file-with-system)
9925 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9926 (defun org-open-file-with-system (path)
9927 "Open file at PATH using the system way of opening it."
9928 (org-open-file path 'system))
9929 (defun org-open-file-with-emacs (path)
9930 "Open file at PATH in Emacs."
9931 (org-open-file path 'emacs))
9932 (defun org-remove-file-link-modifiers ()
9933 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9934 (goto-char (point-min))
9935 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9936 (org-if-unprotected
9937 (replace-match "file:" t t))))
9938 (eval-after-load "org-exp"
9939 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9940 'org-remove-file-link-modifiers))
9942 ;;;; Time estimates
9944 (defun org-get-effort (&optional pom)
9945 "Get the effort estimate for the current entry."
9946 (org-entry-get pom org-effort-property))
9948 ;;; File search
9950 (defvar org-create-file-search-functions nil
9951 "List of functions to construct the right search string for a file link.
9952 These functions are called in turn with point at the location to
9953 which the link should point.
9955 A function in the hook should first test if it would like to
9956 handle this file type, for example by checking the `major-mode'
9957 or the file extension. If it decides not to handle this file, it
9958 should just return nil to give other functions a chance. If it
9959 does handle the file, it must return the search string to be used
9960 when following the link. The search string will be part of the
9961 file link, given after a double colon, and `org-open-at-point'
9962 will automatically search for it. If special measures must be
9963 taken to make the search successful, another function should be
9964 added to the companion hook `org-execute-file-search-functions',
9965 which see.
9967 A function in this hook may also use `setq' to set the variable
9968 `description' to provide a suggestion for the descriptive text to
9969 be used for this link when it gets inserted into an Org-mode
9970 buffer with \\[org-insert-link].")
9972 (defvar org-execute-file-search-functions nil
9973 "List of functions to execute a file search triggered by a link.
9975 Functions added to this hook must accept a single argument, the
9976 search string that was part of the file link, the part after the
9977 double colon. The function must first check if it would like to
9978 handle this search, for example by checking the `major-mode' or
9979 the file extension. If it decides not to handle this search, it
9980 should just return nil to give other functions a chance. If it
9981 does handle the search, it must return a non-nil value to keep
9982 other functions from trying.
9984 Each function can access the current prefix argument through the
9985 variable `current-prefix-argument'. Note that a single prefix is
9986 used to force opening a link in Emacs, so it may be good to only
9987 use a numeric or double prefix to guide the search function.
9989 In case this is needed, a function in this hook can also restore
9990 the window configuration before `org-open-at-point' was called using:
9992 (set-window-configuration org-window-config-before-follow-link)")
9994 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9995 (defun org-link-search (s &optional type avoid-pos stealth)
9996 "Search for a link search option.
9997 If S is surrounded by forward slashes, it is interpreted as a
9998 regular expression. In org-mode files, this will create an `org-occur'
9999 sparse tree. In ordinary files, `occur' will be used to list matches.
10000 If the current buffer is in `dired-mode', grep will be used to search
10001 in all files. If AVOID-POS is given, ignore matches near that position.
10003 When optional argument STEALTH is non-nil, do not modify
10004 visibility around point, thus ignoring
10005 `org-show-hierarchy-above', `org-show-following-heading' and
10006 `org-show-siblings' variables."
10007 (let ((case-fold-search t)
10008 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10009 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10010 (append '(("") (" ") ("\t") ("\n"))
10011 org-emphasis-alist)
10012 "\\|") "\\)"))
10013 (pos (point))
10014 (pre nil) (post nil)
10015 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10016 (cond
10017 ;; First check if there are any special search functions
10018 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10019 ;; Now try the builtin stuff
10020 ((and (equal (string-to-char s0) ?#)
10021 (> (length s0) 1)
10022 (save-excursion
10023 (goto-char (point-min))
10024 (and
10025 (re-search-forward
10026 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10027 (setq type 'dedicated
10028 pos (match-beginning 0))))
10029 ;; There is an exact target for this
10030 (goto-char pos)
10031 (org-back-to-heading t)))
10032 ((save-excursion
10033 (goto-char (point-min))
10034 (and
10035 (re-search-forward
10036 (concat "<<" (regexp-quote s0) ">>") nil t)
10037 (setq type 'dedicated
10038 pos (match-beginning 0))))
10039 ;; There is an exact target for this
10040 (goto-char pos))
10041 ((save-excursion
10042 (goto-char (point-min))
10043 (and
10044 (re-search-forward
10045 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10046 (setq type 'dedicated pos (match-beginning 0))))
10047 ;; Found an invisible target.
10048 (goto-char pos))
10049 ((save-excursion
10050 (goto-char (point-min))
10051 (and
10052 (re-search-forward
10053 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10054 (setq type 'dedicated pos (match-beginning 0))))
10055 ;; Found an element with a matching #+name affiliated keyword.
10056 (goto-char pos))
10057 ((and (string-match "^(\\(.*\\))$" s0)
10058 (save-excursion
10059 (goto-char (point-min))
10060 (and
10061 (re-search-forward
10062 (concat "[^[]" (regexp-quote
10063 (format org-coderef-label-format
10064 (match-string 1 s0))))
10065 nil t)
10066 (setq type 'dedicated
10067 pos (1+ (match-beginning 0))))))
10068 ;; There is a coderef target for this
10069 (goto-char pos))
10070 ((string-match "^/\\(.*\\)/$" s)
10071 ;; A regular expression
10072 (cond
10073 ((derived-mode-p 'org-mode)
10074 (org-occur (match-string 1 s)))
10075 ;;((eq major-mode 'dired-mode)
10076 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10077 (t (org-do-occur (match-string 1 s)))))
10078 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10079 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10080 (goto-char (point-min))
10081 (cond
10082 ((let (case-fold-search)
10083 (re-search-forward (format org-complex-heading-regexp-format
10084 (regexp-quote s))
10085 nil t))
10086 ;; OK, found a match
10087 (setq type 'dedicated)
10088 (goto-char (match-beginning 0)))
10089 ((and (not org-link-search-inhibit-query)
10090 (eq org-link-search-must-match-exact-headline 'query-to-create)
10091 (y-or-n-p "No match - create this as a new heading? "))
10092 (goto-char (point-max))
10093 (or (bolp) (newline))
10094 (insert "* " s "\n")
10095 (beginning-of-line 0))
10097 (goto-char pos)
10098 (error "No match"))))
10100 ;; A normal search string
10101 (when (equal (string-to-char s) ?*)
10102 ;; Anchor on headlines, post may include tags.
10103 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10104 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10105 s (substring s 1)))
10106 (remove-text-properties
10107 0 (length s)
10108 '(face nil mouse-face nil keymap nil fontified nil) s)
10109 ;; Make a series of regular expressions to find a match
10110 (setq words (org-split-string s "[ \n\r\t]+")
10112 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10113 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10114 "\\)" markers)
10115 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10116 re2a (concat "[ \t\r\n]" re2a_)
10117 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10118 re4 (concat "[^a-zA-Z_]" re4_)
10120 re1 (concat pre re2 post)
10121 re3 (concat pre (if pre re4_ re4) post)
10122 re5 (concat pre ".*" re4)
10123 re2 (concat pre re2)
10124 re2a (concat pre (if pre re2a_ re2a))
10125 re4 (concat pre (if pre re4_ re4))
10126 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10127 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10128 re5 "\\)"
10130 (cond
10131 ((eq type 'org-occur) (org-occur reall))
10132 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10133 (t (goto-char (point-min))
10134 (setq type 'fuzzy)
10135 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10136 (org-search-not-self 1 re1 nil t)
10137 (org-search-not-self 1 re2 nil t)
10138 (org-search-not-self 1 re2a nil t)
10139 (org-search-not-self 1 re3 nil t)
10140 (org-search-not-self 1 re4 nil t)
10141 (org-search-not-self 1 re5 nil t)
10143 (goto-char (match-beginning 1))
10144 (goto-char pos)
10145 (error "No match"))))))
10146 (and (derived-mode-p 'org-mode)
10147 (not stealth)
10148 (org-show-context 'link-search))
10149 type))
10151 (defun org-search-not-self (group &rest args)
10152 "Execute `re-search-forward', but only accept matches that do not
10153 enclose the position of `org-open-link-marker'."
10154 (let ((m org-open-link-marker))
10155 (catch 'exit
10156 (while (apply 're-search-forward args)
10157 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10158 (goto-char (match-end group))
10159 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10160 (> (match-beginning 0) (marker-position m))
10161 (< (match-end 0) (marker-position m)))
10162 (save-match-data
10163 (or (not (org-in-regexp
10164 org-bracket-link-analytic-regexp 1))
10165 (not (match-end 4)) ; no description
10166 (and (<= (match-beginning 4) (point))
10167 (>= (match-end 4) (point))))))
10168 (throw 'exit (point))))))))
10170 (defun org-get-buffer-for-internal-link (buffer)
10171 "Return a buffer to be used for displaying the link target of internal links."
10172 (cond
10173 ((not org-display-internal-link-with-indirect-buffer)
10174 buffer)
10175 ((string-match "(Clone)$" (buffer-name buffer))
10176 (message "Buffer is already a clone, not making another one")
10177 ;; we also do not modify visibility in this case
10178 buffer)
10179 (t ; make a new indirect buffer for displaying the link
10180 (let* ((bn (buffer-name buffer))
10181 (ibn (concat bn "(Clone)"))
10182 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10183 (with-current-buffer ib (org-overview))
10184 ib))))
10186 (defun org-do-occur (regexp &optional cleanup)
10187 "Call the Emacs command `occur'.
10188 If CLEANUP is non-nil, remove the printout of the regular expression
10189 in the *Occur* buffer. This is useful if the regex is long and not useful
10190 to read."
10191 (occur regexp)
10192 (when cleanup
10193 (let ((cwin (selected-window)) win beg end)
10194 (when (setq win (get-buffer-window "*Occur*"))
10195 (select-window win))
10196 (goto-char (point-min))
10197 (when (re-search-forward "match[a-z]+" nil t)
10198 (setq beg (match-end 0))
10199 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10200 (setq end (1- (match-beginning 0)))))
10201 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10202 (goto-char (point-min))
10203 (select-window cwin))))
10205 ;;; The mark ring for links jumps
10207 (defvar org-mark-ring nil
10208 "Mark ring for positions before jumps in Org-mode.")
10209 (defvar org-mark-ring-last-goto nil
10210 "Last position in the mark ring used to go back.")
10211 ;; Fill and close the ring
10212 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10213 (loop for i from 1 to org-mark-ring-length do
10214 (push (make-marker) org-mark-ring))
10215 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10216 org-mark-ring)
10218 (defun org-mark-ring-push (&optional pos buffer)
10219 "Put the current position or POS into the mark ring and rotate it."
10220 (interactive)
10221 (setq pos (or pos (point)))
10222 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10223 (move-marker (car org-mark-ring)
10224 (or pos (point))
10225 (or buffer (current-buffer)))
10226 (message "%s"
10227 (substitute-command-keys
10228 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10230 (defun org-mark-ring-goto (&optional n)
10231 "Jump to the previous position in the mark ring.
10232 With prefix arg N, jump back that many stored positions. When
10233 called several times in succession, walk through the entire ring.
10234 Org-mode commands jumping to a different position in the current file,
10235 or to another Org-mode file, automatically push the old position
10236 onto the ring."
10237 (interactive "p")
10238 (let (p m)
10239 (if (eq last-command this-command)
10240 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10241 (setq p org-mark-ring))
10242 (setq org-mark-ring-last-goto p)
10243 (setq m (car p))
10244 (org-pop-to-buffer-same-window (marker-buffer m))
10245 (goto-char m)
10246 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10248 (defun org-remove-angle-brackets (s)
10249 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10250 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10252 (defun org-add-angle-brackets (s)
10253 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10254 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10256 (defun org-remove-double-quotes (s)
10257 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10258 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10261 ;;; Following specific links
10263 (defun org-follow-timestamp-link ()
10264 "Open an agenda view for the time-stamp date/range at point."
10265 (cond
10266 ((org-at-date-range-p t)
10267 (let ((org-agenda-start-on-weekday)
10268 (t1 (match-string 1))
10269 (t2 (match-string 2)) tt1 tt2)
10270 (setq tt1 (time-to-days (org-time-string-to-time t1))
10271 tt2 (time-to-days (org-time-string-to-time t2)))
10272 (let ((org-agenda-buffer-tmp-name
10273 (format "*Org Agenda(a:%s)"
10274 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10275 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10276 ((org-at-timestamp-p t)
10277 (let ((org-agenda-buffer-tmp-name
10278 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10279 (org-agenda-list nil (time-to-days (org-time-string-to-time
10280 (substring (match-string 1) 0 10)))
10281 1)))
10282 (t (error "This should not happen"))))
10285 ;;; Following file links
10286 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10287 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10288 (declare-function mailcap-mime-info
10289 "mailcap" (string &optional request no-decode))
10290 (defvar org-wait nil)
10291 (defun org-open-file (path &optional in-emacs line search)
10292 "Open the file at PATH.
10293 First, this expands any special file name abbreviations. Then the
10294 configuration variable `org-file-apps' is checked if it contains an
10295 entry for this file type, and if yes, the corresponding command is launched.
10297 If no application is found, Emacs simply visits the file.
10299 With optional prefix argument IN-EMACS, Emacs will visit the file.
10300 With a double \\[universal-argument] \\[universal-argument] \
10301 prefix arg, Org tries to avoid opening in Emacs
10302 and to use an external application to visit the file.
10304 Optional LINE specifies a line to go to, optional SEARCH a string
10305 to search for. If LINE or SEARCH is given, the file will be
10306 opened in Emacs, unless an entry from org-file-apps that makes
10307 use of groups in a regexp matches.
10309 If you want to change the way frames are used when following a
10310 link, please customize `org-link-frame-setup'.
10312 If the file does not exist, an error is thrown."
10313 (let* ((file (if (equal path "")
10314 buffer-file-name
10315 (substitute-in-file-name (expand-file-name path))))
10316 (file-apps (append org-file-apps (org-default-apps)))
10317 (apps (org-remove-if
10318 'org-file-apps-entry-match-against-dlink-p file-apps))
10319 (apps-dlink (org-remove-if-not
10320 'org-file-apps-entry-match-against-dlink-p file-apps))
10321 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10322 (dirp (if remp nil (file-directory-p file)))
10323 (file (if (and dirp org-open-directory-means-index-dot-org)
10324 (concat (file-name-as-directory file) "index.org")
10325 file))
10326 (a-m-a-p (assq 'auto-mode apps))
10327 (dfile (downcase file))
10328 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10329 (link (cond ((and (eq line nil)
10330 (eq search nil))
10331 file)
10332 (line
10333 (concat file "::" (number-to-string line)))
10334 (search
10335 (concat file "::" search))))
10336 (dlink (downcase link))
10337 (old-buffer (current-buffer))
10338 (old-pos (point))
10339 (old-mode major-mode)
10340 ext cmd link-match-data)
10341 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10342 (setq ext (match-string 1 dfile))
10343 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10344 (setq ext (match-string 1 dfile))))
10345 (cond
10346 ((member in-emacs '((16) system))
10347 (setq cmd (cdr (assoc 'system apps))))
10348 (in-emacs (setq cmd 'emacs))
10350 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10351 (and dirp (cdr (assoc 'directory apps)))
10352 ; first, try matching against apps-dlink
10353 ; if we get a match here, store the match data for later
10354 (let ((match (assoc-default dlink apps-dlink
10355 'string-match)))
10356 (if match
10357 (progn (setq link-match-data (match-data))
10358 match)
10359 (progn (setq in-emacs (or in-emacs line search))
10360 nil))) ; if we have no match in apps-dlink,
10361 ; always open the file in emacs if line or search
10362 ; is given (for backwards compatibility)
10363 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10364 'string-match)
10365 (cdr (assoc ext apps))
10366 (cdr (assoc t apps))))))
10367 (when (eq cmd 'system)
10368 (setq cmd (cdr (assoc 'system apps))))
10369 (when (eq cmd 'default)
10370 (setq cmd (cdr (assoc t apps))))
10371 (when (eq cmd 'mailcap)
10372 (require 'mailcap)
10373 (mailcap-parse-mailcaps)
10374 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10375 (command (mailcap-mime-info mime-type)))
10376 (if (stringp command)
10377 (setq cmd command)
10378 (setq cmd 'emacs))))
10379 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10380 (not (file-exists-p file))
10381 (not org-open-non-existing-files))
10382 (error "No such file: %s" file))
10383 (cond
10384 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10385 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10386 (while (string-match "['\"]%s['\"]" cmd)
10387 (setq cmd (replace-match "%s" t t cmd)))
10388 (while (string-match "%s" cmd)
10389 (setq cmd (replace-match
10390 (save-match-data
10391 (shell-quote-argument
10392 (convert-standard-filename file)))
10393 t t cmd)))
10395 ;; Replace "%1", "%2" etc. in command with group matches from regex
10396 (save-match-data
10397 (let ((match-index 1)
10398 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10399 (set-match-data link-match-data)
10400 (while (<= match-index number-of-groups)
10401 (let ((regex (concat "%" (number-to-string match-index)))
10402 (replace-with (match-string match-index dlink)))
10403 (while (string-match regex cmd)
10404 (setq cmd (replace-match replace-with t t cmd))))
10405 (setq match-index (+ match-index 1)))))
10407 (save-window-excursion
10408 (start-process-shell-command cmd nil cmd)
10409 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10411 ((or (stringp cmd)
10412 (eq cmd 'emacs))
10413 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10414 (widen)
10415 (if line (org-goto-line line)
10416 (if search (org-link-search search))))
10417 ((consp cmd)
10418 (let ((file (convert-standard-filename file)))
10419 (save-match-data
10420 (set-match-data link-match-data)
10421 (eval cmd))))
10422 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10423 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10424 (or (not (equal old-buffer (current-buffer)))
10425 (not (equal old-pos (point))))
10426 (org-mark-ring-push old-pos old-buffer))))
10428 (defun org-file-apps-entry-match-against-dlink-p (entry)
10429 "This function returns non-nil if `entry' uses a regular
10430 expression which should be matched against the whole link by
10431 org-open-file.
10433 It assumes that is the case when the entry uses a regular
10434 expression which has at least one grouping construct and the
10435 action is either a lisp form or a command string containing
10436 '%1', i.e. using at least one subexpression match as a
10437 parameter."
10438 (let ((selector (car entry))
10439 (action (cdr entry)))
10440 (if (stringp selector)
10441 (and (> (regexp-opt-depth selector) 0)
10442 (or (and (stringp action)
10443 (string-match "%[0-9]" action))
10444 (consp action)))
10445 nil)))
10447 (defun org-default-apps ()
10448 "Return the default applications for this operating system."
10449 (cond
10450 ((eq system-type 'darwin)
10451 org-file-apps-defaults-macosx)
10452 ((eq system-type 'windows-nt)
10453 org-file-apps-defaults-windowsnt)
10454 (t org-file-apps-defaults-gnu)))
10456 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10457 "Convert extensions to regular expressions in the cars of LIST.
10458 Also, weed out any non-string entries, because the return value is used
10459 only for regexp matching.
10460 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10461 point to the symbol `emacs', indicating that the file should
10462 be opened in Emacs."
10463 (append
10464 (delq nil
10465 (mapcar (lambda (x)
10466 (if (not (stringp (car x)))
10468 (if (string-match "\\W" (car x))
10470 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10471 list))
10472 (if add-auto-mode
10473 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10475 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10476 (defun org-file-remote-p (file)
10477 "Test whether FILE specifies a location on a remote system.
10478 Return non-nil if the location is indeed remote.
10480 For example, the filename \"/user@host:/foo\" specifies a location
10481 on the system \"/user@host:\"."
10482 (cond ((fboundp 'file-remote-p)
10483 (file-remote-p file))
10484 ((fboundp 'tramp-handle-file-remote-p)
10485 (tramp-handle-file-remote-p file))
10486 ((and (boundp 'ange-ftp-name-format)
10487 (string-match (car ange-ftp-name-format) file))
10488 t)))
10491 ;;;; Refiling
10493 (defun org-get-org-file ()
10494 "Read a filename, with default directory `org-directory'."
10495 (let ((default (or org-default-notes-file remember-data-file)))
10496 (read-file-name (format "File name [%s]: " default)
10497 (file-name-as-directory org-directory)
10498 default)))
10500 (defun org-notes-order-reversed-p ()
10501 "Check if the current file should receive notes in reversed order."
10502 (cond
10503 ((not org-reverse-note-order) nil)
10504 ((eq t org-reverse-note-order) t)
10505 ((not (listp org-reverse-note-order)) nil)
10506 (t (catch 'exit
10507 (let ((all org-reverse-note-order)
10508 entry)
10509 (while (setq entry (pop all))
10510 (if (string-match (car entry) buffer-file-name)
10511 (throw 'exit (cdr entry))))
10512 nil)))))
10514 (defvar org-refile-target-table nil
10515 "The list of refile targets, created by `org-refile'.")
10517 (defvar org-agenda-new-buffers nil
10518 "Buffers created to visit agenda files.")
10520 (defvar org-refile-cache nil
10521 "Cache for refile targets.")
10523 (defvar org-refile-markers nil
10524 "All the markers used for caching refile locations.")
10526 (defun org-refile-marker (pos)
10527 "Get a new refile marker, but only if caching is in use."
10528 (if (not org-refile-use-cache)
10530 (let ((m (make-marker)))
10531 (move-marker m pos)
10532 (push m org-refile-markers)
10533 m)))
10535 (defun org-refile-cache-clear ()
10536 "Clear the refile cache and disable all the markers."
10537 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10538 (setq org-refile-markers nil)
10539 (setq org-refile-cache nil)
10540 (message "Refile cache has been cleared"))
10542 (defun org-refile-cache-check-set (set)
10543 "Check if all the markers in the cache still have live buffers."
10544 (let (marker)
10545 (catch 'exit
10546 (while (and set (setq marker (nth 3 (pop set))))
10547 ;; if org-refile-use-outline-path is 'file, marker may be nil
10548 (when (and marker (null (marker-buffer marker)))
10549 (message "not found") (sit-for 3)
10550 (throw 'exit nil)))
10551 t)))
10553 (defun org-refile-cache-put (set &rest identifiers)
10554 "Push the refile targets SET into the cache, under IDENTIFIERS."
10555 (let* ((key (sha1 (prin1-to-string identifiers)))
10556 (entry (assoc key org-refile-cache)))
10557 (if entry
10558 (setcdr entry set)
10559 (push (cons key set) org-refile-cache))))
10561 (defun org-refile-cache-get (&rest identifiers)
10562 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10563 (cond
10564 ((not org-refile-cache) nil)
10565 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10567 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10568 org-refile-cache))))
10569 (and set (org-refile-cache-check-set set) set)))))
10571 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10572 "Produce a table with refile targets."
10573 (let ((case-fold-search nil)
10574 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10575 (entries (or org-refile-targets '((nil . (:level . 1)))))
10576 targets tgs txt re files f desc descre fast-path-p level pos0)
10577 (message "Getting targets...")
10578 (with-current-buffer (or default-buffer (current-buffer))
10579 (while (setq entry (pop entries))
10580 (setq files (car entry) desc (cdr entry))
10581 (setq fast-path-p nil)
10582 (cond
10583 ((null files) (setq files (list (current-buffer))))
10584 ((eq files 'org-agenda-files)
10585 (setq files (org-agenda-files 'unrestricted)))
10586 ((and (symbolp files) (fboundp files))
10587 (setq files (funcall files)))
10588 ((and (symbolp files) (boundp files))
10589 (setq files (symbol-value files))))
10590 (if (stringp files) (setq files (list files)))
10591 (cond
10592 ((eq (car desc) :tag)
10593 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10594 ((eq (car desc) :todo)
10595 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10596 ((eq (car desc) :regexp)
10597 (setq descre (cdr desc)))
10598 ((eq (car desc) :level)
10599 (setq descre (concat "^\\*\\{" (number-to-string
10600 (if org-odd-levels-only
10601 (1- (* 2 (cdr desc)))
10602 (cdr desc)))
10603 "\\}[ \t]")))
10604 ((eq (car desc) :maxlevel)
10605 (setq fast-path-p t)
10606 (setq descre (concat "^\\*\\{1," (number-to-string
10607 (if org-odd-levels-only
10608 (1- (* 2 (cdr desc)))
10609 (cdr desc)))
10610 "\\}[ \t]")))
10611 (t (error "Bad refiling target description %s" desc)))
10612 (while (setq f (pop files))
10613 (with-current-buffer
10614 (if (bufferp f) f (org-get-agenda-file-buffer f))
10616 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10617 (progn
10618 (if (bufferp f) (setq f (buffer-file-name
10619 (buffer-base-buffer f))))
10620 (setq f (and f (expand-file-name f)))
10621 (if (eq org-refile-use-outline-path 'file)
10622 (push (list (file-name-nondirectory f) f nil nil) tgs))
10623 (save-excursion
10624 (save-restriction
10625 (widen)
10626 (goto-char (point-min))
10627 (while (re-search-forward descre nil t)
10628 (goto-char (setq pos0 (point-at-bol)))
10629 (catch 'next
10630 (when org-refile-target-verify-function
10631 (save-match-data
10632 (or (funcall org-refile-target-verify-function)
10633 (throw 'next t))))
10634 (when (and (looking-at org-complex-heading-regexp)
10635 (not (member (match-string 4) excluded-entries))
10636 (match-string 4))
10637 (setq level (org-reduced-level
10638 (- (match-end 1) (match-beginning 1)))
10639 txt (org-link-display-format (match-string 4))
10640 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10641 re (format org-complex-heading-regexp-format
10642 (regexp-quote (match-string 4))))
10643 (when org-refile-use-outline-path
10644 (setq txt (mapconcat
10645 'org-protect-slash
10646 (append
10647 (if (eq org-refile-use-outline-path
10648 'file)
10649 (list (file-name-nondirectory
10650 (buffer-file-name
10651 (buffer-base-buffer))))
10652 (if (eq org-refile-use-outline-path
10653 'full-file-path)
10654 (list (buffer-file-name
10655 (buffer-base-buffer)))))
10656 (org-get-outline-path fast-path-p
10657 level txt)
10658 (list txt))
10659 "/")))
10660 (push (list txt f re (org-refile-marker (point)))
10661 tgs)))
10662 (when (= (point) pos0)
10663 ;; verification function has not moved point
10664 (goto-char (point-at-eol))))))))
10665 (when org-refile-use-cache
10666 (org-refile-cache-put tgs (buffer-file-name) descre))
10667 (setq targets (append tgs targets))
10668 ))))
10669 (message "Getting targets...done")
10670 (nreverse targets)))
10672 (defun org-protect-slash (s)
10673 (while (string-match "/" s)
10674 (setq s (replace-match "\\" t t s)))
10677 (defvar org-olpa (make-vector 20 nil))
10679 (defun org-get-outline-path (&optional fastp level heading)
10680 "Return the outline path to the current entry, as a list.
10682 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10683 routine which makes outline path derivations for an entire file,
10684 avoiding backtracing. Refile target collection makes use of that."
10685 (if fastp
10686 (progn
10687 (if (> level 19)
10688 (error "Outline path failure, more than 19 levels"))
10689 (loop for i from level upto 19 do
10690 (aset org-olpa i nil))
10691 (prog1
10692 (delq nil (append org-olpa nil))
10693 (aset org-olpa level heading)))
10694 (let (rtn case-fold-search)
10695 (save-excursion
10696 (save-restriction
10697 (widen)
10698 (while (org-up-heading-safe)
10699 (when (looking-at org-complex-heading-regexp)
10700 (push (org-match-string-no-properties 4) rtn)))
10701 rtn)))))
10703 (defun org-format-outline-path (path &optional width prefix)
10704 "Format the outline path PATH for display.
10705 Width is the maximum number of characters that is available.
10706 Prefix is a prefix to be included in the returned string,
10707 such as the file name."
10708 (setq width (or width 79))
10709 (if prefix (setq width (- width (length prefix))))
10710 (if (not path)
10711 (or prefix "")
10712 (let* ((nsteps (length path))
10713 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10714 (maxwidth (if (<= total-width width)
10715 10000 ;; everything fits
10716 ;; we need to shorten the level headings
10717 (/ (- width nsteps) nsteps)))
10718 (org-odd-levels-only nil)
10719 (n 0)
10720 (total (1+ (length prefix))))
10721 (setq maxwidth (max maxwidth 10))
10722 (concat prefix
10723 (mapconcat
10724 (lambda (h)
10725 (setq n (1+ n))
10726 (if (and (= n nsteps) (< maxwidth 10000))
10727 (setq maxwidth (- total-width total)))
10728 (if (< (length h) maxwidth)
10729 (progn (setq total (+ total (length h) 1)) h)
10730 (setq h (substring h 0 (- maxwidth 2))
10731 total (+ total maxwidth 1))
10732 (if (string-match "[ \t]+\\'" h)
10733 (setq h (substring h 0 (match-beginning 0))))
10734 (setq h (concat h "..")))
10735 (org-add-props h nil 'face
10736 (nth (% (1- n) org-n-level-faces)
10737 org-level-faces))
10739 path "/")))))
10741 (defun org-display-outline-path (&optional file current)
10742 "Display the current outline path in the echo area."
10743 (interactive "P")
10744 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10745 (case-fold-search nil)
10746 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10747 (if current (setq path (append path
10748 (save-excursion
10749 (org-back-to-heading t)
10750 (if (looking-at org-complex-heading-regexp)
10751 (list (match-string 4)))))))
10752 (message "%s"
10753 (org-format-outline-path
10754 path
10755 (1- (frame-width))
10756 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10758 (defvar org-refile-history nil
10759 "History for refiling operations.")
10761 (defvar org-after-refile-insert-hook nil
10762 "Hook run after `org-refile' has inserted its stuff at the new location.
10763 Note that this is still *before* the stuff will be removed from
10764 the *old* location.")
10766 (defvar org-capture-last-stored-marker)
10767 (defun org-refile (&optional goto default-buffer rfloc)
10768 "Move the entry or entries at point to another heading.
10769 The list of target headings is compiled using the information in
10770 `org-refile-targets', which see.
10772 At the target location, the entry is filed as a subitem of the target
10773 heading. Depending on `org-reverse-note-order', the new subitem will
10774 either be the first or the last subitem.
10776 If there is an active region, all entries in that region will be moved.
10777 However, the region must fulfill the requirement that the first heading
10778 is the first one sets the top-level of the moved text - at most siblings
10779 below it are allowed.
10781 With prefix arg GOTO, the command will only visit the target location
10782 and not actually move anything.
10784 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10785 go to the location where the last refiling operation has put the subtree.
10786 With a prefix argument of `2', refile to the running clock.
10788 RFLOC can be a refile location obtained in a different way.
10790 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10792 If you are using target caching (see `org-refile-use-cache'),
10793 you have to clear the target cache in order to find new targets.
10794 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10795 prefix argument (`C-u C-u C-u C-c C-w')."
10797 (interactive "P")
10798 (if (member goto '(0 (64)))
10799 (org-refile-cache-clear)
10800 (let* ((cbuf (current-buffer))
10801 (regionp (org-region-active-p))
10802 (region-start (and regionp (region-beginning)))
10803 (region-end (and regionp (region-end)))
10804 (region-length (and regionp (- region-end region-start)))
10805 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10806 pos it nbuf file re level reversed)
10807 (setq last-command nil)
10808 (when regionp
10809 (goto-char region-start)
10810 (or (bolp) (goto-char (point-at-bol)))
10811 (setq region-start (point))
10812 (unless (or (org-kill-is-subtree-p
10813 (buffer-substring region-start region-end))
10814 (prog1 org-refile-active-region-within-subtree
10815 (org-toggle-heading)))
10816 (error "The region is not a (sequence of) subtree(s)")))
10817 (if (equal goto '(16))
10818 (org-refile-goto-last-stored)
10819 (when (or
10820 (and (equal goto 2)
10821 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10822 (prog1
10823 (setq it (list (or org-clock-heading "running clock")
10824 (buffer-file-name
10825 (marker-buffer org-clock-hd-marker))
10827 (marker-position org-clock-hd-marker)))
10828 (setq goto nil)))
10829 (setq it (or rfloc
10830 (let (heading-text)
10831 (save-excursion
10832 (unless goto
10833 (org-back-to-heading t)
10834 (setq heading-text
10835 (nth 4 (org-heading-components))))
10836 (org-refile-get-location
10837 (cond (goto "Goto")
10838 (regionp "Refile region to")
10839 (t (concat "Refile subtree \""
10840 heading-text "\" to")))
10841 default-buffer
10842 (and (not (equal '(4) goto))
10843 org-refile-allow-creating-parent-nodes)
10844 goto))))))
10845 (setq file (nth 1 it)
10846 re (nth 2 it)
10847 pos (nth 3 it))
10848 (if (and (not goto)
10850 (equal (buffer-file-name) file)
10851 (if regionp
10852 (and (>= pos region-start)
10853 (<= pos region-end))
10854 (and (>= pos (point))
10855 (< pos (save-excursion
10856 (org-end-of-subtree t t))))))
10857 (error "Cannot refile to position inside the tree or region"))
10859 (setq nbuf (or (find-buffer-visiting file)
10860 (find-file-noselect file)))
10861 (if goto
10862 (progn
10863 (org-pop-to-buffer-same-window nbuf)
10864 (goto-char pos)
10865 (org-show-context 'org-goto))
10866 (if regionp
10867 (progn
10868 (org-kill-new (buffer-substring region-start region-end))
10869 (org-save-markers-in-region region-start region-end))
10870 (org-copy-subtree 1 nil t))
10871 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10872 (find-file-noselect file)))
10873 (setq reversed (org-notes-order-reversed-p))
10874 (save-excursion
10875 (save-restriction
10876 (widen)
10877 (if pos
10878 (progn
10879 (goto-char pos)
10880 (looking-at org-outline-regexp)
10881 (setq level (org-get-valid-level (funcall outline-level) 1))
10882 (goto-char
10883 (if reversed
10884 (or (outline-next-heading) (point-max))
10885 (or (save-excursion (org-get-next-sibling))
10886 (org-end-of-subtree t t)
10887 (point-max)))))
10888 (setq level 1)
10889 (if (not reversed)
10890 (goto-char (point-max))
10891 (goto-char (point-min))
10892 (or (outline-next-heading) (goto-char (point-max)))))
10893 (if (not (bolp)) (newline))
10894 (org-paste-subtree level)
10895 (when org-log-refile
10896 (org-add-log-setup 'refile nil nil 'findpos
10897 org-log-refile)
10898 (unless (eq org-log-refile 'note)
10899 (save-excursion (org-add-log-note))))
10900 (and org-auto-align-tags
10901 (let ((org-loop-over-headlines-in-active-region nil))
10902 (org-set-tags nil t)))
10903 (with-demoted-errors
10904 (bookmark-set "org-refile-last-stored"))
10905 ;; If we are refiling for capture, make sure that the
10906 ;; last-capture pointers point here
10907 (when (org-bound-and-true-p org-refile-for-capture)
10908 (with-demoted-errors
10909 (bookmark-set "org-capture-last-stored-marker"))
10910 (move-marker org-capture-last-stored-marker (point)))
10911 (if (fboundp 'deactivate-mark) (deactivate-mark))
10912 (run-hooks 'org-after-refile-insert-hook))))
10913 (if regionp
10914 (delete-region (point) (+ (point) region-length))
10915 (org-cut-subtree))
10916 (when (featurep 'org-inlinetask)
10917 (org-inlinetask-remove-END-maybe))
10918 (setq org-markers-to-move nil)
10919 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10921 (defun org-refile-goto-last-stored ()
10922 "Go to the location where the last refile was stored."
10923 (interactive)
10924 (bookmark-jump "org-refile-last-stored")
10925 (message "This is the location of the last refile"))
10927 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10928 no-exclude)
10929 "Prompt the user for a refile location, using PROMPT.
10930 PROMPT should not be suffixed with a colon and a space, because
10931 this function appends the default value from
10932 `org-refile-history' automatically, if that is not empty.
10933 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10934 this is used for the GOTO interface."
10935 (let ((org-refile-targets org-refile-targets)
10936 (org-refile-use-outline-path org-refile-use-outline-path)
10937 excluded-entries)
10938 (when (and (derived-mode-p 'org-mode)
10939 (not org-refile-use-cache)
10940 (not no-exclude))
10941 (org-map-tree
10942 (lambda()
10943 (setq excluded-entries
10944 (append excluded-entries (list (org-get-heading t t)))))))
10945 (setq org-refile-target-table
10946 (org-refile-get-targets default-buffer excluded-entries)))
10947 (unless org-refile-target-table
10948 (error "No refile targets"))
10949 (let* ((prompt (concat prompt
10950 (and (car org-refile-history)
10951 (concat " (default " (car org-refile-history) ")"))
10952 ": "))
10953 (cbuf (current-buffer))
10954 (partial-completion-mode nil)
10955 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10956 (cfunc (if (and org-refile-use-outline-path
10957 org-outline-path-complete-in-steps)
10958 'org-olpath-completing-read
10959 'org-icompleting-read))
10960 (extra (if org-refile-use-outline-path "/" ""))
10961 (filename (and cfn (expand-file-name cfn)))
10962 (tbl (mapcar
10963 (lambda (x)
10964 (if (and (not (member org-refile-use-outline-path
10965 '(file full-file-path)))
10966 (not (equal filename (nth 1 x))))
10967 (cons (concat (car x) extra " ("
10968 (file-name-nondirectory (nth 1 x)) ")")
10969 (cdr x))
10970 (cons (concat (car x) extra) (cdr x))))
10971 org-refile-target-table))
10972 (completion-ignore-case t)
10973 pa answ parent-target child parent old-hist)
10974 (setq old-hist org-refile-history)
10975 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10976 nil 'org-refile-history (car org-refile-history)))
10977 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10978 (org-refile-check-position pa)
10979 (if pa
10980 (progn
10981 (when (or (not org-refile-history)
10982 (not (eq old-hist org-refile-history))
10983 (not (equal (car pa) (car org-refile-history))))
10984 (setq org-refile-history
10985 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10986 org-refile-history
10987 (cdr org-refile-history))))
10988 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10989 (pop org-refile-history)))
10991 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10992 (progn
10993 (setq parent (match-string 1 answ)
10994 child (match-string 2 answ))
10995 (setq parent-target (or (assoc parent tbl)
10996 (assoc (concat parent "/") tbl)))
10997 (when (and parent-target
10998 (or (eq new-nodes t)
10999 (and (eq new-nodes 'confirm)
11000 (y-or-n-p (format "Create new node \"%s\"? "
11001 child)))))
11002 (org-refile-new-child parent-target child)))
11003 (error "Invalid target location")))))
11005 (declare-function org-string-nw-p "org-macs" (s))
11006 (defun org-refile-check-position (refile-pointer)
11007 "Check if the refile pointer matches the headline to which it points."
11008 (let* ((file (nth 1 refile-pointer))
11009 (re (nth 2 refile-pointer))
11010 (pos (nth 3 refile-pointer))
11011 buffer)
11012 (if (and (not (markerp pos)) (not file))
11013 (error "Please save the buffer to a file before refiling")
11014 (when (org-string-nw-p re)
11015 (setq buffer (if (markerp pos)
11016 (marker-buffer pos)
11017 (or (find-buffer-visiting file)
11018 (find-file-noselect file))))
11019 (with-current-buffer buffer
11020 (save-excursion
11021 (save-restriction
11022 (widen)
11023 (goto-char pos)
11024 (beginning-of-line 1)
11025 (unless (org-looking-at-p re)
11026 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11028 (defun org-refile-new-child (parent-target child)
11029 "Use refile target PARENT-TARGET to add new CHILD below it."
11030 (unless parent-target
11031 (error "Cannot find parent for new node"))
11032 (let ((file (nth 1 parent-target))
11033 (pos (nth 3 parent-target))
11034 level)
11035 (with-current-buffer (or (find-buffer-visiting file)
11036 (find-file-noselect file))
11037 (save-excursion
11038 (save-restriction
11039 (widen)
11040 (if pos
11041 (goto-char pos)
11042 (goto-char (point-max))
11043 (if (not (bolp)) (newline)))
11044 (when (looking-at org-outline-regexp)
11045 (setq level (funcall outline-level))
11046 (org-end-of-subtree t t))
11047 (org-back-over-empty-lines)
11048 (insert "\n" (make-string
11049 (if pos (org-get-valid-level level 1) 1) ?*)
11050 " " child "\n")
11051 (beginning-of-line 0)
11052 (list (concat (car parent-target) "/" child) file "" (point)))))))
11054 (defun org-olpath-completing-read (prompt collection &rest args)
11055 "Read an outline path like a file name."
11056 (let ((thetable collection)
11057 (org-completion-use-ido nil) ; does not work with ido.
11058 (org-completion-use-iswitchb nil)) ; or iswitchb
11059 (apply
11060 'org-icompleting-read prompt
11061 (lambda (string predicate &optional flag)
11062 (let (rtn r f (l (length string)))
11063 (cond
11064 ((eq flag nil)
11065 ;; try completion
11066 (try-completion string thetable))
11067 ((eq flag t)
11068 ;; all-completions
11069 (setq rtn (all-completions string thetable predicate))
11070 (mapcar
11071 (lambda (x)
11072 (setq r (substring x l))
11073 (if (string-match " ([^)]*)$" x)
11074 (setq f (match-string 0 x))
11075 (setq f ""))
11076 (if (string-match "/" r)
11077 (concat string (substring r 0 (match-end 0)) f)
11079 rtn))
11080 ((eq flag 'lambda)
11081 ;; exact match?
11082 (assoc string thetable)))))
11083 args)))
11085 ;;;; Dynamic blocks
11087 (defun org-find-dblock (name)
11088 "Find the first dynamic block with name NAME in the buffer.
11089 If not found, stay at current position and return nil."
11090 (let ((case-fold-search t) pos)
11091 (save-excursion
11092 (goto-char (point-min))
11093 (setq pos (and (re-search-forward
11094 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11095 (match-beginning 0))))
11096 (if pos (goto-char pos))
11097 pos))
11099 (defconst org-dblock-start-re
11100 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11101 "Matches the start line of a dynamic block, with parameters.")
11103 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11104 "Matches the end of a dynamic block.")
11106 (defun org-create-dblock (plist)
11107 "Create a dynamic block section, with parameters taken from PLIST.
11108 PLIST must contain a :name entry which is used as name of the block."
11109 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11110 (end-of-line 1)
11111 (newline))
11112 (let ((col (current-column))
11113 (name (plist-get plist :name)))
11114 (insert "#+BEGIN: " name)
11115 (while plist
11116 (if (eq (car plist) :name)
11117 (setq plist (cddr plist))
11118 (insert " " (prin1-to-string (pop plist)))))
11119 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11120 (beginning-of-line -2)))
11122 (defun org-prepare-dblock ()
11123 "Prepare dynamic block for refresh.
11124 This empties the block, puts the cursor at the insert position and returns
11125 the property list including an extra property :name with the block name."
11126 (unless (looking-at org-dblock-start-re)
11127 (error "Not at a dynamic block"))
11128 (let* ((begdel (1+ (match-end 0)))
11129 (name (org-no-properties (match-string 1)))
11130 (params (append (list :name name)
11131 (read (concat "(" (match-string 3) ")")))))
11132 (save-excursion
11133 (beginning-of-line 1)
11134 (skip-chars-forward " \t")
11135 (setq params (plist-put params :indentation-column (current-column))))
11136 (unless (re-search-forward org-dblock-end-re nil t)
11137 (error "Dynamic block not terminated"))
11138 (setq params
11139 (append params
11140 (list :content (buffer-substring
11141 begdel (match-beginning 0)))))
11142 (delete-region begdel (match-beginning 0))
11143 (goto-char begdel)
11144 (open-line 1)
11145 params))
11147 (defun org-map-dblocks (&optional command)
11148 "Apply COMMAND to all dynamic blocks in the current buffer.
11149 If COMMAND is not given, use `org-update-dblock'."
11150 (let ((cmd (or command 'org-update-dblock)))
11151 (save-excursion
11152 (goto-char (point-min))
11153 (while (re-search-forward org-dblock-start-re nil t)
11154 (goto-char (match-beginning 0))
11155 (save-excursion
11156 (condition-case nil
11157 (funcall cmd)
11158 (error (message "Error during update of dynamic block"))))
11159 (unless (re-search-forward org-dblock-end-re nil t)
11160 (error "Dynamic block not terminated"))))))
11162 (defun org-dblock-update (&optional arg)
11163 "User command for updating dynamic blocks.
11164 Update the dynamic block at point. With prefix ARG, update all dynamic
11165 blocks in the buffer."
11166 (interactive "P")
11167 (if arg
11168 (org-update-all-dblocks)
11169 (or (looking-at org-dblock-start-re)
11170 (org-beginning-of-dblock))
11171 (org-update-dblock)))
11173 (defun org-update-dblock ()
11174 "Update the dynamic block at point.
11175 This means to empty the block, parse for parameters and then call
11176 the correct writing function."
11177 (interactive)
11178 (save-window-excursion
11179 (let* ((pos (point))
11180 (line (org-current-line))
11181 (params (org-prepare-dblock))
11182 (name (plist-get params :name))
11183 (indent (plist-get params :indentation-column))
11184 (cmd (intern (concat "org-dblock-write:" name))))
11185 (message "Updating dynamic block `%s' at line %d..." name line)
11186 (funcall cmd params)
11187 (message "Updating dynamic block `%s' at line %d...done" name line)
11188 (goto-char pos)
11189 (when (and indent (> indent 0))
11190 (setq indent (make-string indent ?\ ))
11191 (save-excursion
11192 (org-beginning-of-dblock)
11193 (forward-line 1)
11194 (while (not (looking-at org-dblock-end-re))
11195 (insert indent)
11196 (beginning-of-line 2))
11197 (when (looking-at org-dblock-end-re)
11198 (and (looking-at "[ \t]+")
11199 (replace-match ""))
11200 (insert indent)))))))
11202 (defun org-beginning-of-dblock ()
11203 "Find the beginning of the dynamic block at point.
11204 Error if there is no such block at point."
11205 (let ((pos (point))
11206 beg)
11207 (end-of-line 1)
11208 (if (and (re-search-backward org-dblock-start-re nil t)
11209 (setq beg (match-beginning 0))
11210 (re-search-forward org-dblock-end-re nil t)
11211 (> (match-end 0) pos))
11212 (goto-char beg)
11213 (goto-char pos)
11214 (error "Not in a dynamic block"))))
11216 (defun org-update-all-dblocks ()
11217 "Update all dynamic blocks in the buffer.
11218 This function can be used in a hook."
11219 (interactive)
11220 (when (derived-mode-p 'org-mode)
11221 (org-map-dblocks 'org-update-dblock)))
11224 ;;;; Completion
11226 (defconst org-additional-option-like-keywords
11227 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11228 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11229 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11230 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11231 "BEGIN:" "END:"
11232 "ORGTBL" "TBLFM:" "TBLNAME:"
11233 "BEGIN_EXAMPLE" "END_EXAMPLE"
11234 "BEGIN_VERBATIM" "END_VERBATIM"
11235 "BEGIN_QUOTE" "END_QUOTE"
11236 "BEGIN_VERSE" "END_VERSE"
11237 "BEGIN_CENTER" "END_CENTER"
11238 "BEGIN_SRC" "END_SRC"
11239 "BEGIN_RESULT" "END_RESULT"
11240 "BEGIN_lstlisting" "END_lstlisting"
11241 "NAME:" "RESULTS:"
11242 "HEADER:" "HEADERS:"
11243 "COLUMNS:" "PROPERTY:"
11244 "CAPTION:" "LABEL:"
11245 "SETUPFILE:"
11246 "INCLUDE:" "INDEX:"
11247 "BIND:"
11248 "MACRO:"))
11250 (defconst org-options-keywords
11251 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11252 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11253 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11254 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11255 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11256 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11257 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11259 (defconst org-additional-option-like-keywords-for-flyspell
11260 (delete-dups
11261 (split-string
11262 (mapconcat (lambda(k)
11263 (replace-regexp-in-string
11264 "_\\|:" " "
11265 (concat k " " (downcase k) " " (upcase k))))
11266 (append org-options-keywords org-additional-option-like-keywords)
11267 " ")
11268 " +" t)))
11270 (defcustom org-structure-template-alist
11271 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11272 "<src lang=\"?\">\n\n</src>")
11273 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11274 "<example>\n?\n</example>")
11275 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11276 "<quote>\n?\n</quote>")
11277 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11278 "<verse>\n?\n</verse>")
11279 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11280 "<verbatim>\n?\n</verbatim>")
11281 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11282 "<center>\n?\n</center>")
11283 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11284 "<literal style=\"latex\">\n?\n</literal>")
11285 ("L" "#+LaTeX: "
11286 "<literal style=\"latex\">?</literal>")
11287 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11288 "<literal style=\"html\">\n?\n</literal>")
11289 ("H" "#+HTML: "
11290 "<literal style=\"html\">?</literal>")
11291 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11292 ("A" "#+ASCII: ")
11293 ("i" "#+INDEX: ?"
11294 "#+INDEX: ?")
11295 ("I" "#+INCLUDE: %file ?"
11296 "<include file=%file markup=\"?\">"))
11297 "Structure completion elements.
11298 This is a list of abbreviation keys and values. The value gets inserted
11299 if you type `<' followed by the key and then press the completion key,
11300 usually `M-TAB'. %file will be replaced by a file name after prompting
11301 for the file using completion. The cursor will be placed at the position
11302 of the `?` in the template.
11303 There are two templates for each key, the first uses the original Org syntax,
11304 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11305 the default when the /org-mtags.el/ module has been loaded. See also the
11306 variable `org-mtags-prefer-muse-templates'."
11307 :group 'org-completion
11308 :type '(repeat
11309 (string :tag "Key")
11310 (string :tag "Template")
11311 (string :tag "Muse Template")))
11313 (defun org-try-structure-completion ()
11314 "Try to complete a structure template before point.
11315 This looks for strings like \"<e\" on an otherwise empty line and
11316 expands them."
11317 (let ((l (buffer-substring (point-at-bol) (point)))
11319 (when (and (looking-at "[ \t]*$")
11320 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11321 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11322 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11323 (match-beginning 1)) a)
11324 t)))
11326 (defun org-complete-expand-structure-template (start cell)
11327 "Expand a structure template."
11328 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11329 (rpl (nth (if musep 2 1) cell))
11330 (ind ""))
11331 (delete-region start (point))
11332 (when (string-match "\\`#\\+" rpl)
11333 (cond
11334 ((bolp))
11335 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11336 (setq ind (buffer-substring (point-at-bol) (point))))
11337 (t (newline))))
11338 (setq start (point))
11339 (if (string-match "%file" rpl)
11340 (setq rpl (replace-match
11341 (concat
11342 "\""
11343 (save-match-data
11344 (abbreviate-file-name (read-file-name "Include file: ")))
11345 "\"")
11346 t t rpl)))
11347 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11348 (concat "\n" ind)))
11349 (insert rpl)
11350 (if (re-search-backward "\\?" start t) (delete-char 1))))
11352 ;;;; TODO, DEADLINE, Comments
11354 (defun org-toggle-comment ()
11355 "Change the COMMENT state of an entry."
11356 (interactive)
11357 (save-excursion
11358 (org-back-to-heading)
11359 (let (case-fold-search)
11360 (cond
11361 ((looking-at (format org-heading-keyword-regexp-format
11362 org-comment-string))
11363 (goto-char (match-end 1))
11364 (looking-at (concat " +" org-comment-string))
11365 (replace-match "" t t)
11366 (when (eolp) (insert " ")))
11367 ((looking-at org-outline-regexp)
11368 (goto-char (match-end 0))
11369 (insert org-comment-string " "))))))
11371 (defvar org-last-todo-state-is-todo nil
11372 "This is non-nil when the last TODO state change led to a TODO state.
11373 If the last change removed the TODO tag or switched to DONE, then
11374 this is nil.")
11376 (defvar org-setting-tags nil) ; dynamically skipped
11378 (defvar org-todo-setup-filter-hook nil
11379 "Hook for functions that pre-filter todo specs.
11380 Each function takes a todo spec and returns either nil or the spec
11381 transformed into canonical form." )
11383 (defvar org-todo-get-default-hook nil
11384 "Hook for functions that get a default item for todo.
11385 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11386 nil or a string to be used for the todo mark." )
11388 (defvar org-agenda-headline-snapshot-before-repeat)
11390 (defun org-current-effective-time ()
11391 "Return current time adjusted for `org-extend-today-until' variable."
11392 (let* ((ct (org-current-time))
11393 (dct (decode-time ct))
11394 (ct1
11395 (if (and org-use-effective-time
11396 (< (nth 2 dct) org-extend-today-until))
11397 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11398 ct)))
11399 ct1))
11401 (defun org-todo-yesterday (&optional arg)
11402 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11403 (interactive "P")
11404 (if (eq major-mode 'org-agenda-mode)
11405 (apply 'org-agenda-todo-yesterday arg)
11406 (let* ((hour (third (decode-time
11407 (org-current-time))))
11408 (org-extend-today-until (1+ hour)))
11409 (org-todo arg))))
11411 (defun org-todo (&optional arg)
11412 "Change the TODO state of an item.
11413 The state of an item is given by a keyword at the start of the heading,
11414 like
11415 *** TODO Write paper
11416 *** DONE Call mom
11418 The different keywords are specified in the variable `org-todo-keywords'.
11419 By default the available states are \"TODO\" and \"DONE\".
11420 So for this example: when the item starts with TODO, it is changed to DONE.
11421 When it starts with DONE, the DONE is removed. And when neither TODO nor
11422 DONE are present, add TODO at the beginning of the heading.
11424 With \\[universal-argument] prefix arg, use completion to determine the new \
11425 state.
11426 With numeric prefix arg, switch to that state.
11427 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11428 keywords (nextset).
11429 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11430 With a numeric prefix arg of 0, inhibit note taking for the change.
11432 For calling through lisp, arg is also interpreted in the following way:
11433 'none -> empty state
11434 \"\"(empty string) -> switch to empty state
11435 'done -> switch to DONE
11436 'nextset -> switch to the next set of keywords
11437 'previousset -> switch to the previous set of keywords
11438 \"WAITING\" -> switch to the specified keyword, but only if it
11439 really is a member of `org-todo-keywords'."
11440 (interactive "P")
11441 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11442 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11443 'region-start-level 'region))
11444 org-loop-over-headlines-in-active-region)
11445 (org-map-entries
11446 `(org-todo ,arg)
11447 org-loop-over-headlines-in-active-region
11448 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11449 (if (equal arg '(16)) (setq arg 'nextset))
11450 (let ((org-blocker-hook org-blocker-hook)
11451 commentp
11452 case-fold-search)
11453 (when (equal arg '(64))
11454 (setq arg nil org-blocker-hook nil))
11455 (when (and org-blocker-hook
11456 (or org-inhibit-blocking
11457 (org-entry-get nil "NOBLOCKING")))
11458 (setq org-blocker-hook nil))
11459 (save-excursion
11460 (catch 'exit
11461 (org-back-to-heading t)
11462 (when (looking-at (concat "^\\*+ " org-comment-string))
11463 (org-toggle-comment)
11464 (setq commentp t))
11465 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11466 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11467 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11468 (let* ((match-data (match-data))
11469 (startpos (point-at-bol))
11470 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11471 (org-log-done org-log-done)
11472 (org-log-repeat org-log-repeat)
11473 (org-todo-log-states org-todo-log-states)
11474 (org-inhibit-logging
11475 (if (equal arg 0)
11476 (progn (setq arg nil) 'note) org-inhibit-logging))
11477 (this (match-string 1))
11478 (hl-pos (match-beginning 0))
11479 (head (org-get-todo-sequence-head this))
11480 (ass (assoc head org-todo-kwd-alist))
11481 (interpret (nth 1 ass))
11482 (done-word (nth 3 ass))
11483 (final-done-word (nth 4 ass))
11484 (org-last-state (or this ""))
11485 (completion-ignore-case t)
11486 (member (member this org-todo-keywords-1))
11487 (tail (cdr member))
11488 (org-state (cond
11489 ((and org-todo-key-trigger
11490 (or (and (equal arg '(4))
11491 (eq org-use-fast-todo-selection 'prefix))
11492 (and (not arg) org-use-fast-todo-selection
11493 (not (eq org-use-fast-todo-selection
11494 'prefix)))))
11495 ;; Use fast selection
11496 (org-fast-todo-selection))
11497 ((and (equal arg '(4))
11498 (or (not org-use-fast-todo-selection)
11499 (not org-todo-key-trigger)))
11500 ;; Read a state with completion
11501 (org-icompleting-read
11502 "State: " (mapcar (lambda(x) (list x))
11503 org-todo-keywords-1)
11504 nil t))
11505 ((eq arg 'right)
11506 (if this
11507 (if tail (car tail) nil)
11508 (car org-todo-keywords-1)))
11509 ((eq arg 'left)
11510 (if (equal member org-todo-keywords-1)
11512 (if this
11513 (nth (- (length org-todo-keywords-1)
11514 (length tail) 2)
11515 org-todo-keywords-1)
11516 (org-last org-todo-keywords-1))))
11517 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11518 (setq arg nil))) ; hack to fall back to cycling
11519 (arg
11520 ;; user or caller requests a specific state
11521 (cond
11522 ((equal arg "") nil)
11523 ((eq arg 'none) nil)
11524 ((eq arg 'done) (or done-word (car org-done-keywords)))
11525 ((eq arg 'nextset)
11526 (or (car (cdr (member head org-todo-heads)))
11527 (car org-todo-heads)))
11528 ((eq arg 'previousset)
11529 (let ((org-todo-heads (reverse org-todo-heads)))
11530 (or (car (cdr (member head org-todo-heads)))
11531 (car org-todo-heads))))
11532 ((car (member arg org-todo-keywords-1)))
11533 ((stringp arg)
11534 (error "State `%s' not valid in this file" arg))
11535 ((nth (1- (prefix-numeric-value arg))
11536 org-todo-keywords-1))))
11537 ((null member) (or head (car org-todo-keywords-1)))
11538 ((equal this final-done-word) nil) ;; -> make empty
11539 ((null tail) nil) ;; -> first entry
11540 ((memq interpret '(type priority))
11541 (if (eq this-command last-command)
11542 (car tail)
11543 (if (> (length tail) 0)
11544 (or done-word (car org-done-keywords))
11545 nil)))
11547 (car tail))))
11548 (org-state (or
11549 (run-hook-with-args-until-success
11550 'org-todo-get-default-hook org-state org-last-state)
11551 org-state))
11552 (next (if org-state (concat " " org-state " ") " "))
11553 (change-plist (list :type 'todo-state-change :from this :to org-state
11554 :position startpos))
11555 dolog now-done-p)
11556 (when org-blocker-hook
11557 (setq org-last-todo-state-is-todo
11558 (not (member this org-done-keywords)))
11559 (unless (save-excursion
11560 (save-match-data
11561 (org-with-wide-buffer
11562 (run-hook-with-args-until-failure
11563 'org-blocker-hook change-plist))))
11564 (if (org-called-interactively-p 'interactive)
11565 (error "TODO state change from %s to %s blocked" this org-state)
11566 ;; fail silently
11567 (message "TODO state change from %s to %s blocked" this org-state)
11568 (throw 'exit nil))))
11569 (store-match-data match-data)
11570 (replace-match next t t)
11571 (unless (pos-visible-in-window-p hl-pos)
11572 (message "TODO state changed to %s" (org-trim next)))
11573 (unless head
11574 (setq head (org-get-todo-sequence-head org-state)
11575 ass (assoc head org-todo-kwd-alist)
11576 interpret (nth 1 ass)
11577 done-word (nth 3 ass)
11578 final-done-word (nth 4 ass)))
11579 (when (memq arg '(nextset previousset))
11580 (message "Keyword-Set %d/%d: %s"
11581 (- (length org-todo-sets) -1
11582 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11583 (length org-todo-sets)
11584 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11585 (setq org-last-todo-state-is-todo
11586 (not (member org-state org-done-keywords)))
11587 (setq now-done-p (and (member org-state org-done-keywords)
11588 (not (member this org-done-keywords))))
11589 (and logging (org-local-logging logging))
11590 (when (and (or org-todo-log-states org-log-done)
11591 (not (eq org-inhibit-logging t))
11592 (not (memq arg '(nextset previousset))))
11593 ;; we need to look at recording a time and note
11594 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11595 (nth 2 (assoc this org-todo-log-states))))
11596 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11597 (setq dolog 'time))
11598 (when (and org-state
11599 (member org-state org-not-done-keywords)
11600 (not (member this org-not-done-keywords)))
11601 ;; This is now a todo state and was not one before
11602 ;; If there was a CLOSED time stamp, get rid of it.
11603 (org-add-planning-info nil nil 'closed))
11604 (when (and now-done-p org-log-done)
11605 ;; It is now done, and it was not done before
11606 (org-add-planning-info 'closed (org-current-effective-time))
11607 (if (and (not dolog) (eq 'note org-log-done))
11608 (org-add-log-setup 'done org-state this 'findpos 'note)))
11609 (when (and org-state dolog)
11610 ;; This is a non-nil state, and we need to log it
11611 (org-add-log-setup 'state org-state this 'findpos dolog)))
11612 ;; Fixup tag positioning
11613 (org-todo-trigger-tag-changes org-state)
11614 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11615 (when org-provide-todo-statistics
11616 (org-update-parent-todo-statistics))
11617 (run-hooks 'org-after-todo-state-change-hook)
11618 (if (and arg (not (member org-state org-done-keywords)))
11619 (setq head (org-get-todo-sequence-head org-state)))
11620 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11621 ;; Do we need to trigger a repeat?
11622 (when now-done-p
11623 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11624 ;; This is for the agenda, take a snapshot of the headline.
11625 (save-match-data
11626 (setq org-agenda-headline-snapshot-before-repeat
11627 (org-get-heading))))
11628 (org-auto-repeat-maybe org-state))
11629 ;; Fixup cursor location if close to the keyword
11630 (if (and (outline-on-heading-p)
11631 (not (bolp))
11632 (save-excursion (beginning-of-line 1)
11633 (looking-at org-todo-line-regexp))
11634 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11635 (progn
11636 (goto-char (or (match-end 2) (match-end 1)))
11637 (and (looking-at " ") (just-one-space))))
11638 (when org-trigger-hook
11639 (save-excursion
11640 (run-hook-with-args 'org-trigger-hook change-plist)))
11641 (when commentp (org-toggle-comment))))))))
11643 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11644 "Block turning an entry into a TODO, using the hierarchy.
11645 This checks whether the current task should be blocked from state
11646 changes. Such blocking occurs when:
11648 1. The task has children which are not all in a completed state.
11650 2. A task has a parent with the property :ORDERED:, and there
11651 are siblings prior to the current task with incomplete
11652 status.
11654 3. The parent of the task is blocked because it has siblings that should
11655 be done first, or is child of a block grandparent TODO entry."
11657 (if (not org-enforce-todo-dependencies)
11658 t ; if locally turned off don't block
11659 (catch 'dont-block
11660 ;; If this is not a todo state change, or if this entry is already DONE,
11661 ;; do not block
11662 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11663 (member (plist-get change-plist :from)
11664 (cons 'done org-done-keywords))
11665 (member (plist-get change-plist :to)
11666 (cons 'todo org-not-done-keywords))
11667 (not (plist-get change-plist :to)))
11668 (throw 'dont-block t))
11669 ;; If this task has children, and any are undone, it's blocked
11670 (save-excursion
11671 (org-back-to-heading t)
11672 (let ((this-level (funcall outline-level)))
11673 (outline-next-heading)
11674 (let ((child-level (funcall outline-level)))
11675 (while (and (not (eobp))
11676 (> child-level this-level))
11677 ;; this todo has children, check whether they are all
11678 ;; completed
11679 (if (and (not (org-entry-is-done-p))
11680 (org-entry-is-todo-p))
11681 (throw 'dont-block nil))
11682 (outline-next-heading)
11683 (setq child-level (funcall outline-level))))))
11684 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11685 ;; any previous siblings are undone, it's blocked
11686 (save-excursion
11687 (org-back-to-heading t)
11688 (let* ((pos (point))
11689 (parent-pos (and (org-up-heading-safe) (point))))
11690 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11691 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11692 (forward-line 1)
11693 (re-search-forward org-not-done-heading-regexp pos t))
11694 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11695 ;; Search further up the hierarchy, to see if an ancestor is blocked
11696 (while t
11697 (goto-char parent-pos)
11698 (if (not (looking-at org-not-done-heading-regexp))
11699 (throw 'dont-block t)) ; do not block, parent is not a TODO
11700 (setq pos (point))
11701 (setq parent-pos (and (org-up-heading-safe) (point)))
11702 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11703 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11704 (forward-line 1)
11705 (re-search-forward org-not-done-heading-regexp pos t))
11706 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11708 (defcustom org-track-ordered-property-with-tag nil
11709 "Should the ORDERED property also be shown as a tag?
11710 The ORDERED property decides if an entry should require subtasks to be
11711 completed in sequence. Since a property is not very visible, setting
11712 this option means that toggling the ORDERED property with the command
11713 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11714 not relevant for the behavior, but it makes things more visible.
11716 Note that toggling the tag with tags commands will not change the property
11717 and therefore not influence behavior!
11719 This can be t, meaning the tag ORDERED should be used, It can also be a
11720 string to select a different tag for this task."
11721 :group 'org-todo
11722 :type '(choice
11723 (const :tag "No tracking" nil)
11724 (const :tag "Track with ORDERED tag" t)
11725 (string :tag "Use other tag")))
11727 (defun org-toggle-ordered-property ()
11728 "Toggle the ORDERED property of the current entry.
11729 For better visibility, you can track the value of this property with a tag.
11730 See variable `org-track-ordered-property-with-tag'."
11731 (interactive)
11732 (let* ((t1 org-track-ordered-property-with-tag)
11733 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11734 (save-excursion
11735 (org-back-to-heading)
11736 (if (org-entry-get nil "ORDERED")
11737 (progn
11738 (org-delete-property "ORDERED")
11739 (and tag (org-toggle-tag tag 'off))
11740 (message "Subtasks can be completed in arbitrary order"))
11741 (org-entry-put nil "ORDERED" "t")
11742 (and tag (org-toggle-tag tag 'on))
11743 (message "Subtasks must be completed in sequence")))))
11745 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11746 (defun org-block-todo-from-checkboxes (change-plist)
11747 "Block turning an entry into a TODO, using checkboxes.
11748 This checks whether the current task should be blocked from state
11749 changes because there are unchecked boxes in this entry."
11750 (if (not org-enforce-todo-checkbox-dependencies)
11751 t ; if locally turned off don't block
11752 (catch 'dont-block
11753 ;; If this is not a todo state change, or if this entry is already DONE,
11754 ;; do not block
11755 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11756 (member (plist-get change-plist :from)
11757 (cons 'done org-done-keywords))
11758 (member (plist-get change-plist :to)
11759 (cons 'todo org-not-done-keywords))
11760 (not (plist-get change-plist :to)))
11761 (throw 'dont-block t))
11762 ;; If this task has checkboxes that are not checked, it's blocked
11763 (save-excursion
11764 (org-back-to-heading t)
11765 (let ((beg (point)) end)
11766 (outline-next-heading)
11767 (setq end (point))
11768 (goto-char beg)
11769 (if (org-list-search-forward
11770 (concat (org-item-beginning-re)
11771 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11772 "\\[[- ]\\]")
11773 end t)
11774 (progn
11775 (if (boundp 'org-blocked-by-checkboxes)
11776 (setq org-blocked-by-checkboxes t))
11777 (throw 'dont-block nil)))))
11778 t))) ; do not block
11780 (defun org-entry-blocked-p ()
11781 "Is the current entry blocked?"
11782 (org-with-buffer-modified-unmodified
11783 (if (org-entry-get nil "NOBLOCKING")
11784 nil ;; Never block this entry
11785 (not
11786 (run-hook-with-args-until-failure
11787 'org-blocker-hook
11788 (list :type 'todo-state-change
11789 :position (point)
11790 :from 'todo
11791 :to 'done))))))
11793 (defun org-update-statistics-cookies (all)
11794 "Update the statistics cookie, either from TODO or from checkboxes.
11795 This should be called with the cursor in a line with a statistics cookie."
11796 (interactive "P")
11797 (if all
11798 (progn
11799 (org-update-checkbox-count 'all)
11800 (org-map-entries 'org-update-parent-todo-statistics))
11801 (if (not (org-at-heading-p))
11802 (org-update-checkbox-count)
11803 (let ((pos (point-marker))
11804 end l1 l2)
11805 (ignore-errors (org-back-to-heading t))
11806 (if (not (org-at-heading-p))
11807 (org-update-checkbox-count)
11808 (setq l1 (org-outline-level))
11809 (setq end (save-excursion
11810 (outline-next-heading)
11811 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11812 (point)))
11813 (if (and (save-excursion
11814 (re-search-forward
11815 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11816 (not (save-excursion (re-search-forward
11817 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11818 (org-update-checkbox-count)
11819 (if (and l2 (> l2 l1))
11820 (progn
11821 (goto-char end)
11822 (org-update-parent-todo-statistics))
11823 (goto-char pos)
11824 (beginning-of-line 1)
11825 (while (re-search-forward
11826 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11827 (point-at-eol) t)
11828 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11829 (goto-char pos)
11830 (move-marker pos nil)))))
11832 (defvar org-entry-property-inherited-from) ;; defined below
11833 (defun org-update-parent-todo-statistics ()
11834 "Update any statistics cookie in the parent of the current headline.
11835 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11836 the entire subtree and this will travel up the hierarchy and update
11837 statistics everywhere."
11838 (let* ((prop (save-excursion (org-up-heading-safe)
11839 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11840 (recursive (or (not org-hierarchical-todo-statistics)
11841 (and prop (string-match "\\<recursive\\>" prop))))
11842 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11844 (first t)
11845 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11846 level ltoggle l1 new ndel
11847 (cnt-all 0) (cnt-done 0) is-percent kwd
11848 checkbox-beg ov ovs ove cookie-present)
11849 (catch 'exit
11850 (save-excursion
11851 (beginning-of-line 1)
11852 (setq ltoggle (funcall outline-level))
11853 ;; Three situations are to consider:
11855 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11856 ;; to the top-level ancestor on the headline;
11858 ;; 2. If parent has "recursive" property, repeat up to the
11859 ;; headline setting that property, taking inheritance into
11860 ;; account;
11862 ;; 3. Else, move up to direct parent and proceed only once.
11863 (while (and (setq level (org-up-heading-safe))
11864 (or recursive first)
11865 (>= (point) lim))
11866 (setq first nil cookie-present nil)
11867 (unless (and level
11868 (not (string-match
11869 "\\<checkbox\\>"
11870 (downcase (or (org-entry-get nil "COOKIE_DATA")
11871 "")))))
11872 (throw 'exit nil))
11873 (while (re-search-forward box-re (point-at-eol) t)
11874 (setq cnt-all 0 cnt-done 0 cookie-present t)
11875 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11876 (save-match-data
11877 (unless (outline-next-heading) (throw 'exit nil))
11878 (while (and (looking-at org-complex-heading-regexp)
11879 (> (setq l1 (length (match-string 1))) level))
11880 (setq kwd (and (or recursive (= l1 ltoggle))
11881 (match-string 2)))
11882 (if (or (eq org-provide-todo-statistics 'all-headlines)
11883 (and (listp org-provide-todo-statistics)
11884 (or (member kwd org-provide-todo-statistics)
11885 (member kwd org-done-keywords))))
11886 (setq cnt-all (1+ cnt-all))
11887 (if (eq org-provide-todo-statistics t)
11888 (and kwd (setq cnt-all (1+ cnt-all)))))
11889 (and (member kwd org-done-keywords)
11890 (setq cnt-done (1+ cnt-done)))
11891 (outline-next-heading)))
11892 (setq new
11893 (if is-percent
11894 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11895 (format "[%d/%d]" cnt-done cnt-all))
11896 ndel (- (match-end 0) checkbox-beg))
11897 ;; handle overlays when updating cookie from column view
11898 (when (setq ov (car (overlays-at checkbox-beg)))
11899 (setq ovs (overlay-start ov) ove (overlay-end ov))
11900 (delete-overlay ov))
11901 (goto-char checkbox-beg)
11902 (insert new)
11903 (delete-region (point) (+ (point) ndel))
11904 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11905 (when ov (move-overlay ov ovs ove)))
11906 (when cookie-present
11907 (run-hook-with-args 'org-after-todo-statistics-hook
11908 cnt-done (- cnt-all cnt-done))))))
11909 (run-hooks 'org-todo-statistics-hook)))
11911 (defvar org-after-todo-statistics-hook nil
11912 "Hook that is called after a TODO statistics cookie has been updated.
11913 Each function is called with two arguments: the number of not-done entries
11914 and the number of done entries.
11916 For example, the following function, when added to this hook, will switch
11917 an entry to DONE when all children are done, and back to TODO when new
11918 entries are set to a TODO status. Note that this hook is only called
11919 when there is a statistics cookie in the headline!
11921 (defun org-summary-todo (n-done n-not-done)
11922 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11923 (let (org-log-done org-log-states) ; turn off logging
11924 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11927 (defvar org-todo-statistics-hook nil
11928 "Hook that is run whenever Org thinks TODO statistics should be updated.
11929 This hook runs even if there is no statistics cookie present, in which case
11930 `org-after-todo-statistics-hook' would not run.")
11932 (defun org-todo-trigger-tag-changes (state)
11933 "Apply the changes defined in `org-todo-state-tags-triggers'."
11934 (let ((l org-todo-state-tags-triggers)
11935 changes)
11936 (when (or (not state) (equal state ""))
11937 (setq changes (append changes (cdr (assoc "" l)))))
11938 (when (and (stringp state) (> (length state) 0))
11939 (setq changes (append changes (cdr (assoc state l)))))
11940 (when (member state org-not-done-keywords)
11941 (setq changes (append changes (cdr (assoc 'todo l)))))
11942 (when (member state org-done-keywords)
11943 (setq changes (append changes (cdr (assoc 'done l)))))
11944 (dolist (c changes)
11945 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11947 (defun org-local-logging (value)
11948 "Get logging settings from a property VALUE."
11949 (let* (words w a)
11950 ;; directly set the variables, they are already local.
11951 (setq org-log-done nil
11952 org-log-repeat nil
11953 org-todo-log-states nil)
11954 (setq words (org-split-string value))
11955 (while (setq w (pop words))
11956 (cond
11957 ((setq a (assoc w org-startup-options))
11958 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11959 (set (nth 1 a) (nth 2 a))))
11960 ((setq a (org-extract-log-state-settings w))
11961 (and (member (car a) org-todo-keywords-1)
11962 (push a org-todo-log-states)))))))
11964 (defun org-get-todo-sequence-head (kwd)
11965 "Return the head of the TODO sequence to which KWD belongs.
11966 If KWD is not set, check if there is a text property remembering the
11967 right sequence."
11968 (let (p)
11969 (cond
11970 ((not kwd)
11971 (or (get-text-property (point-at-bol) 'org-todo-head)
11972 (progn
11973 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11974 nil (point-at-eol)))
11975 (get-text-property p 'org-todo-head))))
11976 ((not (member kwd org-todo-keywords-1))
11977 (car org-todo-keywords-1))
11978 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11980 (defun org-fast-todo-selection ()
11981 "Fast TODO keyword selection with single keys.
11982 Returns the new TODO keyword, or nil if no state change should occur."
11983 (let* ((fulltable org-todo-key-alist)
11984 (done-keywords org-done-keywords) ;; needed for the faces.
11985 (maxlen (apply 'max (mapcar
11986 (lambda (x)
11987 (if (stringp (car x)) (string-width (car x)) 0))
11988 fulltable)))
11989 (expert nil)
11990 (fwidth (+ maxlen 3 1 3))
11991 (ncol (/ (- (window-width) 4) fwidth))
11992 tg cnt e c tbl
11993 groups ingroup)
11994 (save-excursion
11995 (save-window-excursion
11996 (if expert
11997 (set-buffer (get-buffer-create " *Org todo*"))
11998 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11999 (erase-buffer)
12000 (org-set-local 'org-done-keywords done-keywords)
12001 (setq tbl fulltable cnt 0)
12002 (while (setq e (pop tbl))
12003 (cond
12004 ((equal e '(:startgroup))
12005 (push '() groups) (setq ingroup t)
12006 (when (not (= cnt 0))
12007 (setq cnt 0)
12008 (insert "\n"))
12009 (insert "{ "))
12010 ((equal e '(:endgroup))
12011 (setq ingroup nil cnt 0)
12012 (insert "}\n"))
12013 ((equal e '(:newline))
12014 (when (not (= cnt 0))
12015 (setq cnt 0)
12016 (insert "\n")
12017 (setq e (car tbl))
12018 (while (equal (car tbl) '(:newline))
12019 (insert "\n")
12020 (setq tbl (cdr tbl)))))
12022 (setq tg (car e) c (cdr e))
12023 (if ingroup (push tg (car groups)))
12024 (setq tg (org-add-props tg nil 'face
12025 (org-get-todo-face tg)))
12026 (if (and (= cnt 0) (not ingroup)) (insert " "))
12027 (insert "[" c "] " tg (make-string
12028 (- fwidth 4 (length tg)) ?\ ))
12029 (when (= (setq cnt (1+ cnt)) ncol)
12030 (insert "\n")
12031 (if ingroup (insert " "))
12032 (setq cnt 0)))))
12033 (insert "\n")
12034 (goto-char (point-min))
12035 (if (not expert) (org-fit-window-to-buffer))
12036 (message "[a-z..]:Set [SPC]:clear")
12037 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12038 (cond
12039 ((or (= c ?\C-g)
12040 (and (= c ?q) (not (rassoc c fulltable))))
12041 (setq quit-flag t))
12042 ((= c ?\ ) nil)
12043 ((setq e (rassoc c fulltable) tg (car e))
12045 (t (setq quit-flag t)))))))
12047 (defun org-entry-is-todo-p ()
12048 (member (org-get-todo-state) org-not-done-keywords))
12050 (defun org-entry-is-done-p ()
12051 (member (org-get-todo-state) org-done-keywords))
12053 (defun org-get-todo-state ()
12054 (save-excursion
12055 (org-back-to-heading t)
12056 (and (looking-at org-todo-line-regexp)
12057 (match-end 2)
12058 (match-string 2))))
12060 (defun org-at-date-range-p (&optional inactive-ok)
12061 "Is the cursor inside a date range?"
12062 (interactive)
12063 (save-excursion
12064 (catch 'exit
12065 (let ((pos (point)))
12066 (skip-chars-backward "^[<\r\n")
12067 (skip-chars-backward "<[")
12068 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12069 (>= (match-end 0) pos)
12070 (throw 'exit t))
12071 (skip-chars-backward "^<[\r\n")
12072 (skip-chars-backward "<[")
12073 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12074 (>= (match-end 0) pos)
12075 (throw 'exit t)))
12076 nil)))
12078 (defun org-get-repeat (&optional tagline)
12079 "Check if there is a deadline/schedule with repeater in this entry."
12080 (save-match-data
12081 (save-excursion
12082 (org-back-to-heading t)
12083 (and (re-search-forward (if tagline
12084 (concat tagline "\\s-*" org-repeat-re)
12085 org-repeat-re)
12086 (org-entry-end-position) t)
12087 (match-string-no-properties 1)))))
12089 (defvar org-last-changed-timestamp)
12090 (defvar org-last-inserted-timestamp)
12091 (defvar org-log-post-message)
12092 (defvar org-log-note-purpose)
12093 (defvar org-log-note-how)
12094 (defvar org-log-note-extra)
12095 (defun org-auto-repeat-maybe (done-word)
12096 "Check if the current headline contains a repeated deadline/schedule.
12097 If yes, set TODO state back to what it was and change the base date
12098 of repeating deadline/scheduled time stamps to new date.
12099 This function is run automatically after each state change to a DONE state."
12100 ;; last-state is dynamically scoped into this function
12101 (let* ((repeat (org-get-repeat))
12102 (aa (assoc org-last-state org-todo-kwd-alist))
12103 (interpret (nth 1 aa))
12104 (head (nth 2 aa))
12105 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12106 (msg "Entry repeats: ")
12107 (org-log-done nil)
12108 (org-todo-log-states nil)
12109 re type n what ts time to-state)
12110 (when repeat
12111 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12112 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12113 org-todo-repeat-to-state))
12114 (unless (and to-state (member to-state org-todo-keywords-1))
12115 (setq to-state (if (eq interpret 'type) org-last-state head)))
12116 (org-todo to-state)
12117 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12118 (org-entry-put nil "LAST_REPEAT" (format-time-string
12119 (org-time-stamp-format t t))))
12120 (when org-log-repeat
12121 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12122 (memq 'org-add-log-note post-command-hook))
12123 ;; OK, we are already setup for some record
12124 (if (eq org-log-repeat 'note)
12125 ;; make sure we take a note, not only a time stamp
12126 (setq org-log-note-how 'note))
12127 ;; Set up for taking a record
12128 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12129 org-last-state
12130 'findpos org-log-repeat)))
12131 (org-back-to-heading t)
12132 (org-add-planning-info nil nil 'closed)
12133 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12134 org-deadline-time-regexp "\\)\\|\\("
12135 org-ts-regexp "\\)"))
12136 (while (re-search-forward
12137 re (save-excursion (outline-next-heading) (point)) t)
12138 (setq type (if (match-end 1) org-scheduled-string
12139 (if (match-end 3) org-deadline-string "Plain:"))
12140 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12141 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12142 (setq n (string-to-number (match-string 2 ts))
12143 what (match-string 3 ts))
12144 (if (equal what "w") (setq n (* n 7) what "d"))
12145 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12146 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12147 ;; Preparation, see if we need to modify the start date for the change
12148 (when (match-end 1)
12149 (setq time (save-match-data (org-time-string-to-time ts)))
12150 (cond
12151 ((equal (match-string 1 ts) ".")
12152 ;; Shift starting date to today
12153 (org-timestamp-change
12154 (- (org-today) (time-to-days time))
12155 'day))
12156 ((equal (match-string 1 ts) "+")
12157 (let ((nshiftmax 10) (nshift 0))
12158 (while (or (= nshift 0)
12159 (<= (time-to-days time)
12160 (time-to-days (current-time))))
12161 (when (= (incf nshift) nshiftmax)
12162 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12163 (error "Abort")))
12164 (org-timestamp-change n (cdr (assoc what whata)))
12165 (org-at-timestamp-p t)
12166 (setq ts (match-string 1))
12167 (setq time (save-match-data (org-time-string-to-time ts)))))
12168 (org-timestamp-change (- n) (cdr (assoc what whata)))
12169 ;; rematch, so that we have everything in place for the real shift
12170 (org-at-timestamp-p t)
12171 (setq ts (match-string 1))
12172 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12173 (org-timestamp-change n (cdr (assoc what whata)))
12174 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12175 (setq org-log-post-message msg)
12176 (message "%s" msg))))
12178 (defun org-show-todo-tree (arg)
12179 "Make a compact tree which shows all headlines marked with TODO.
12180 The tree will show the lines where the regexp matches, and all higher
12181 headlines above the match.
12182 With a \\[universal-argument] prefix, prompt for a regexp to match.
12183 With a numeric prefix N, construct a sparse tree for the Nth element
12184 of `org-todo-keywords-1'."
12185 (interactive "P")
12186 (let ((case-fold-search nil)
12187 (kwd-re
12188 (cond ((null arg) org-not-done-regexp)
12189 ((equal arg '(4))
12190 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12191 (mapcar 'list org-todo-keywords-1))))
12192 (concat "\\("
12193 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12194 "\\)\\>")))
12195 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12196 (regexp-quote (nth (1- (prefix-numeric-value arg))
12197 org-todo-keywords-1)))
12198 (t (error "Invalid prefix argument: %s" arg)))))
12199 (message "%d TODO entries found"
12200 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12202 (defun org-deadline (&optional remove time)
12203 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12204 With argument REMOVE, remove any deadline from the item.
12205 With argument TIME, set the deadline at the corresponding date. TIME
12206 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12207 (interactive "P")
12208 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12209 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12210 'region-start-level 'region))
12211 org-loop-over-headlines-in-active-region)
12212 (org-map-entries
12213 `(org-deadline ',remove ,time)
12214 org-loop-over-headlines-in-active-region
12215 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12216 (let* ((old-date (org-entry-get nil "DEADLINE"))
12217 (repeater (and old-date
12218 (string-match
12219 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12220 old-date)
12221 (match-string 1 old-date))))
12222 (if remove
12223 (progn
12224 (when (and old-date org-log-redeadline)
12225 (org-add-log-setup 'deldeadline nil old-date 'findpos
12226 org-log-redeadline))
12227 (org-remove-timestamp-with-keyword org-deadline-string)
12228 (message "Item no longer has a deadline."))
12229 (org-add-planning-info 'deadline time 'closed)
12230 (when (and old-date org-log-redeadline
12231 (not (equal old-date
12232 (substring org-last-inserted-timestamp 1 -1))))
12233 (org-add-log-setup 'redeadline nil old-date 'findpos
12234 org-log-redeadline))
12235 (when repeater
12236 (save-excursion
12237 (org-back-to-heading t)
12238 (when (re-search-forward (concat org-deadline-string " "
12239 org-last-inserted-timestamp)
12240 (save-excursion
12241 (outline-next-heading) (point)) t)
12242 (goto-char (1- (match-end 0)))
12243 (insert " " repeater)
12244 (setq org-last-inserted-timestamp
12245 (concat (substring org-last-inserted-timestamp 0 -1)
12246 " " repeater
12247 (substring org-last-inserted-timestamp -1))))))
12248 (message "Deadline on %s" org-last-inserted-timestamp)))))
12250 (defun org-schedule (&optional remove time)
12251 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12252 With argument REMOVE, remove any scheduling date from the item.
12253 With argument TIME, scheduled at the corresponding date. TIME can
12254 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12255 (interactive "P")
12256 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12257 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12258 'region-start-level 'region))
12259 org-loop-over-headlines-in-active-region)
12260 (org-map-entries
12261 `(org-schedule ',remove ,time)
12262 org-loop-over-headlines-in-active-region
12263 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12264 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12265 (repeater (and old-date
12266 (string-match
12267 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12268 old-date)
12269 (match-string 1 old-date))))
12270 (if remove
12271 (progn
12272 (when (and old-date org-log-reschedule)
12273 (org-add-log-setup 'delschedule nil old-date 'findpos
12274 org-log-reschedule))
12275 (org-remove-timestamp-with-keyword org-scheduled-string)
12276 (message "Item is no longer scheduled."))
12277 (org-add-planning-info 'scheduled time 'closed)
12278 (when (and old-date org-log-reschedule
12279 (not (equal old-date
12280 (substring org-last-inserted-timestamp 1 -1))))
12281 (org-add-log-setup 'reschedule nil old-date 'findpos
12282 org-log-reschedule))
12283 (when repeater
12284 (save-excursion
12285 (org-back-to-heading t)
12286 (when (re-search-forward (concat org-scheduled-string " "
12287 org-last-inserted-timestamp)
12288 (save-excursion
12289 (outline-next-heading) (point)) t)
12290 (goto-char (1- (match-end 0)))
12291 (insert " " repeater)
12292 (setq org-last-inserted-timestamp
12293 (concat (substring org-last-inserted-timestamp 0 -1)
12294 " " repeater
12295 (substring org-last-inserted-timestamp -1))))))
12296 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12298 (defun org-get-scheduled-time (pom &optional inherit)
12299 "Get the scheduled time as a time tuple, of a format suitable
12300 for calling org-schedule with, or if there is no scheduling,
12301 returns nil."
12302 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12303 (when time
12304 (apply 'encode-time (org-parse-time-string time)))))
12306 (defun org-get-deadline-time (pom &optional inherit)
12307 "Get the deadline as a time tuple, of a format suitable for
12308 calling org-deadline with, or if there is no scheduling, returns
12309 nil."
12310 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12311 (when time
12312 (apply 'encode-time (org-parse-time-string time)))))
12314 (defun org-remove-timestamp-with-keyword (keyword)
12315 "Remove all time stamps with KEYWORD in the current entry."
12316 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12317 beg)
12318 (save-excursion
12319 (org-back-to-heading t)
12320 (setq beg (point))
12321 (outline-next-heading)
12322 (while (re-search-backward re beg t)
12323 (replace-match "")
12324 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12325 (equal (char-before) ?\ ))
12326 (backward-delete-char 1)
12327 (if (string-match "^[ \t]*$" (buffer-substring
12328 (point-at-bol) (point-at-eol)))
12329 (delete-region (point-at-bol)
12330 (min (point-max) (1+ (point-at-eol))))))))))
12332 (defun org-add-planning-info (what &optional time &rest remove)
12333 "Insert new timestamp with keyword in the line directly after the headline.
12334 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12335 If non is given, the user is prompted for a date.
12336 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12337 be removed."
12338 (interactive)
12339 (let (org-time-was-given org-end-time-was-given ts
12340 end default-time default-input)
12342 (catch 'exit
12343 (when (and (memq what '(scheduled deadline))
12344 (or (not time)
12345 (and (stringp time)
12346 (string-match "^[-+]+[0-9]" time))))
12347 ;; Try to get a default date/time from existing timestamp
12348 (save-excursion
12349 (org-back-to-heading t)
12350 (setq end (save-excursion (outline-next-heading) (point)))
12351 (when (re-search-forward (if (eq what 'scheduled)
12352 org-scheduled-time-regexp
12353 org-deadline-time-regexp)
12354 end t)
12355 (setq ts (match-string 1)
12356 default-time
12357 (apply 'encode-time (org-parse-time-string ts))
12358 default-input (and ts (org-get-compact-tod ts))))))
12359 (when what
12360 (setq time
12361 (if (stringp time)
12362 ;; This is a string (relative or absolute), set proper date
12363 (apply 'encode-time
12364 (org-read-date-analyze
12365 time default-time (decode-time default-time)))
12366 ;; If necessary, get the time from the user
12367 (or time (org-read-date nil 'to-time nil nil
12368 default-time default-input)))))
12370 (when (and org-insert-labeled-timestamps-at-point
12371 (member what '(scheduled deadline)))
12372 (insert
12373 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12374 (org-insert-time-stamp time org-time-was-given
12375 nil nil nil (list org-end-time-was-given))
12376 (setq what nil))
12377 (save-excursion
12378 (save-restriction
12379 (let (col list elt ts buffer-invisibility-spec)
12380 (org-back-to-heading t)
12381 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12382 (goto-char (match-end 1))
12383 (setq col (current-column))
12384 (goto-char (match-end 0))
12385 (if (eobp) (insert "\n") (forward-char 1))
12386 (when (and (not what)
12387 (not (looking-at
12388 (concat "[ \t]*"
12389 org-keyword-time-not-clock-regexp))))
12390 ;; Nothing to add, nothing to remove...... :-)
12391 (throw 'exit nil))
12392 (if (and (not (looking-at org-outline-regexp))
12393 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12394 "[^\r\n]*"))
12395 (not (equal (match-string 1) org-clock-string)))
12396 (narrow-to-region (match-beginning 0) (match-end 0))
12397 (insert-before-markers "\n")
12398 (backward-char 1)
12399 (narrow-to-region (point) (point))
12400 (and org-adapt-indentation (org-indent-to-column col)))
12401 ;; Check if we have to remove something.
12402 (setq list (cons what remove))
12403 (while list
12404 (setq elt (pop list))
12405 (when (or (and (eq elt 'scheduled)
12406 (re-search-forward org-scheduled-time-regexp nil t))
12407 (and (eq elt 'deadline)
12408 (re-search-forward org-deadline-time-regexp nil t))
12409 (and (eq elt 'closed)
12410 (re-search-forward org-closed-time-regexp nil t)))
12411 (replace-match "")
12412 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12413 (and (looking-at "[ \t]+") (replace-match ""))
12414 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12415 (when what
12416 (insert
12417 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12418 (cond ((eq what 'scheduled) org-scheduled-string)
12419 ((eq what 'deadline) org-deadline-string)
12420 ((eq what 'closed) org-closed-string))
12421 " ")
12422 (setq ts (org-insert-time-stamp
12423 time
12424 (or org-time-was-given
12425 (and (eq what 'closed) org-log-done-with-time))
12426 (eq what 'closed)
12427 nil nil (list org-end-time-was-given)))
12428 (insert
12429 (if (not (or (bolp) (eq (char-before) ?\ )
12430 (memq (char-after) '(32 10))
12431 (eobp))) " " ""))
12432 (end-of-line 1))
12433 (goto-char (point-min))
12434 (widen)
12435 (if (and (looking-at "[ \t]*\n")
12436 (equal (char-before) ?\n))
12437 (delete-region (1- (point)) (point-at-eol)))
12438 ts))))))
12440 (defvar org-log-note-marker (make-marker))
12441 (defvar org-log-note-purpose nil)
12442 (defvar org-log-note-state nil)
12443 (defvar org-log-note-previous-state nil)
12444 (defvar org-log-note-how nil)
12445 (defvar org-log-note-extra nil)
12446 (defvar org-log-note-window-configuration nil)
12447 (defvar org-log-note-return-to (make-marker))
12448 (defvar org-log-note-effective-time nil
12449 "Remembered current time so that dynamically scoped
12450 `org-extend-today-until' affects tha timestamps in state change
12451 log")
12453 (defvar org-log-post-message nil
12454 "Message to be displayed after a log note has been stored.
12455 The auto-repeater uses this.")
12457 (defun org-add-note ()
12458 "Add a note to the current entry.
12459 This is done in the same way as adding a state change note."
12460 (interactive)
12461 (org-add-log-setup 'note nil nil 'findpos nil))
12463 (defvar org-property-end-re)
12464 (defun org-add-log-setup (&optional purpose state prev-state
12465 findpos how extra)
12466 "Set up the post command hook to take a note.
12467 If this is about to TODO state change, the new state is expected in STATE.
12468 When FINDPOS is non-nil, find the correct position for the note in
12469 the current entry. If not, assume that it can be inserted at point.
12470 HOW is an indicator what kind of note should be created.
12471 EXTRA is additional text that will be inserted into the notes buffer."
12472 (let* ((org-log-into-drawer (org-log-into-drawer))
12473 (drawer (cond ((stringp org-log-into-drawer)
12474 org-log-into-drawer)
12475 (org-log-into-drawer "LOGBOOK"))))
12476 (save-restriction
12477 (save-excursion
12478 (when findpos
12479 (org-back-to-heading t)
12480 (narrow-to-region (point) (save-excursion
12481 (outline-next-heading) (point)))
12482 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12483 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12484 "[^\r\n]*\\)?"))
12485 (goto-char (match-end 0))
12486 (cond
12487 (drawer
12488 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12489 nil t)
12490 (progn
12491 (goto-char (match-end 0))
12492 (or org-log-states-order-reversed
12493 (and (re-search-forward org-property-end-re nil t)
12494 (goto-char (1- (match-beginning 0))))))
12495 (insert "\n:" drawer ":\n:END:")
12496 (beginning-of-line 0)
12497 (org-indent-line)
12498 (beginning-of-line 2)
12499 (org-indent-line)
12500 (end-of-line 0)))
12501 ((and org-log-state-notes-insert-after-drawers
12502 (save-excursion
12503 (forward-line) (looking-at org-drawer-regexp)))
12504 (forward-line)
12505 (while (looking-at org-drawer-regexp)
12506 (goto-char (match-end 0))
12507 (re-search-forward org-property-end-re (point-max) t)
12508 (forward-line))
12509 (forward-line -1)))
12510 (unless org-log-states-order-reversed
12511 (and (= (char-after) ?\n) (forward-char 1))
12512 (org-skip-over-state-notes)
12513 (skip-chars-backward " \t\n\r")))
12514 (move-marker org-log-note-marker (point))
12515 (setq org-log-note-purpose purpose
12516 org-log-note-state state
12517 org-log-note-previous-state prev-state
12518 org-log-note-how how
12519 org-log-note-extra extra
12520 org-log-note-effective-time (org-current-effective-time))
12521 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12523 (defun org-skip-over-state-notes ()
12524 "Skip past the list of State notes in an entry."
12525 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12526 (when (ignore-errors (goto-char (org-in-item-p)))
12527 (let* ((struct (org-list-struct))
12528 (prevs (org-list-prevs-alist struct)))
12529 (while (looking-at "[ \t]*- State")
12530 (goto-char (or (org-list-get-next-item (point) struct prevs)
12531 (org-list-get-item-end (point) struct)))))))
12533 (defun org-add-log-note (&optional purpose)
12534 "Pop up a window for taking a note, and add this note later at point."
12535 (remove-hook 'post-command-hook 'org-add-log-note)
12536 (setq org-log-note-window-configuration (current-window-configuration))
12537 (delete-other-windows)
12538 (move-marker org-log-note-return-to (point))
12539 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12540 (goto-char org-log-note-marker)
12541 (org-switch-to-buffer-other-window "*Org Note*")
12542 (erase-buffer)
12543 (if (memq org-log-note-how '(time state))
12544 (let (current-prefix-arg) (org-store-log-note))
12545 (let ((org-inhibit-startup t)) (org-mode))
12546 (insert (format "# Insert note for %s.
12547 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12548 (cond
12549 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12550 ((eq org-log-note-purpose 'done) "closed todo item")
12551 ((eq org-log-note-purpose 'state)
12552 (format "state change from \"%s\" to \"%s\""
12553 (or org-log-note-previous-state "")
12554 (or org-log-note-state "")))
12555 ((eq org-log-note-purpose 'reschedule)
12556 "rescheduling")
12557 ((eq org-log-note-purpose 'delschedule)
12558 "no longer scheduled")
12559 ((eq org-log-note-purpose 'redeadline)
12560 "changing deadline")
12561 ((eq org-log-note-purpose 'deldeadline)
12562 "removing deadline")
12563 ((eq org-log-note-purpose 'refile)
12564 "refiling")
12565 ((eq org-log-note-purpose 'note)
12566 "this entry")
12567 (t (error "This should not happen")))))
12568 (if org-log-note-extra (insert org-log-note-extra))
12569 (org-set-local 'org-finish-function 'org-store-log-note)
12570 (run-hooks 'org-log-buffer-setup-hook)))
12572 (defvar org-note-abort nil) ; dynamically scoped
12573 (defun org-store-log-note ()
12574 "Finish taking a log note, and insert it to where it belongs."
12575 (let ((txt (buffer-string))
12576 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12577 lines ind bul)
12578 (kill-buffer (current-buffer))
12579 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12580 (setq txt (replace-match "" t t txt)))
12581 (if (string-match "\\s-+\\'" txt)
12582 (setq txt (replace-match "" t t txt)))
12583 (setq lines (org-split-string txt "\n"))
12584 (when (and note (string-match "\\S-" note))
12585 (setq note
12586 (org-replace-escapes
12587 note
12588 (list (cons "%u" (user-login-name))
12589 (cons "%U" user-full-name)
12590 (cons "%t" (format-time-string
12591 (org-time-stamp-format 'long 'inactive)
12592 org-log-note-effective-time))
12593 (cons "%T" (format-time-string
12594 (org-time-stamp-format 'long nil)
12595 org-log-note-effective-time))
12596 (cons "%d" (format-time-string
12597 (org-time-stamp-format nil 'inactive)
12598 org-log-note-effective-time))
12599 (cons "%D" (format-time-string
12600 (org-time-stamp-format nil nil)
12601 org-log-note-effective-time))
12602 (cons "%s" (if org-log-note-state
12603 (concat "\"" org-log-note-state "\"")
12604 ""))
12605 (cons "%S" (if org-log-note-previous-state
12606 (concat "\"" org-log-note-previous-state "\"")
12607 "\"\"")))))
12608 (if lines (setq note (concat note " \\\\")))
12609 (push note lines))
12610 (when (or current-prefix-arg org-note-abort)
12611 (when org-log-into-drawer
12612 (org-remove-empty-drawer-at
12613 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12614 org-log-note-marker))
12615 (setq lines nil))
12616 (when lines
12617 (with-current-buffer (marker-buffer org-log-note-marker)
12618 (save-excursion
12619 (goto-char org-log-note-marker)
12620 (move-marker org-log-note-marker nil)
12621 (end-of-line 1)
12622 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12623 (setq ind (save-excursion
12624 (if (ignore-errors (goto-char (org-in-item-p)))
12625 (let ((struct (org-list-struct)))
12626 (org-list-get-ind
12627 (org-list-get-top-point struct) struct))
12628 (skip-chars-backward " \r\t\n")
12629 (cond
12630 ((and (org-at-heading-p)
12631 org-adapt-indentation)
12632 (1+ (org-current-level)))
12633 ((org-at-heading-p) 0)
12634 (t (org-get-indentation))))))
12635 (setq bul (org-list-bullet-string "-"))
12636 (org-indent-line-to ind)
12637 (insert bul (pop lines))
12638 (let ((ind-body (+ (length bul) ind)))
12639 (while lines
12640 (insert "\n")
12641 (org-indent-line-to ind-body)
12642 (insert (pop lines))))
12643 (message "Note stored")
12644 (org-back-to-heading t)
12645 (org-cycle-hide-drawers 'children)))))
12646 (set-window-configuration org-log-note-window-configuration)
12647 (with-current-buffer (marker-buffer org-log-note-return-to)
12648 (goto-char org-log-note-return-to))
12649 (move-marker org-log-note-return-to nil)
12650 (and org-log-post-message (message "%s" org-log-post-message)))
12652 (defun org-remove-empty-drawer-at (drawer pos)
12653 "Remove an empty drawer DRAWER at position POS.
12654 POS may also be a marker."
12655 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12656 (save-excursion
12657 (save-restriction
12658 (widen)
12659 (goto-char pos)
12660 (if (org-in-regexp
12661 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12662 (replace-match ""))))))
12664 (defvar org-ts-type nil)
12665 (defun org-sparse-tree (&optional arg type)
12666 "Create a sparse tree, prompt for the details.
12667 This command can create sparse trees. You first need to select the type
12668 of match used to create the tree:
12670 t Show all TODO entries.
12671 T Show entries with a specific TODO keyword.
12672 m Show entries selected by a tags/property match.
12673 p Enter a property name and its value (both with completion on existing
12674 names/values) and show entries with that property.
12675 r Show entries matching a regular expression (`/' can be used as well).
12676 b Show deadlines and scheduled items before a date.
12677 a Show deadlines and scheduled items after a date.
12678 d Show deadlines due within `org-deadline-warning-days'.
12679 D Show deadlines and scheduled items between a date range."
12680 (interactive "P")
12681 (let (ans kwd value ts-type)
12682 (setq type (or type org-sparse-tree-default-date-type))
12683 (setq org-ts-type type)
12684 (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"
12685 (cond ((eq type 'all) "all timestamps")
12686 ((eq type 'scheduled) "only scheduled")
12687 ((eq type 'deadline) "only deadline")
12688 ((eq type 'active) "only active timestamps")
12689 ((eq type 'inactive) "only inactive timestamps")
12690 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12691 (t "scheduled/deadline")))
12692 (setq ans (read-char-exclusive))
12693 (cond
12694 ((equal ans ?c)
12695 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12696 ((equal ans ?d)
12697 (call-interactively 'org-check-deadlines))
12698 ((equal ans ?b)
12699 (call-interactively 'org-check-before-date))
12700 ((equal ans ?a)
12701 (call-interactively 'org-check-after-date))
12702 ((equal ans ?D)
12703 (call-interactively 'org-check-dates-range))
12704 ((equal ans ?t)
12705 (call-interactively 'org-show-todo-tree))
12706 ((equal ans ?T)
12707 (org-show-todo-tree '(4)))
12708 ((member ans '(?T ?m))
12709 (call-interactively 'org-match-sparse-tree))
12710 ((member ans '(?p ?P))
12711 (setq kwd (org-icompleting-read "Property: "
12712 (mapcar 'list (org-buffer-property-keys))))
12713 (setq value (org-icompleting-read "Value: "
12714 (mapcar 'list (org-property-values kwd))))
12715 (unless (string-match "\\`{.*}\\'" value)
12716 (setq value (concat "\"" value "\"")))
12717 (org-match-sparse-tree arg (concat kwd "=" value)))
12718 ((member ans '(?r ?R ?/))
12719 (call-interactively 'org-occur))
12720 (t (error "No such sparse tree command \"%c\"" ans)))))
12722 (defvar org-occur-highlights nil
12723 "List of overlays used for occur matches.")
12724 (make-variable-buffer-local 'org-occur-highlights)
12725 (defvar org-occur-parameters nil
12726 "Parameters of the active org-occur calls.
12727 This is a list, each call to org-occur pushes as cons cell,
12728 containing the regular expression and the callback, onto the list.
12729 The list can contain several entries if `org-occur' has been called
12730 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12731 will only contain one set of parameters. When the highlights are
12732 removed (for example with `C-c C-c', or with the next edit (depending
12733 on `org-remove-highlights-with-change'), this variable is emptied
12734 as well.")
12735 (make-variable-buffer-local 'org-occur-parameters)
12737 (defun org-occur (regexp &optional keep-previous callback)
12738 "Make a compact tree which shows all matches of REGEXP.
12739 The tree will show the lines where the regexp matches, and all higher
12740 headlines above the match. It will also show the heading after the match,
12741 to make sure editing the matching entry is easy.
12742 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12743 call to `org-occur' will be kept, to allow stacking of calls to this
12744 command.
12745 If CALLBACK is non-nil, it is a function which is called to confirm
12746 that the match should indeed be shown."
12747 (interactive "sRegexp: \nP")
12748 (when (equal regexp "")
12749 (error "Regexp cannot be empty"))
12750 (unless keep-previous
12751 (org-remove-occur-highlights nil nil t))
12752 (push (cons regexp callback) org-occur-parameters)
12753 (let ((cnt 0))
12754 (save-excursion
12755 (goto-char (point-min))
12756 (if (or (not keep-previous) ; do not want to keep
12757 (not org-occur-highlights)) ; no previous matches
12758 ;; hide everything
12759 (org-overview))
12760 (while (re-search-forward regexp nil t)
12761 (when (or (not callback)
12762 (save-match-data (funcall callback)))
12763 (setq cnt (1+ cnt))
12764 (when org-highlight-sparse-tree-matches
12765 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12766 (org-show-context 'occur-tree))))
12767 (when org-remove-highlights-with-change
12768 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12769 nil 'local))
12770 (unless org-sparse-tree-open-archived-trees
12771 (org-hide-archived-subtrees (point-min) (point-max)))
12772 (run-hooks 'org-occur-hook)
12773 (if (org-called-interactively-p 'interactive)
12774 (message "%d match(es) for regexp %s" cnt regexp))
12775 cnt))
12777 (defun org-occur-next-match (&optional n reset)
12778 "Function for `next-error-function' to find sparse tree matches.
12779 N is the number of matches to move, when negative move backwards.
12780 RESET is entirely ignored - this function always goes back to the
12781 starting point when no match is found."
12782 (let* ((limit (if (< n 0) (point-min) (point-max)))
12783 (search-func (if (< n 0)
12784 'previous-single-char-property-change
12785 'next-single-char-property-change))
12786 (n (abs n))
12787 (pos (point))
12789 (catch 'exit
12790 (while (setq p1 (funcall search-func (point) 'org-type))
12791 (when (equal p1 limit)
12792 (goto-char pos)
12793 (error "No more matches"))
12794 (when (equal (get-char-property p1 'org-type) 'org-occur)
12795 (setq n (1- n))
12796 (when (= n 0)
12797 (goto-char p1)
12798 (throw 'exit (point))))
12799 (goto-char p1))
12800 (goto-char p1)
12801 (error "No more matches"))))
12803 (defun org-show-context (&optional key)
12804 "Make sure point and context are visible.
12805 How much context is shown depends upon the variables
12806 `org-show-hierarchy-above', `org-show-following-heading',
12807 `org-show-entry-below' and `org-show-siblings'."
12808 (let ((heading-p (org-at-heading-p t))
12809 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12810 (following-p (org-get-alist-option org-show-following-heading key))
12811 (entry-p (org-get-alist-option org-show-entry-below key))
12812 (siblings-p (org-get-alist-option org-show-siblings key)))
12813 (catch 'exit
12814 ;; Show heading or entry text
12815 (if (and heading-p (not entry-p))
12816 (org-flag-heading nil) ; only show the heading
12817 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12818 (org-show-hidden-entry))) ; show entire entry
12819 (when following-p
12820 ;; Show next sibling, or heading below text
12821 (save-excursion
12822 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12823 (org-flag-heading nil))))
12824 (when siblings-p (org-show-siblings))
12825 (when hierarchy-p
12826 ;; show all higher headings, possibly with siblings
12827 (save-excursion
12828 (while (and (condition-case nil
12829 (progn (org-up-heading-all 1) t)
12830 (error nil))
12831 (not (bobp)))
12832 (org-flag-heading nil)
12833 (when siblings-p (org-show-siblings))))))))
12835 (defvar org-reveal-start-hook nil
12836 "Hook run before revealing a location.")
12838 (defun org-reveal (&optional siblings)
12839 "Show current entry, hierarchy above it, and the following headline.
12840 This can be used to show a consistent set of context around locations
12841 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12842 not t for the search context.
12844 With optional argument SIBLINGS, on each level of the hierarchy all
12845 siblings are shown. This repairs the tree structure to what it would
12846 look like when opened with hierarchical calls to `org-cycle'.
12847 With double optional argument \\[universal-argument] \\[universal-argument], \
12848 go to the parent and show the
12849 entire tree."
12850 (interactive "P")
12851 (run-hooks 'org-reveal-start-hook)
12852 (let ((org-show-hierarchy-above t)
12853 (org-show-following-heading t)
12854 (org-show-siblings (if siblings t org-show-siblings)))
12855 (org-show-context nil))
12856 (when (equal siblings '(16))
12857 (save-excursion
12858 (when (org-up-heading-safe)
12859 (org-show-subtree)
12860 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12862 (defun org-highlight-new-match (beg end)
12863 "Highlight from BEG to END and mark the highlight is an occur headline."
12864 (let ((ov (make-overlay beg end)))
12865 (overlay-put ov 'face 'secondary-selection)
12866 (overlay-put ov 'org-type 'org-occur)
12867 (push ov org-occur-highlights)))
12869 (defun org-remove-occur-highlights (&optional beg end noremove)
12870 "Remove the occur highlights from the buffer.
12871 BEG and END are ignored. If NOREMOVE is nil, remove this function
12872 from the `before-change-functions' in the current buffer."
12873 (interactive)
12874 (unless org-inhibit-highlight-removal
12875 (mapc 'delete-overlay org-occur-highlights)
12876 (setq org-occur-highlights nil)
12877 (setq org-occur-parameters nil)
12878 (unless noremove
12879 (remove-hook 'before-change-functions
12880 'org-remove-occur-highlights 'local))))
12882 ;;;; Priorities
12884 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12885 "Regular expression matching the priority indicator.")
12887 (defvar org-remove-priority-next-time nil)
12889 (defun org-priority-up ()
12890 "Increase the priority of the current item."
12891 (interactive)
12892 (org-priority 'up))
12894 (defun org-priority-down ()
12895 "Decrease the priority of the current item."
12896 (interactive)
12897 (org-priority 'down))
12899 (defun org-priority (&optional action show)
12900 "Change the priority of an item.
12901 ACTION can be `set', `up', `down', or a character."
12902 (interactive "P")
12903 (if (equal action '(4))
12904 (org-show-priority)
12905 (unless org-enable-priority-commands
12906 (error "Priority commands are disabled"))
12907 (setq action (or action 'set))
12908 (let (current new news have remove)
12909 (save-excursion
12910 (org-back-to-heading t)
12911 (if (looking-at org-priority-regexp)
12912 (setq current (string-to-char (match-string 2))
12913 have t))
12914 (cond
12915 ((eq action 'remove)
12916 (setq remove t new ?\ ))
12917 ((or (eq action 'set)
12918 (if (featurep 'xemacs) (characterp action) (integerp action)))
12919 (if (not (eq action 'set))
12920 (setq new action)
12921 (message "Priority %c-%c, SPC to remove: "
12922 org-highest-priority org-lowest-priority)
12923 (save-match-data
12924 (setq new (read-char-exclusive))))
12925 (if (and (= (upcase org-highest-priority) org-highest-priority)
12926 (= (upcase org-lowest-priority) org-lowest-priority))
12927 (setq new (upcase new)))
12928 (cond ((equal new ?\ ) (setq remove t))
12929 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12930 (error "Priority must be between `%c' and `%c'"
12931 org-highest-priority org-lowest-priority))))
12932 ((eq action 'up)
12933 (setq new (if have
12934 (1- current) ; normal cycling
12935 ;; last priority was empty
12936 (if (eq last-command this-command)
12937 org-lowest-priority ; wrap around empty to lowest
12938 ;; default
12939 (if org-priority-start-cycle-with-default
12940 org-default-priority
12941 (1- org-default-priority))))))
12942 ((eq action 'down)
12943 (setq new (if have
12944 (1+ current) ; normal cycling
12945 ;; last priority was empty
12946 (if (eq last-command this-command)
12947 org-highest-priority ; wrap around empty to highest
12948 ;; default
12949 (if org-priority-start-cycle-with-default
12950 org-default-priority
12951 (1+ org-default-priority))))))
12952 (t (error "Invalid action")))
12953 (if (or (< (upcase new) org-highest-priority)
12954 (> (upcase new) org-lowest-priority))
12955 (if (and (memq action '(up down))
12956 (not have) (not (eq last-command this-command)))
12957 ;; `new' is from default priority
12958 (error
12959 "The default can not be set, see `org-default-priority' why")
12960 ;; normal cycling: `new' is beyond highest/lowest priority
12961 ;; and is wrapped around to the empty priority
12962 (setq remove t)))
12963 (setq news (format "%c" new))
12964 (if have
12965 (if remove
12966 (replace-match "" t t nil 1)
12967 (replace-match news t t nil 2))
12968 (if remove
12969 (error "No priority cookie found in line")
12970 (let ((case-fold-search nil))
12971 (looking-at org-todo-line-regexp))
12972 (if (match-end 2)
12973 (progn
12974 (goto-char (match-end 2))
12975 (insert " [#" news "]"))
12976 (goto-char (match-beginning 3))
12977 (insert "[#" news "] "))))
12978 (org-preserve-lc (org-set-tags nil 'align)))
12979 (if remove
12980 (message "Priority removed")
12981 (message "Priority of current item set to %s" news)))))
12983 (defun org-show-priority ()
12984 "Show the priority of the current item.
12985 This priority is composed of the main priority given with the [#A] cookies,
12986 and by additional input from the age of a schedules or deadline entry."
12987 (interactive)
12988 (let ((pri (if (eq major-mode 'org-agenda-mode)
12989 (org-get-at-bol 'priority)
12990 (save-excursion
12991 (save-match-data
12992 (beginning-of-line)
12993 (and (looking-at org-heading-regexp)
12994 (org-get-priority (match-string 0))))))))
12995 (message "Priority is %d" (if pri pri -1000))))
12997 (defun org-get-priority (s)
12998 "Find priority cookie and return priority."
12999 (if (functionp org-get-priority-function)
13000 (funcall org-get-priority-function)
13001 (save-match-data
13002 (if (not (string-match org-priority-regexp s))
13003 (* 1000 (- org-lowest-priority org-default-priority))
13004 (* 1000 (- org-lowest-priority
13005 (string-to-char (match-string 2 s))))))))
13007 ;;;; Tags
13009 (defvar org-agenda-archives-mode)
13010 (defvar org-map-continue-from nil
13011 "Position from where mapping should continue.
13012 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13014 (defvar org-scanner-tags nil
13015 "The current tag list while the tags scanner is running.")
13016 (defvar org-trust-scanner-tags nil
13017 "Should `org-get-tags-at' use the tags for the scanner.
13018 This is for internal dynamical scoping only.
13019 When this is non-nil, the function `org-get-tags-at' will return the value
13020 of `org-scanner-tags' instead of building the list by itself. This
13021 can lead to large speed-ups when the tags scanner is used in a file with
13022 many entries, and when the list of tags is retrieved, for example to
13023 obtain a list of properties. Building the tags list for each entry in such
13024 a file becomes an N^2 operation - but with this variable set, it scales
13025 as N.")
13027 (defun org-scan-tags (action matcher todo-only &optional start-level)
13028 "Scan headline tags with inheritance and produce output ACTION.
13030 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13031 or `agenda' to produce an entry list for an agenda view. It can also be
13032 a Lisp form or a function that should be called at each matched headline, in
13033 this case the return value is a list of all return values from these calls.
13035 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13036 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13037 only lines with a not-done TODO keyword are included in the output.
13038 This should be the same variable that was scoped into
13039 and set by `org-make-tags-matcher' when it constructed MATCHER.
13041 START-LEVEL can be a string with asterisks, reducing the scope to
13042 headlines matching this string."
13043 (require 'org-agenda)
13044 (let* ((re (concat "^"
13045 (if start-level
13046 ;; Get the correct level to match
13047 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13048 org-outline-regexp)
13049 " *\\(\\<\\("
13050 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13051 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13052 (props (list 'face 'default
13053 'done-face 'org-agenda-done
13054 'undone-face 'default
13055 'mouse-face 'highlight
13056 'org-not-done-regexp org-not-done-regexp
13057 'org-todo-regexp org-todo-regexp
13058 'org-complex-heading-regexp org-complex-heading-regexp
13059 'help-echo
13060 (format "mouse-2 or RET jump to org file %s"
13061 (abbreviate-file-name
13062 (or (buffer-file-name (buffer-base-buffer))
13063 (buffer-name (buffer-base-buffer)))))))
13064 (case-fold-search nil)
13065 (org-map-continue-from nil)
13066 lspos tags tags-list
13067 (tags-alist (list (cons 0 org-file-tags)))
13068 (llast 0) rtn rtn1 level category i txt
13069 todo marker entry priority)
13070 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13071 (setq action (list 'lambda nil action)))
13072 (save-excursion
13073 (goto-char (point-min))
13074 (when (eq action 'sparse-tree)
13075 (org-overview)
13076 (org-remove-occur-highlights))
13077 (while (re-search-forward re nil t)
13078 (setq org-map-continue-from nil)
13079 (catch :skip
13080 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13081 tags (if (match-end 4) (org-match-string-no-properties 4)))
13082 (goto-char (setq lspos (match-beginning 0)))
13083 (setq level (org-reduced-level (funcall outline-level))
13084 category (org-get-category))
13085 (setq i llast llast level)
13086 ;; remove tag lists from same and sublevels
13087 (while (>= i level)
13088 (when (setq entry (assoc i tags-alist))
13089 (setq tags-alist (delete entry tags-alist)))
13090 (setq i (1- i)))
13091 ;; add the next tags
13092 (when tags
13093 (setq tags (org-split-string tags ":")
13094 tags-alist
13095 (cons (cons level tags) tags-alist)))
13096 ;; compile tags for current headline
13097 (setq tags-list
13098 (if org-use-tag-inheritance
13099 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13100 tags)
13101 org-scanner-tags tags-list)
13102 (when org-use-tag-inheritance
13103 (setcdr (car tags-alist)
13104 (mapcar (lambda (x)
13105 (setq x (copy-sequence x))
13106 (org-add-prop-inherited x))
13107 (cdar tags-alist))))
13108 (when (and tags org-use-tag-inheritance
13109 (or (not (eq t org-use-tag-inheritance))
13110 org-tags-exclude-from-inheritance))
13111 ;; selective inheritance, remove uninherited ones
13112 (setcdr (car tags-alist)
13113 (org-remove-uninherited-tags (cdar tags-alist))))
13114 (when (and
13116 ;; eval matcher only when the todo condition is OK
13117 (and (or (not todo-only) (member todo org-not-done-keywords))
13118 (let ((case-fold-search t) (org-trust-scanner-tags t))
13119 (eval matcher)))
13121 ;; Call the skipper, but return t if it does not skip,
13122 ;; so that the `and' form continues evaluating
13123 (progn
13124 (unless (eq action 'sparse-tree) (org-agenda-skip))
13127 ;; Check if timestamps are deselecting this entry
13128 (or (not todo-only)
13129 (and (member todo org-not-done-keywords)
13130 (or (not org-agenda-tags-todo-honor-ignore-options)
13131 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13133 ;; Extra check for the archive tag
13134 ;; FIXME: Does the skipper already do this????
13136 (not (member org-archive-tag tags-list))
13137 ;; we have an archive tag, should we use this anyway?
13138 (or (not org-agenda-skip-archived-trees)
13139 (and (eq action 'agenda) org-agenda-archives-mode))))
13141 ;; select this headline
13143 (cond
13144 ((eq action 'sparse-tree)
13145 (and org-highlight-sparse-tree-matches
13146 (org-get-heading) (match-end 0)
13147 (org-highlight-new-match
13148 (match-beginning 1) (match-end 1)))
13149 (org-show-context 'tags-tree))
13150 ((eq action 'agenda)
13151 (setq txt (org-agenda-format-item
13153 (concat
13154 (if (eq org-tags-match-list-sublevels 'indented)
13155 (make-string (1- level) ?.) "")
13156 (org-get-heading))
13157 category
13158 tags-list)
13159 priority (org-get-priority txt))
13160 (goto-char lspos)
13161 (setq marker (org-agenda-new-marker))
13162 (org-add-props txt props
13163 'org-marker marker 'org-hd-marker marker 'org-category category
13164 'todo-state todo
13165 'priority priority 'type "tagsmatch")
13166 (push txt rtn))
13167 ((functionp action)
13168 (setq org-map-continue-from nil)
13169 (save-excursion
13170 (setq rtn1 (funcall action))
13171 (push rtn1 rtn)))
13172 (t (error "Invalid action")))
13174 ;; if we are to skip sublevels, jump to end of subtree
13175 (unless org-tags-match-list-sublevels
13176 (org-end-of-subtree t)
13177 (backward-char 1))))
13178 ;; Get the correct position from where to continue
13179 (if org-map-continue-from
13180 (goto-char org-map-continue-from)
13181 (and (= (point) lspos) (end-of-line 1)))))
13182 (when (and (eq action 'sparse-tree)
13183 (not org-sparse-tree-open-archived-trees))
13184 (org-hide-archived-subtrees (point-min) (point-max)))
13185 (nreverse rtn)))
13187 (defun org-remove-uninherited-tags (tags)
13188 "Remove all tags that are not inherited from the list TAGS."
13189 (cond
13190 ((eq org-use-tag-inheritance t)
13191 (if org-tags-exclude-from-inheritance
13192 (org-delete-all org-tags-exclude-from-inheritance tags)
13193 tags))
13194 ((not org-use-tag-inheritance) nil)
13195 ((stringp org-use-tag-inheritance)
13196 (delq nil (mapcar
13197 (lambda (x)
13198 (if (and (string-match org-use-tag-inheritance x)
13199 (not (member x org-tags-exclude-from-inheritance)))
13200 x nil))
13201 tags)))
13202 ((listp org-use-tag-inheritance)
13203 (delq nil (mapcar
13204 (lambda (x)
13205 (if (member x org-use-tag-inheritance) x nil))
13206 tags)))))
13208 (defun org-match-sparse-tree (&optional todo-only match)
13209 "Create a sparse tree according to tags string MATCH.
13210 MATCH can contain positive and negative selection of tags, like
13211 \"+WORK+URGENT-WITHBOSS\".
13212 If optional argument TODO-ONLY is non-nil, only select lines that are
13213 also TODO lines."
13214 (interactive "P")
13215 (org-agenda-prepare-buffers (list (current-buffer)))
13216 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13218 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13220 (defvar org-cached-props nil)
13221 (defun org-cached-entry-get (pom property)
13222 (if (or (eq t org-use-property-inheritance)
13223 (and (stringp org-use-property-inheritance)
13224 (string-match org-use-property-inheritance property))
13225 (and (listp org-use-property-inheritance)
13226 (member property org-use-property-inheritance)))
13227 ;; Caching is not possible, check it directly
13228 (org-entry-get pom property 'inherit)
13229 ;; Get all properties, so that we can do complicated checks easily
13230 (cdr (assoc property (or org-cached-props
13231 (setq org-cached-props
13232 (org-entry-properties pom)))))))
13234 (defun org-global-tags-completion-table (&optional files)
13235 "Return the list of all tags in all agenda buffer/files.
13236 Optional FILES argument is a list of files which can be used
13237 instead of the agenda files."
13238 (save-excursion
13239 (org-uniquify
13240 (delq nil
13241 (apply 'append
13242 (mapcar
13243 (lambda (file)
13244 (set-buffer (find-file-noselect file))
13245 (append (org-get-buffer-tags)
13246 (mapcar (lambda (x) (if (stringp (car-safe x))
13247 (list (car-safe x)) nil))
13248 org-tag-alist)))
13249 (if (and files (car files))
13250 files
13251 (org-agenda-files))))))))
13253 (defun org-make-tags-matcher (match)
13254 "Create the TAGS/TODO matcher form for the selection string MATCH.
13256 The variable `todo-only' is scoped dynamically into this function.
13257 It will be set to t if the matcher restricts matching to TODO entries,
13258 otherwise will not be touched.
13260 Returns a cons of the selection string MATCH and the constructed
13261 lisp form implementing the matcher. The matcher is to be evaluated
13262 at an Org entry, with point on the headline, and returns t if the
13263 entry matches the selection string MATCH. The returned lisp form
13264 references two variables with information about the entry, which
13265 must be bound around the form's evaluation: todo, the TODO keyword
13266 at the entry (or nil of none); and tags-list, the list of all tags
13267 at the entry including inherited ones. Additionally, the category
13268 of the entry (if any) must be specified as the text property
13269 'org-category on the headline.
13271 See also `org-scan-tags'.
13273 (declare (special todo-only))
13274 (unless (boundp 'todo-only)
13275 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13276 (unless match
13277 ;; Get a new match request, with completion
13278 (let ((org-last-tags-completion-table
13279 (org-global-tags-completion-table)))
13280 (setq match (org-completing-read-no-i
13281 "Match: " 'org-tags-completion-function nil nil nil
13282 'org-tags-history))))
13284 ;; Parse the string and create a lisp form
13285 (let ((match0 match)
13286 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13287 minus tag mm
13288 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13289 orterms term orlist re-p str-p level-p level-op time-p
13290 prop-p pn pv po gv rest)
13291 (if (string-match "/+" match)
13292 ;; match contains also a todo-matching request
13293 (progn
13294 (setq tagsmatch (substring match 0 (match-beginning 0))
13295 todomatch (substring match (match-end 0)))
13296 (if (string-match "^!" todomatch)
13297 (setq todo-only t todomatch (substring todomatch 1)))
13298 (if (string-match "^\\s-*$" todomatch)
13299 (setq todomatch nil)))
13300 ;; only matching tags
13301 (setq tagsmatch match todomatch nil))
13303 ;; Make the tags matcher
13304 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13305 (setq tagsmatcher t)
13306 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13307 (while (setq term (pop orterms))
13308 (while (and (equal (substring term -1) "\\") orterms)
13309 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13310 (while (string-match re term)
13311 (setq rest (substring term (match-end 0))
13312 minus (and (match-end 1)
13313 (equal (match-string 1 term) "-"))
13314 tag (save-match-data (replace-regexp-in-string
13315 "\\\\-" "-"
13316 (match-string 2 term)))
13317 re-p (equal (string-to-char tag) ?{)
13318 level-p (match-end 4)
13319 prop-p (match-end 5)
13320 mm (cond
13321 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13322 (level-p
13323 (setq level-op (org-op-to-function (match-string 3 term)))
13324 `(,level-op level ,(string-to-number
13325 (match-string 4 term))))
13326 (prop-p
13327 (setq pn (match-string 5 term)
13328 po (match-string 6 term)
13329 pv (match-string 7 term)
13330 re-p (equal (string-to-char pv) ?{)
13331 str-p (equal (string-to-char pv) ?\")
13332 time-p (save-match-data
13333 (string-match "^\"[[<].*[]>]\"$" pv))
13334 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13335 (if time-p (setq pv (org-matcher-time pv)))
13336 (setq po (org-op-to-function po (if time-p 'time str-p)))
13337 (cond
13338 ((equal pn "CATEGORY")
13339 (setq gv '(get-text-property (point) 'org-category)))
13340 ((equal pn "TODO")
13341 (setq gv 'todo))
13343 (setq gv `(org-cached-entry-get nil ,pn))))
13344 (if re-p
13345 (if (eq po 'org<>)
13346 `(not (string-match ,pv (or ,gv "")))
13347 `(string-match ,pv (or ,gv "")))
13348 (if str-p
13349 `(,po (or ,gv "") ,pv)
13350 `(,po (string-to-number (or ,gv ""))
13351 ,(string-to-number pv) ))))
13352 (t `(member ,tag tags-list)))
13353 mm (if minus (list 'not mm) mm)
13354 term rest)
13355 (push mm tagsmatcher))
13356 (push (if (> (length tagsmatcher) 1)
13357 (cons 'and tagsmatcher)
13358 (car tagsmatcher))
13359 orlist)
13360 (setq tagsmatcher nil))
13361 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13362 (setq tagsmatcher
13363 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13364 ;; Make the todo matcher
13365 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13366 (setq todomatcher t)
13367 (setq orterms (org-split-string todomatch "|") orlist nil)
13368 (while (setq term (pop orterms))
13369 (while (string-match re term)
13370 (setq minus (and (match-end 1)
13371 (equal (match-string 1 term) "-"))
13372 kwd (match-string 2 term)
13373 re-p (equal (string-to-char kwd) ?{)
13374 term (substring term (match-end 0))
13375 mm (if re-p
13376 `(string-match ,(substring kwd 1 -1) todo)
13377 (list 'equal 'todo kwd))
13378 mm (if minus (list 'not mm) mm))
13379 (push mm todomatcher))
13380 (push (if (> (length todomatcher) 1)
13381 (cons 'and todomatcher)
13382 (car todomatcher))
13383 orlist)
13384 (setq todomatcher nil))
13385 (setq todomatcher (if (> (length orlist) 1)
13386 (cons 'or orlist) (car orlist))))
13388 ;; Return the string and lisp forms of the matcher
13389 (setq matcher (if todomatcher
13390 (list 'and tagsmatcher todomatcher)
13391 tagsmatcher))
13392 (when todo-only
13393 (setq matcher (list 'and '(member todo org-not-done-keywords)
13394 matcher)))
13395 (cons match0 matcher)))
13397 (defun org-op-to-function (op &optional stringp)
13398 "Turn an operator into the appropriate function."
13399 (setq op
13400 (cond
13401 ((equal op "<" ) '(< string< org-time<))
13402 ((equal op ">" ) '(> org-string> org-time>))
13403 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13404 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13405 ((member op '("=" "==")) '(= string= org-time=))
13406 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13407 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13409 (defun org<> (a b) (not (= a b)))
13410 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13411 (defun org-string>= (a b) (not (string< a b)))
13412 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13413 (defun org-string<> (a b) (not (string= a b)))
13414 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13415 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13416 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13417 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13418 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13419 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13420 (defun org-2ft (s)
13421 "Convert S to a floating point time.
13422 If S is already a number, just return it. If it is a string, parse
13423 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13424 (cond
13425 ((numberp s) s)
13426 ((stringp s)
13427 (condition-case nil
13428 (float-time (apply 'encode-time (org-parse-time-string s)))
13429 (error 0.)))
13430 (t 0.)))
13432 (defun org-time-today ()
13433 "Time in seconds today at 0:00.
13434 Returns the float number of seconds since the beginning of the
13435 epoch to the beginning of today (00:00)."
13436 (float-time (apply 'encode-time
13437 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13439 (defun org-matcher-time (s)
13440 "Interpret a time comparison value."
13441 (save-match-data
13442 (cond
13443 ((string= s "<now>") (float-time))
13444 ((string= s "<today>") (org-time-today))
13445 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13446 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13447 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13448 (+ (org-time-today)
13449 (* (string-to-number (match-string 1 s))
13450 (cdr (assoc (match-string 2 s)
13451 '(("d" . 86400.0) ("w" . 604800.0)
13452 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13453 (t (org-2ft s)))))
13455 (defun org-match-any-p (re list)
13456 "Does re match any element of list?"
13457 (setq list (mapcar (lambda (x) (string-match re x)) list))
13458 (delq nil list))
13460 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13461 (defvar org-tags-overlay (make-overlay 1 1))
13462 (org-detach-overlay org-tags-overlay)
13464 (defun org-get-local-tags-at (&optional pos)
13465 "Get a list of tags defined in the current headline."
13466 (org-get-tags-at pos 'local))
13468 (defun org-get-local-tags ()
13469 "Get a list of tags defined in the current headline."
13470 (org-get-tags-at nil 'local))
13472 (defun org-get-tags-at (&optional pos local)
13473 "Get a list of all headline tags applicable at POS.
13474 POS defaults to point. If tags are inherited, the list contains
13475 the targets in the same sequence as the headlines appear, i.e.
13476 the tags of the current headline come last.
13477 When LOCAL is non-nil, only return tags from the current headline,
13478 ignore inherited ones."
13479 (interactive)
13480 (if (and org-trust-scanner-tags
13481 (or (not pos) (equal pos (point)))
13482 (not local))
13483 org-scanner-tags
13484 (let (tags ltags lastpos parent)
13485 (save-excursion
13486 (save-restriction
13487 (widen)
13488 (goto-char (or pos (point)))
13489 (save-match-data
13490 (catch 'done
13491 (condition-case nil
13492 (progn
13493 (org-back-to-heading t)
13494 (while (not (equal lastpos (point)))
13495 (setq lastpos (point))
13496 (when (looking-at
13497 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13498 (setq ltags (org-split-string
13499 (org-match-string-no-properties 1) ":"))
13500 (when parent
13501 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13502 (setq tags (append
13503 (if parent
13504 (org-remove-uninherited-tags ltags)
13505 ltags)
13506 tags)))
13507 (or org-use-tag-inheritance (throw 'done t))
13508 (if local (throw 'done t))
13509 (or (org-up-heading-safe) (error nil))
13510 (setq parent t)))
13511 (error nil)))))
13512 (if local
13513 tags
13514 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13516 (defun org-add-prop-inherited (s)
13517 (add-text-properties 0 (length s) '(inherited t) s)
13520 (defun org-toggle-tag (tag &optional onoff)
13521 "Toggle the tag TAG for the current line.
13522 If ONOFF is `on' or `off', don't toggle but set to this state."
13523 (let (res current)
13524 (save-excursion
13525 (org-back-to-heading t)
13526 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13527 (point-at-eol) t)
13528 (progn
13529 (setq current (match-string 1))
13530 (replace-match ""))
13531 (setq current ""))
13532 (setq current (nreverse (org-split-string current ":")))
13533 (cond
13534 ((eq onoff 'on)
13535 (setq res t)
13536 (or (member tag current) (push tag current)))
13537 ((eq onoff 'off)
13538 (or (not (member tag current)) (setq current (delete tag current))))
13539 (t (if (member tag current)
13540 (setq current (delete tag current))
13541 (setq res t)
13542 (push tag current))))
13543 (end-of-line 1)
13544 (if current
13545 (progn
13546 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13547 (org-set-tags nil t))
13548 (delete-horizontal-space))
13549 (run-hooks 'org-after-tags-change-hook))
13550 res))
13552 (defun org-align-tags-here (to-col)
13553 ;; Assumes that this is a headline
13554 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13555 (beginning-of-line 1)
13556 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13557 (< pos (match-beginning 2)))
13558 (progn
13559 (setq tags-l (- (match-end 2) (match-beginning 2)))
13560 (goto-char (match-beginning 1))
13561 (insert " ")
13562 (delete-region (point) (1+ (match-beginning 2)))
13563 (setq ncol (max (current-column)
13564 (1+ col)
13565 (if (> to-col 0)
13566 to-col
13567 (- (abs to-col) tags-l))))
13568 (setq p (point))
13569 (insert (make-string (- ncol (current-column)) ?\ ))
13570 (setq ncol (current-column))
13571 (when indent-tabs-mode (tabify p (point-at-eol)))
13572 (org-move-to-column (min ncol col) t))
13573 (goto-char pos))))
13575 (defun org-set-tags-command (&optional arg just-align)
13576 "Call the set-tags command for the current entry."
13577 (interactive "P")
13578 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13579 (org-set-tags arg just-align)
13580 (save-excursion
13581 (org-back-to-heading t)
13582 (org-set-tags arg just-align))))
13584 (defun org-set-tags-to (data)
13585 "Set the tags of the current entry to DATA, replacing the current tags.
13586 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13587 If DATA is nil or the empty string, any tags will be removed."
13588 (interactive "sTags: ")
13589 (setq data
13590 (cond
13591 ((eq data nil) "")
13592 ((equal data "") "")
13593 ((stringp data)
13594 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13595 ":"))
13596 ((listp data)
13597 (concat ":" (mapconcat 'identity data ":") ":"))))
13598 (when data
13599 (save-excursion
13600 (org-back-to-heading t)
13601 (when (looking-at org-complex-heading-regexp)
13602 (if (match-end 5)
13603 (progn
13604 (goto-char (match-beginning 5))
13605 (insert data)
13606 (delete-region (point) (point-at-eol))
13607 (org-set-tags nil 'align))
13608 (goto-char (point-at-eol))
13609 (insert " " data)
13610 (org-set-tags nil 'align)))
13611 (beginning-of-line 1)
13612 (if (looking-at ".*?\\([ \t]+\\)$")
13613 (delete-region (match-beginning 1) (match-end 1))))))
13615 (defun org-align-all-tags ()
13616 "Align the tags i all headings."
13617 (interactive)
13618 (save-excursion
13619 (or (ignore-errors (org-back-to-heading t))
13620 (outline-next-heading))
13621 (if (org-at-heading-p)
13622 (org-set-tags t)
13623 (message "No headings"))))
13625 (defvar org-indent-indentation-per-level)
13626 (defun org-set-tags (&optional arg just-align)
13627 "Set the tags for the current headline.
13628 With prefix ARG, realign all tags in headings in the current buffer."
13629 (interactive "P")
13630 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13631 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13632 'region-start-level 'region))
13633 org-loop-over-headlines-in-active-region)
13634 (org-map-entries
13635 ;; We don't use ARG and JUST-ALIGN here these args are not
13636 ;; useful when looping over headlines
13637 `(org-set-tags)
13638 org-loop-over-headlines-in-active-region
13639 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13640 (let* ((re org-outline-regexp-bol)
13641 (current (unless arg (org-get-tags-string)))
13642 (col (current-column))
13643 (org-setting-tags t)
13644 table current-tags inherited-tags ; computed below when needed
13645 tags p0 c0 c1 rpl di tc level)
13646 (if arg
13647 (save-excursion
13648 (goto-char (point-min))
13649 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13650 (while (re-search-forward re nil t)
13651 (org-set-tags nil t)
13652 (end-of-line 1)))
13653 (message "All tags realigned to column %d" org-tags-column))
13654 (if just-align
13655 (setq tags current)
13656 ;; Get a new set of tags from the user
13657 (save-excursion
13658 (setq table (append org-tag-persistent-alist
13659 (or org-tag-alist (org-get-buffer-tags))
13660 (and
13661 org-complete-tags-always-offer-all-agenda-tags
13662 (org-global-tags-completion-table
13663 (org-agenda-files))))
13664 org-last-tags-completion-table table
13665 current-tags (org-split-string current ":")
13666 inherited-tags (nreverse
13667 (nthcdr (length current-tags)
13668 (nreverse (org-get-tags-at))))
13669 tags
13670 (if (or (eq t org-use-fast-tag-selection)
13671 (and org-use-fast-tag-selection
13672 (delq nil (mapcar 'cdr table))))
13673 (org-fast-tag-selection
13674 current-tags inherited-tags table
13675 (if org-fast-tag-selection-include-todo
13676 org-todo-key-alist))
13677 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13678 (org-trim
13679 (org-icompleting-read "Tags: "
13680 'org-tags-completion-function
13681 nil nil current 'org-tags-history))))))
13682 (while (string-match "[-+&]+" tags)
13683 ;; No boolean logic, just a list
13684 (setq tags (replace-match ":" t t tags))))
13686 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13688 (if org-tags-sort-function
13689 (setq tags (mapconcat 'identity
13690 (sort (org-split-string
13691 tags (org-re "[^[:alnum:]_@#%]+"))
13692 org-tags-sort-function) ":")))
13694 (if (string-match "\\`[\t ]*\\'" tags)
13695 (setq tags "")
13696 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13697 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13699 ;; Insert new tags at the correct column
13700 (beginning-of-line 1)
13701 (setq level (or (and (looking-at org-outline-regexp)
13702 (- (match-end 0) (point) 1))
13704 (cond
13705 ((and (equal current "") (equal tags "")))
13706 ((re-search-forward
13707 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13708 (point-at-eol) t)
13709 (if (equal tags "")
13710 (setq rpl "")
13711 (goto-char (match-beginning 0))
13712 (setq c0 (current-column)
13713 ;; compute offset for the case of org-indent-mode active
13714 di (if org-indent-mode
13715 (* (1- org-indent-indentation-per-level) (1- level))
13717 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13718 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13719 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13720 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13721 (replace-match rpl t t)
13722 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13723 tags)
13724 (t (error "Tags alignment failed")))
13725 (org-move-to-column col)
13726 (unless just-align
13727 (run-hooks 'org-after-tags-change-hook))))))
13729 (defun org-change-tag-in-region (beg end tag off)
13730 "Add or remove TAG for each entry in the region.
13731 This works in the agenda, and also in an org-mode buffer."
13732 (interactive
13733 (list (region-beginning) (region-end)
13734 (let ((org-last-tags-completion-table
13735 (if (derived-mode-p 'org-mode)
13736 (org-get-buffer-tags)
13737 (org-global-tags-completion-table))))
13738 (org-icompleting-read
13739 "Tag: " 'org-tags-completion-function nil nil nil
13740 'org-tags-history))
13741 (progn
13742 (message "[s]et or [r]emove? ")
13743 (equal (read-char-exclusive) ?r))))
13744 (if (fboundp 'deactivate-mark) (deactivate-mark))
13745 (let ((agendap (equal major-mode 'org-agenda-mode))
13746 l1 l2 m buf pos newhead (cnt 0))
13747 (goto-char end)
13748 (setq l2 (1- (org-current-line)))
13749 (goto-char beg)
13750 (setq l1 (org-current-line))
13751 (loop for l from l1 to l2 do
13752 (org-goto-line l)
13753 (setq m (get-text-property (point) 'org-hd-marker))
13754 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13755 (and agendap m))
13756 (setq buf (if agendap (marker-buffer m) (current-buffer))
13757 pos (if agendap m (point)))
13758 (with-current-buffer buf
13759 (save-excursion
13760 (save-restriction
13761 (goto-char pos)
13762 (setq cnt (1+ cnt))
13763 (org-toggle-tag tag (if off 'off 'on))
13764 (setq newhead (org-get-heading)))))
13765 (and agendap (org-agenda-change-all-lines newhead m))))
13766 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13768 (defun org-tags-completion-function (string predicate &optional flag)
13769 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13770 (confirm (lambda (x) (stringp (car x)))))
13771 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13772 (setq s1 (match-string 1 string)
13773 s2 (match-string 2 string))
13774 (setq s1 "" s2 string))
13775 (cond
13776 ((eq flag nil)
13777 ;; try completion
13778 (setq rtn (try-completion s2 ctable confirm))
13779 (if (stringp rtn)
13780 (setq rtn
13781 (concat s1 s2 (substring rtn (length s2))
13782 (if (and org-add-colon-after-tag-completion
13783 (assoc rtn ctable))
13784 ":" ""))))
13785 rtn)
13786 ((eq flag t)
13787 ;; all-completions
13788 (all-completions s2 ctable confirm)
13790 ((eq flag 'lambda)
13791 ;; exact match?
13792 (assoc s2 ctable)))
13795 (defun org-fast-tag-insert (kwd tags face &optional end)
13796 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13797 (insert (format "%-12s" (concat kwd ":"))
13798 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13799 (or end "")))
13801 (defun org-fast-tag-show-exit (flag)
13802 (save-excursion
13803 (org-goto-line 3)
13804 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13805 (replace-match ""))
13806 (when flag
13807 (end-of-line 1)
13808 (org-move-to-column (- (window-width) 19) t)
13809 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13811 (defun org-set-current-tags-overlay (current prefix)
13812 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13813 (if (featurep 'xemacs)
13814 (org-overlay-display org-tags-overlay (concat prefix s)
13815 'secondary-selection)
13816 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13817 (org-overlay-display org-tags-overlay (concat prefix s)))))
13819 (defvar org-last-tag-selection-key nil)
13820 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13821 "Fast tag selection with single keys.
13822 CURRENT is the current list of tags in the headline, INHERITED is the
13823 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13824 possibly with grouping information. TODO-TABLE is a similar table with
13825 TODO keywords, should these have keys assigned to them.
13826 If the keys are nil, a-z are automatically assigned.
13827 Returns the new tags string, or nil to not change the current settings."
13828 (let* ((fulltable (append table todo-table))
13829 (maxlen (apply 'max (mapcar
13830 (lambda (x)
13831 (if (stringp (car x)) (string-width (car x)) 0))
13832 fulltable)))
13833 (buf (current-buffer))
13834 (expert (eq org-fast-tag-selection-single-key 'expert))
13835 (buffer-tags nil)
13836 (fwidth (+ maxlen 3 1 3))
13837 (ncol (/ (- (window-width) 4) fwidth))
13838 (i-face 'org-done)
13839 (c-face 'org-todo)
13840 tg cnt e c char c1 c2 ntable tbl rtn
13841 ov-start ov-end ov-prefix
13842 (exit-after-next org-fast-tag-selection-single-key)
13843 (done-keywords org-done-keywords)
13844 groups ingroup)
13845 (save-excursion
13846 (beginning-of-line 1)
13847 (if (looking-at
13848 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13849 (setq ov-start (match-beginning 1)
13850 ov-end (match-end 1)
13851 ov-prefix "")
13852 (setq ov-start (1- (point-at-eol))
13853 ov-end (1+ ov-start))
13854 (skip-chars-forward "^\n\r")
13855 (setq ov-prefix
13856 (concat
13857 (buffer-substring (1- (point)) (point))
13858 (if (> (current-column) org-tags-column)
13860 (make-string (- org-tags-column (current-column)) ?\ ))))))
13861 (move-overlay org-tags-overlay ov-start ov-end)
13862 (save-window-excursion
13863 (if expert
13864 (set-buffer (get-buffer-create " *Org tags*"))
13865 (delete-other-windows)
13866 (split-window-vertically)
13867 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13868 (erase-buffer)
13869 (org-set-local 'org-done-keywords done-keywords)
13870 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13871 (org-fast-tag-insert "Current" current c-face "\n\n")
13872 (org-fast-tag-show-exit exit-after-next)
13873 (org-set-current-tags-overlay current ov-prefix)
13874 (setq tbl fulltable char ?a cnt 0)
13875 (while (setq e (pop tbl))
13876 (cond
13877 ((equal (car e) :startgroup)
13878 (push '() groups) (setq ingroup t)
13879 (when (not (= cnt 0))
13880 (setq cnt 0)
13881 (insert "\n"))
13882 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13883 ((equal (car e) :endgroup)
13884 (setq ingroup nil cnt 0)
13885 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13886 ((equal e '(:newline))
13887 (when (not (= cnt 0))
13888 (setq cnt 0)
13889 (insert "\n")
13890 (setq e (car tbl))
13891 (while (equal (car tbl) '(:newline))
13892 (insert "\n")
13893 (setq tbl (cdr tbl)))))
13895 (setq tg (copy-sequence (car e)) c2 nil)
13896 (if (cdr e)
13897 (setq c (cdr e))
13898 ;; automatically assign a character.
13899 (setq c1 (string-to-char
13900 (downcase (substring
13901 tg (if (= (string-to-char tg) ?@) 1 0)))))
13902 (if (or (rassoc c1 ntable) (rassoc c1 table))
13903 (while (or (rassoc char ntable) (rassoc char table))
13904 (setq char (1+ char)))
13905 (setq c2 c1))
13906 (setq c (or c2 char)))
13907 (if ingroup (push tg (car groups)))
13908 (setq tg (org-add-props tg nil 'face
13909 (cond
13910 ((not (assoc tg table))
13911 (org-get-todo-face tg))
13912 ((member tg current) c-face)
13913 ((member tg inherited) i-face))))
13914 (if (and (= cnt 0) (not ingroup)) (insert " "))
13915 (insert "[" c "] " tg (make-string
13916 (- fwidth 4 (length tg)) ?\ ))
13917 (push (cons tg c) ntable)
13918 (when (= (setq cnt (1+ cnt)) ncol)
13919 (insert "\n")
13920 (if ingroup (insert " "))
13921 (setq cnt 0)))))
13922 (setq ntable (nreverse ntable))
13923 (insert "\n")
13924 (goto-char (point-min))
13925 (if (not expert) (org-fit-window-to-buffer))
13926 (setq rtn
13927 (catch 'exit
13928 (while t
13929 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13930 (if (not groups) "no " "")
13931 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13932 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13933 (setq org-last-tag-selection-key c)
13934 (cond
13935 ((= c ?\r) (throw 'exit t))
13936 ((= c ?!)
13937 (setq groups (not groups))
13938 (goto-char (point-min))
13939 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13940 ((= c ?\C-c)
13941 (if (not expert)
13942 (org-fast-tag-show-exit
13943 (setq exit-after-next (not exit-after-next)))
13944 (setq expert nil)
13945 (delete-other-windows)
13946 (set-window-buffer (split-window-vertically) " *Org tags*")
13947 (org-switch-to-buffer-other-window " *Org tags*")
13948 (org-fit-window-to-buffer)))
13949 ((or (= c ?\C-g)
13950 (and (= c ?q) (not (rassoc c ntable))))
13951 (org-detach-overlay org-tags-overlay)
13952 (setq quit-flag t))
13953 ((= c ?\ )
13954 (setq current nil)
13955 (if exit-after-next (setq exit-after-next 'now)))
13956 ((= c ?\t)
13957 (condition-case nil
13958 (setq tg (org-icompleting-read
13959 "Tag: "
13960 (or buffer-tags
13961 (with-current-buffer buf
13962 (org-get-buffer-tags)))))
13963 (quit (setq tg "")))
13964 (when (string-match "\\S-" tg)
13965 (add-to-list 'buffer-tags (list tg))
13966 (if (member tg current)
13967 (setq current (delete tg current))
13968 (push tg current)))
13969 (if exit-after-next (setq exit-after-next 'now)))
13970 ((setq e (rassoc c todo-table) tg (car e))
13971 (with-current-buffer buf
13972 (save-excursion (org-todo tg)))
13973 (if exit-after-next (setq exit-after-next 'now)))
13974 ((setq e (rassoc c ntable) tg (car e))
13975 (if (member tg current)
13976 (setq current (delete tg current))
13977 (loop for g in groups do
13978 (if (member tg g)
13979 (mapc (lambda (x)
13980 (setq current (delete x current)))
13981 g)))
13982 (push tg current))
13983 (if exit-after-next (setq exit-after-next 'now))))
13985 ;; Create a sorted list
13986 (setq current
13987 (sort current
13988 (lambda (a b)
13989 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13990 (if (eq exit-after-next 'now) (throw 'exit t))
13991 (goto-char (point-min))
13992 (beginning-of-line 2)
13993 (delete-region (point) (point-at-eol))
13994 (org-fast-tag-insert "Current" current c-face)
13995 (org-set-current-tags-overlay current ov-prefix)
13996 (while (re-search-forward
13997 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13998 (setq tg (match-string 1))
13999 (add-text-properties
14000 (match-beginning 1) (match-end 1)
14001 (list 'face
14002 (cond
14003 ((member tg current) c-face)
14004 ((member tg inherited) i-face)
14005 (t (get-text-property (match-beginning 1) 'face))))))
14006 (goto-char (point-min)))))
14007 (org-detach-overlay org-tags-overlay)
14008 (if rtn
14009 (mapconcat 'identity current ":")
14010 nil))))
14012 (defun org-get-tags-string ()
14013 "Get the TAGS string in the current headline."
14014 (unless (org-at-heading-p t)
14015 (error "Not on a heading"))
14016 (save-excursion
14017 (beginning-of-line 1)
14018 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14019 (org-match-string-no-properties 1)
14020 "")))
14022 (defun org-get-tags ()
14023 "Get the list of tags specified in the current headline."
14024 (org-split-string (org-get-tags-string) ":"))
14026 (defun org-get-buffer-tags ()
14027 "Get a table of all tags used in the buffer, for completion."
14028 (let (tags)
14029 (save-excursion
14030 (goto-char (point-min))
14031 (while (re-search-forward
14032 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14033 (when (equal (char-after (point-at-bol 0)) ?*)
14034 (mapc (lambda (x) (add-to-list 'tags x))
14035 (org-split-string (org-match-string-no-properties 1) ":")))))
14036 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14037 (mapcar 'list tags)))
14039 ;;;; The mapping API
14041 (defun org-map-entries (func &optional match scope &rest skip)
14042 "Call FUNC at each headline selected by MATCH in SCOPE.
14044 FUNC is a function or a lisp form. The function will be called without
14045 arguments, with the cursor positioned at the beginning of the headline.
14046 The return values of all calls to the function will be collected and
14047 returned as a list.
14049 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14050 does not need to preserve point. After evaluation, the cursor will be
14051 moved to the end of the line (presumably of the headline of the
14052 processed entry) and search continues from there. Under some
14053 circumstances, this may not produce the wanted results. For example,
14054 if you have removed (e.g. archived) the current (sub)tree it could
14055 mean that the next entry will be skipped entirely. In such cases, you
14056 can specify the position from where search should continue by making
14057 FUNC set the variable `org-map-continue-from' to the desired buffer
14058 position.
14060 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14061 Only headlines that are matched by this query will be considered during
14062 the iteration. When MATCH is nil or t, all headlines will be
14063 visited by the iteration.
14065 SCOPE determines the scope of this command. It can be any of:
14067 nil The current buffer, respecting the restriction if any
14068 tree The subtree started with the entry at point
14069 region The entries within the active region, if any
14070 region-start-level
14071 The entries within the active region, but only those at
14072 the same level than the first one.
14073 file The current buffer, without restriction
14074 file-with-archives
14075 The current buffer, and any archives associated with it
14076 agenda All agenda files
14077 agenda-with-archives
14078 All agenda files with any archive files associated with them
14079 \(file1 file2 ...)
14080 If this is a list, all files in the list will be scanned
14082 The remaining args are treated as settings for the skipping facilities of
14083 the scanner. The following items can be given here:
14085 archive skip trees with the archive tag.
14086 comment skip trees with the COMMENT keyword
14087 function or Emacs Lisp form:
14088 will be used as value for `org-agenda-skip-function', so whenever
14089 the function returns t, FUNC will not be called for that
14090 entry and search will continue from the point where the
14091 function leaves it.
14093 If your function needs to retrieve the tags including inherited tags
14094 at the *current* entry, you can use the value of the variable
14095 `org-scanner-tags' which will be much faster than getting the value
14096 with `org-get-tags-at'. If your function gets properties with
14097 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14098 to t around the call to `org-entry-properties' to get the same speedup.
14099 Note that if your function moves around to retrieve tags and properties at
14100 a *different* entry, you cannot use these techniques."
14101 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14102 (not (org-region-active-p)))
14103 (let* ((org-agenda-archives-mode nil) ; just to make sure
14104 (org-agenda-skip-archived-trees (memq 'archive skip))
14105 (org-agenda-skip-comment-trees (memq 'comment skip))
14106 (org-agenda-skip-function
14107 (car (org-delete-all '(comment archive) skip)))
14108 (org-tags-match-list-sublevels t)
14109 (start-level (eq scope 'region-start-level))
14110 matcher file res
14111 org-todo-keywords-for-agenda
14112 org-done-keywords-for-agenda
14113 org-todo-keyword-alist-for-agenda
14114 org-drawers-for-agenda
14115 org-tag-alist-for-agenda
14116 todo-only)
14118 (cond
14119 ((eq match t) (setq matcher t))
14120 ((eq match nil) (setq matcher t))
14121 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14123 (save-excursion
14124 (save-restriction
14125 (cond ((eq scope 'tree)
14126 (org-back-to-heading t)
14127 (org-narrow-to-subtree)
14128 (setq scope nil))
14129 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14130 (org-region-active-p))
14131 ;; If needed, set start-level to a string like "2"
14132 (when start-level
14133 (save-excursion
14134 (goto-char (region-beginning))
14135 (unless (org-at-heading-p) (outline-next-heading))
14136 (setq start-level (org-current-level))))
14137 (narrow-to-region (region-beginning)
14138 (save-excursion
14139 (goto-char (region-end))
14140 (unless (and (bolp) (org-at-heading-p))
14141 (outline-next-heading))
14142 (point)))
14143 (setq scope nil)))
14145 (if (not scope)
14146 (progn
14147 (org-agenda-prepare-buffers
14148 (list (buffer-file-name (current-buffer))))
14149 (setq res (org-scan-tags func matcher todo-only start-level)))
14150 ;; Get the right scope
14151 (cond
14152 ((and scope (listp scope) (symbolp (car scope)))
14153 (setq scope (eval scope)))
14154 ((eq scope 'agenda)
14155 (setq scope (org-agenda-files t)))
14156 ((eq scope 'agenda-with-archives)
14157 (setq scope (org-agenda-files t))
14158 (setq scope (org-add-archive-files scope)))
14159 ((eq scope 'file)
14160 (setq scope (list (buffer-file-name))))
14161 ((eq scope 'file-with-archives)
14162 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14163 (org-agenda-prepare-buffers scope)
14164 (while (setq file (pop scope))
14165 (with-current-buffer (org-find-base-buffer-visiting file)
14166 (save-excursion
14167 (save-restriction
14168 (widen)
14169 (goto-char (point-min))
14170 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14171 res)))
14173 ;;;; Properties
14175 ;;; Setting and retrieving properties
14177 (defconst org-special-properties
14178 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14179 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14180 "The special properties valid in Org-mode.
14182 These are properties that are not defined in the property drawer,
14183 but in some other way.")
14185 (defconst org-default-properties
14186 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14187 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14188 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14189 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14190 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14191 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14192 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14193 "Some properties that are used by Org-mode for various purposes.
14194 Being in this list makes sure that they are offered for completion.")
14196 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14197 "Regular expression matching the first line of a property drawer.")
14199 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14200 "Regular expression matching the last line of a property drawer.")
14202 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14203 "Regular expression matching the first line of a property drawer.")
14205 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14206 "Regular expression matching the first line of a property drawer.")
14208 (defconst org-property-drawer-re
14209 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14210 org-property-end-re "\\)\n?")
14211 "Matches an entire property drawer.")
14213 (defconst org-clock-drawer-re
14214 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14215 org-property-end-re "\\)\n?")
14216 "Matches an entire clock drawer.")
14218 (defsubst org-re-property (property)
14219 "Return a regexp matching a PROPERTY line.
14220 Match group 1 will be set to the value."
14221 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14223 (defsubst org-re-property-keyword (property)
14224 "Return a regexp matching a PROPERTY line, possibly with no
14225 value for the property."
14226 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14228 (defun org-property-action ()
14229 "Do an action on properties."
14230 (interactive)
14231 (let (c)
14232 (org-at-property-p)
14233 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14234 (setq c (read-char-exclusive))
14235 (cond
14236 ((equal c ?s)
14237 (call-interactively 'org-set-property))
14238 ((equal c ?d)
14239 (call-interactively 'org-delete-property))
14240 ((equal c ?D)
14241 (call-interactively 'org-delete-property-globally))
14242 ((equal c ?c)
14243 (call-interactively 'org-compute-property-at-point))
14244 (t (error "No such property action %c" c)))))
14246 (defun org-inc-effort ()
14247 "Increment the value of the effort property in the current entry."
14248 (interactive)
14249 (org-set-effort nil t))
14251 (defun org-set-effort (&optional value increment)
14252 "Set the effort property of the current entry.
14253 With numerical prefix arg, use the nth allowed value, 0 stands for the
14254 10th allowed value.
14256 When INCREMENT is non-nil, set the property to the next allowed value."
14257 (interactive "P")
14258 (if (equal value 0) (setq value 10))
14259 (let* ((completion-ignore-case t)
14260 (prop org-effort-property)
14261 (cur (org-entry-get nil prop))
14262 (allowed (org-property-get-allowed-values nil prop 'table))
14263 (existing (mapcar 'list (org-property-values prop)))
14265 (val (cond
14266 ((stringp value) value)
14267 ((and allowed (integerp value))
14268 (or (car (nth (1- value) allowed))
14269 (car (org-last allowed))))
14270 ((and allowed increment)
14271 (or (caadr (member (list cur) allowed))
14272 (error "Allowed effort values are not set")))
14273 (allowed
14274 (message "Select 1-9,0, [RET%s]: %s"
14275 (if cur (concat "=" cur) "")
14276 (mapconcat 'car allowed " "))
14277 (setq rpl (read-char-exclusive))
14278 (if (equal rpl ?\r)
14280 (setq rpl (- rpl ?0))
14281 (if (equal rpl 0) (setq rpl 10))
14282 (if (and (> rpl 0) (<= rpl (length allowed)))
14283 (car (nth (1- rpl) allowed))
14284 (org-completing-read "Effort: " allowed nil))))
14286 (let (org-completion-use-ido org-completion-use-iswitchb)
14287 (org-completing-read
14288 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14289 (concat "[" cur "]") "")
14290 ": ")
14291 existing nil nil "" nil cur))))))
14292 (unless (equal (org-entry-get nil prop) val)
14293 (org-entry-put nil prop val))
14294 (message "%s is now %s" prop val)))
14296 (defun org-at-property-p ()
14297 "Is cursor inside a property drawer?"
14298 (save-excursion
14299 (beginning-of-line 1)
14300 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14301 (save-match-data ;; Used by calling procedures
14302 (let ((p (point))
14303 (range (unless (org-before-first-heading-p)
14304 (org-get-property-block))))
14305 (and range (<= (car range) p) (< p (cdr range))))))))
14307 (defun org-get-property-block (&optional beg end force)
14308 "Return the (beg . end) range of the body of the property drawer.
14309 BEG and END are the beginning and end of the current subtree, or of
14310 the part before the first headline. If they are not given, they will
14311 be found. If the drawer does not exist and FORCE is non-nil, create
14312 the drawer."
14313 (catch 'exit
14314 (save-excursion
14315 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14316 (progn (org-back-to-heading t) (point))))
14317 (end (or end (and (not (outline-next-heading)) (point-max))
14318 (point))))
14319 (goto-char beg)
14320 (if (re-search-forward org-property-start-re end t)
14321 (setq beg (1+ (match-end 0)))
14322 (if force
14323 (save-excursion
14324 (org-insert-property-drawer)
14325 (setq end (progn (outline-next-heading) (point))))
14326 (throw 'exit nil))
14327 (goto-char beg)
14328 (if (re-search-forward org-property-start-re end t)
14329 (setq beg (1+ (match-end 0)))))
14330 (if (re-search-forward org-property-end-re end t)
14331 (setq end (match-beginning 0))
14332 (or force (throw 'exit nil))
14333 (goto-char beg)
14334 (setq end beg)
14335 (org-indent-line)
14336 (insert ":END:\n"))
14337 (cons beg end)))))
14339 (defun org-entry-properties (&optional pom which specific)
14340 "Get all properties of the entry at point-or-marker POM.
14341 This includes the TODO keyword, the tags, time strings for deadline,
14342 scheduled, and clocking, and any additional properties defined in the
14343 entry. The return value is an alist, keys may occur multiple times
14344 if the property key was used several times.
14345 POM may also be nil, in which case the current entry is used.
14346 If WHICH is nil or `all', get all properties. If WHICH is
14347 `special' or `standard', only get that subclass. If WHICH
14348 is a string only get exactly this property. SPECIFIC can be a string, the
14349 specific property we are interested in. Specifying it can speed
14350 things up because then unnecessary parsing is avoided."
14351 (setq which (or which 'all))
14352 (org-with-point-at pom
14353 (let ((clockstr (substring org-clock-string 0 -1))
14354 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14355 (case-fold-search nil)
14356 beg end range props sum-props key key1 value string clocksum clocksumt)
14357 (save-excursion
14358 (when (condition-case nil
14359 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14360 (error nil))
14361 (setq beg (point))
14362 (setq sum-props (get-text-property (point) 'org-summaries))
14363 (setq clocksum (get-text-property (point) :org-clock-minutes)
14364 clocksumt (get-text-property (point) :org-clock-minutes-today))
14365 (outline-next-heading)
14366 (setq end (point))
14367 (when (memq which '(all special))
14368 ;; Get the special properties, like TODO and tags
14369 (goto-char beg)
14370 (when (and (or (not specific) (string= specific "TODO"))
14371 (looking-at org-todo-line-regexp) (match-end 2))
14372 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14373 (when (and (or (not specific) (string= specific "PRIORITY"))
14374 (looking-at org-priority-regexp))
14375 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14376 (when (or (not specific) (string= specific "FILE"))
14377 (push (cons "FILE" buffer-file-name) props))
14378 (when (and (or (not specific) (string= specific "TAGS"))
14379 (setq value (org-get-tags-string))
14380 (string-match "\\S-" value))
14381 (push (cons "TAGS" value) props))
14382 (when (and (or (not specific) (string= specific "ALLTAGS"))
14383 (setq value (org-get-tags-at)))
14384 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14385 ":"))
14386 props))
14387 (when (or (not specific) (string= specific "BLOCKED"))
14388 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14389 (when (or (not specific)
14390 (member specific
14391 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14392 "TIMESTAMP" "TIMESTAMP_IA")))
14393 (catch 'match
14394 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14395 (setq key (if (match-end 1)
14396 (substring (org-match-string-no-properties 1)
14397 0 -1))
14398 string (if (equal key clockstr)
14399 (org-trim
14400 (buffer-substring-no-properties
14401 (match-beginning 3) (goto-char
14402 (point-at-eol))))
14403 (substring (org-match-string-no-properties 3)
14404 1 -1)))
14405 ;; Get the correct property name from the key. This is
14406 ;; necessary if the user has configured time keywords.
14407 (setq key1 (concat key ":"))
14408 (cond
14409 ((not key)
14410 (setq key
14411 (if (= (char-after (match-beginning 3)) ?\[)
14412 "TIMESTAMP_IA" "TIMESTAMP")))
14413 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14414 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14415 ((equal key1 org-closed-string) (setq key "CLOSED"))
14416 ((equal key1 org-clock-string) (setq key "CLOCK")))
14417 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14418 (progn
14419 (push (cons key string) props)
14420 ;; no need to search further if match is found
14421 (throw 'match t))
14422 (when (or (equal key "CLOCK") (not (assoc key props)))
14423 (push (cons key string) props)))))))
14425 (when (memq which '(all standard))
14426 ;; Get the standard properties, like :PROP: ...
14427 (setq range (org-get-property-block beg end))
14428 (when range
14429 (goto-char (car range))
14430 (while (re-search-forward
14431 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14432 (cdr range) t)
14433 (setq key (org-match-string-no-properties 1)
14434 value (org-trim (or (org-match-string-no-properties 2) "")))
14435 (unless (member key excluded)
14436 (push (cons key (or value "")) props)))))
14437 (if clocksum
14438 (push (cons "CLOCKSUM"
14439 (org-columns-number-to-string (/ (float clocksum) 60.)
14440 'add_times))
14441 props))
14442 (if clocksumt
14443 (push (cons "CLOCKSUM_T"
14444 (org-columns-number-to-string (/ (float clocksumt) 60.)
14445 'add_times))
14446 props))
14447 (unless (assoc "CATEGORY" props)
14448 (push (cons "CATEGORY" (org-get-category)) props))
14449 (append sum-props (nreverse props)))))))
14451 (defun org-entry-get (pom property &optional inherit literal-nil)
14452 "Get value of PROPERTY for entry or content at point-or-marker POM.
14453 If INHERIT is non-nil and the entry does not have the property,
14454 then also check higher levels of the hierarchy.
14455 If INHERIT is the symbol `selective', use inheritance only if the setting
14456 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14457 If the property is present but empty, the return value is the empty string.
14458 If the property is not present at all, nil is returned.
14460 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14461 do not interpret it as the list atom nil. This is used for inheritance
14462 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14463 (org-with-point-at pom
14464 (if (and inherit (if (eq inherit 'selective)
14465 (org-property-inherit-p property)
14467 (org-entry-get-with-inheritance property literal-nil)
14468 (if (member property org-special-properties)
14469 ;; We need a special property. Use `org-entry-properties' to
14470 ;; retrieve it, but specify the wanted property
14471 (cdr (assoc property (org-entry-properties nil 'special property)))
14472 (let* ((range (org-get-property-block))
14473 (props (list (or (assoc property org-file-properties)
14474 (assoc property org-global-properties)
14475 (assoc property org-global-properties-fixed))))
14476 (ap (lambda (key)
14477 (when (re-search-forward
14478 (org-re-property key) (cdr range) t)
14479 (setq props
14480 (org-update-property-plist
14482 (if (match-end 1)
14483 (org-match-string-no-properties 1) "")
14484 props)))))
14485 val)
14486 (when (and range (goto-char (car range)))
14487 (funcall ap property)
14488 (goto-char (car range))
14489 (while (funcall ap (concat property "+")))
14490 (setq val (cdr (assoc property props)))
14491 (when val (if literal-nil val (org-not-nil val)))))))))
14493 (defun org-property-or-variable-value (var &optional inherit)
14494 "Check if there is a property fixing the value of VAR.
14495 If yes, return this value. If not, return the current value of the variable."
14496 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14497 (if (and prop (stringp prop) (string-match "\\S-" prop))
14498 (read prop)
14499 (symbol-value var))))
14501 (defun org-entry-delete (pom property)
14502 "Delete the property PROPERTY from entry at point-or-marker POM."
14503 (org-with-point-at pom
14504 (if (member property org-special-properties)
14505 nil ; cannot delete these properties.
14506 (let ((range (org-get-property-block)))
14507 (if (and range
14508 (goto-char (car range))
14509 (re-search-forward
14510 (org-re-property property)
14511 (cdr range) t))
14512 (progn
14513 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14515 nil)))))
14517 ;; Multi-values properties are properties that contain multiple values
14518 ;; These values are assumed to be single words, separated by whitespace.
14519 (defun org-entry-add-to-multivalued-property (pom property value)
14520 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14521 (let* ((old (org-entry-get pom property))
14522 (values (and old (org-split-string old "[ \t]"))))
14523 (setq value (org-entry-protect-space value))
14524 (unless (member value values)
14525 (setq values (cons value values))
14526 (org-entry-put pom property
14527 (mapconcat 'identity values " ")))))
14529 (defun org-entry-remove-from-multivalued-property (pom property value)
14530 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14531 (let* ((old (org-entry-get pom property))
14532 (values (and old (org-split-string old "[ \t]"))))
14533 (setq value (org-entry-protect-space value))
14534 (when (member value values)
14535 (setq values (delete value values))
14536 (org-entry-put pom property
14537 (mapconcat 'identity values " ")))))
14539 (defun org-entry-member-in-multivalued-property (pom property value)
14540 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14541 (let* ((old (org-entry-get pom property))
14542 (values (and old (org-split-string old "[ \t]"))))
14543 (setq value (org-entry-protect-space value))
14544 (member value values)))
14546 (defun org-entry-get-multivalued-property (pom property)
14547 "Return a list of values in a multivalued property."
14548 (let* ((value (org-entry-get pom property))
14549 (values (and value (org-split-string value "[ \t]"))))
14550 (mapcar 'org-entry-restore-space values)))
14552 (defun org-entry-put-multivalued-property (pom property &rest values)
14553 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14554 VALUES should be a list of strings. Spaces will be protected."
14555 (org-entry-put pom property
14556 (mapconcat 'org-entry-protect-space values " "))
14557 (let* ((value (org-entry-get pom property))
14558 (values (and value (org-split-string value "[ \t]"))))
14559 (mapcar 'org-entry-restore-space values)))
14561 (defun org-entry-protect-space (s)
14562 "Protect spaces and newline in string S."
14563 (while (string-match " " s)
14564 (setq s (replace-match "%20" t t s)))
14565 (while (string-match "\n" s)
14566 (setq s (replace-match "%0A" t t s)))
14569 (defun org-entry-restore-space (s)
14570 "Restore spaces and newline in string S."
14571 (while (string-match "%20" s)
14572 (setq s (replace-match " " t t s)))
14573 (while (string-match "%0A" s)
14574 (setq s (replace-match "\n" t t s)))
14577 (defvar org-entry-property-inherited-from (make-marker)
14578 "Marker pointing to the entry from where a property was inherited.
14579 Each call to `org-entry-get-with-inheritance' will set this marker to the
14580 location of the entry where the inheritance search matched. If there was
14581 no match, the marker will point nowhere.
14582 Note that also `org-entry-get' calls this function, if the INHERIT flag
14583 is set.")
14585 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14586 "Get PROPERTY of entry or content at point, search higher levels if needed.
14587 The search will stop at the first ancestor which has the property defined.
14588 If the value found is \"nil\", return nil to show that the property
14589 should be considered as undefined (this is the meaning of nil here).
14590 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14591 (move-marker org-entry-property-inherited-from nil)
14592 (let (tmp)
14593 (save-excursion
14594 (save-restriction
14595 (widen)
14596 (catch 'ex
14597 (while t
14598 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14599 (or (ignore-errors (org-back-to-heading t))
14600 (goto-char (point-min)))
14601 (move-marker org-entry-property-inherited-from (point))
14602 (throw 'ex tmp))
14603 (or (ignore-errors (org-up-heading-safe))
14604 (throw 'ex nil))))))
14605 (setq tmp (or tmp
14606 (cdr (assoc property org-file-properties))
14607 (cdr (assoc property org-global-properties))
14608 (cdr (assoc property org-global-properties-fixed))))
14609 (if literal-nil tmp (org-not-nil tmp))))
14611 (defvar org-property-changed-functions nil
14612 "Hook called when the value of a property has changed.
14613 Each hook function should accept two arguments, the name of the property
14614 and the new value.")
14616 (defun org-entry-put (pom property value)
14617 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14618 (org-with-point-at pom
14619 (org-back-to-heading t)
14620 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14621 range)
14622 (cond
14623 ((equal property "TODO")
14624 (when (and (stringp value) (string-match "\\S-" value)
14625 (not (member value org-todo-keywords-1)))
14626 (error "\"%s\" is not a valid TODO state" value))
14627 (if (or (not value)
14628 (not (string-match "\\S-" value)))
14629 (setq value 'none))
14630 (org-todo value)
14631 (org-set-tags nil 'align))
14632 ((equal property "PRIORITY")
14633 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14634 (string-to-char value) ?\ ))
14635 (org-set-tags nil 'align))
14636 ((equal property "SCHEDULED")
14637 (if (re-search-forward org-scheduled-time-regexp end t)
14638 (cond
14639 ((eq value 'earlier) (org-timestamp-change -1 'day))
14640 ((eq value 'later) (org-timestamp-change 1 'day))
14641 (t (call-interactively 'org-schedule)))
14642 (call-interactively 'org-schedule)))
14643 ((equal property "DEADLINE")
14644 (if (re-search-forward org-deadline-time-regexp end t)
14645 (cond
14646 ((eq value 'earlier) (org-timestamp-change -1 'day))
14647 ((eq value 'later) (org-timestamp-change 1 'day))
14648 (t (call-interactively 'org-deadline)))
14649 (call-interactively 'org-deadline)))
14650 ((member property org-special-properties)
14651 (error "The %s property can not yet be set with `org-entry-put'"
14652 property))
14653 (t ; a non-special property
14654 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14655 (setq range (org-get-property-block beg end 'force))
14656 (goto-char (car range))
14657 (if (re-search-forward
14658 (org-re-property-keyword property) (cdr range) t)
14659 (progn
14660 (delete-region (match-beginning 0) (match-end 0))
14661 (goto-char (match-beginning 0)))
14662 (goto-char (cdr range))
14663 (insert "\n")
14664 (backward-char 1)
14665 (org-indent-line))
14666 (insert ":" property ":")
14667 (and value (insert " " value))
14668 (org-indent-line)))))
14669 (run-hook-with-args 'org-property-changed-functions property value)))
14671 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14672 "Get all property keys in the current buffer.
14673 With INCLUDE-SPECIALS, also list the special properties that reflect things
14674 like tags and TODO state.
14675 With INCLUDE-DEFAULTS, also include properties that has special meaning
14676 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14677 and others.
14678 With INCLUDE-COLUMNS, also include property names given in COLUMN
14679 formats in the current buffer."
14680 (let (rtn range cfmt s p)
14681 (save-excursion
14682 (save-restriction
14683 (widen)
14684 (goto-char (point-min))
14685 (while (re-search-forward org-property-start-re nil t)
14686 (setq range (org-get-property-block))
14687 (goto-char (car range))
14688 (while (re-search-forward
14689 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14690 (cdr range) t)
14691 (add-to-list 'rtn (org-match-string-no-properties 1)))
14692 (outline-next-heading))))
14694 (when include-specials
14695 (setq rtn (append org-special-properties rtn)))
14697 (when include-defaults
14698 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14699 (add-to-list 'rtn org-effort-property))
14701 (when include-columns
14702 (save-excursion
14703 (save-restriction
14704 (widen)
14705 (goto-char (point-min))
14706 (while (re-search-forward
14707 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14708 nil t)
14709 (setq cfmt (match-string 2) s 0)
14710 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14711 cfmt s)
14712 (setq s (match-end 0)
14713 p (match-string 1 cfmt))
14714 (unless (or (equal p "ITEM")
14715 (member p org-special-properties))
14716 (add-to-list 'rtn (match-string 1 cfmt))))))))
14718 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14720 (defun org-property-values (key)
14721 "Return a list of all values of property KEY in the current buffer."
14722 (save-excursion
14723 (save-restriction
14724 (widen)
14725 (goto-char (point-min))
14726 (let ((re (org-re-property key))
14727 values)
14728 (while (re-search-forward re nil t)
14729 (add-to-list 'values (org-trim (match-string 1))))
14730 (delete "" values)))))
14732 (defun org-insert-property-drawer ()
14733 "Insert a property drawer into the current entry."
14734 (org-back-to-heading t)
14735 (looking-at org-outline-regexp)
14736 (let ((indent (if org-adapt-indentation
14737 (- (match-end 0) (match-beginning 0))
14739 (beg (point))
14740 (re (concat "^[ \t]*" org-keyword-time-regexp))
14741 end hiddenp)
14742 (outline-next-heading)
14743 (setq end (point))
14744 (goto-char beg)
14745 (while (re-search-forward re end t))
14746 (setq hiddenp (outline-invisible-p))
14747 (end-of-line 1)
14748 (and (equal (char-after) ?\n) (forward-char 1))
14749 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14750 (if (member (match-string 1) '("CLOCK:" ":END:"))
14751 ;; just skip this line
14752 (beginning-of-line 2)
14753 ;; Drawer start, find the end
14754 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14755 (beginning-of-line 1)))
14756 (org-skip-over-state-notes)
14757 (skip-chars-backward " \t\n\r")
14758 (if (eq (char-before) ?*) (forward-char 1))
14759 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14760 (beginning-of-line 0)
14761 (org-indent-to-column indent)
14762 (beginning-of-line 2)
14763 (org-indent-to-column indent)
14764 (beginning-of-line 0)
14765 (if hiddenp
14766 (save-excursion
14767 (org-back-to-heading t)
14768 (hide-entry))
14769 (org-flag-drawer t))))
14771 (defun org-insert-drawer (&optional arg drawer)
14772 "Insert a drawer at point.
14774 Optional argument DRAWER, when non-nil, is a string representing
14775 drawer's name. Otherwise, the user is prompted for a name.
14777 If a region is active, insert the drawer around that region
14778 instead.
14780 Point is left between drawer's boundaries."
14781 (interactive "P")
14782 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14783 "LOGBOOK"))
14784 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14785 ;; internally by Org. They are meant to be inserted
14786 ;; automatically.
14787 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14788 ;; Remove system drawers from list. Note: For some reason,
14789 ;; `org-completing-read' ignores the predicate while
14790 ;; `completing-read' handles it fine.
14791 (drawer (if arg "PROPERTIES"
14792 (or drawer
14793 (completing-read
14794 "Drawer: " org-drawers
14795 (lambda (d) (not (member d system-drawers))))))))
14796 (cond
14797 ;; With C-u, fall back on `org-insert-property-drawer'
14798 (arg (org-insert-property-drawer))
14799 ;; With an active region, insert a drawer at point.
14800 ((not (org-region-active-p))
14801 (progn
14802 (unless (bolp) (insert "\n"))
14803 (insert (format ":%s:\n\n:END:\n" drawer))
14804 (forward-line -2)))
14805 ;; Otherwise, insert the drawer at point
14807 (let ((rbeg (region-beginning))
14808 (rend (copy-marker (region-end))))
14809 (unwind-protect
14810 (progn
14811 (goto-char rbeg)
14812 (beginning-of-line)
14813 (when (save-excursion
14814 (re-search-forward org-outline-regexp-bol rend t))
14815 (error "Drawers cannot contain headlines"))
14816 ;; Position point at the beginning of the first
14817 ;; non-blank line in region. Insert drawer's opening
14818 ;; there, then indent it.
14819 (org-skip-whitespace)
14820 (beginning-of-line)
14821 (insert ":" drawer ":\n")
14822 (forward-line -1)
14823 (indent-for-tab-command)
14824 ;; Move point to the beginning of the first blank line
14825 ;; after the last non-blank line in region. Insert
14826 ;; drawer's closing, then indent it.
14827 (goto-char rend)
14828 (skip-chars-backward " \r\t\n")
14829 (insert "\n:END:")
14830 (deactivate-mark t)
14831 (indent-for-tab-command)
14832 (unless (eolp) (insert "\n")))
14833 ;; Clear marker, whatever the outcome of insertion is.
14834 (set-marker rend nil)))))))
14836 (defvar org-property-set-functions-alist nil
14837 "Property set function alist.
14838 Each entry should have the following format:
14840 (PROPERTY . READ-FUNCTION)
14842 The read function will be called with the same argument as
14843 `org-completing-read'.")
14845 (defun org-set-property-function (property)
14846 "Get the function that should be used to set PROPERTY.
14847 This is computed according to `org-property-set-functions-alist'."
14848 (or (cdr (assoc property org-property-set-functions-alist))
14849 'org-completing-read))
14851 (defun org-read-property-value (property)
14852 "Read PROPERTY value from user."
14853 (let* ((completion-ignore-case t)
14854 (allowed (org-property-get-allowed-values nil property 'table))
14855 (cur (org-entry-get nil property))
14856 (prompt (concat property " value"
14857 (if (and cur (string-match "\\S-" cur))
14858 (concat " [" cur "]") "") ": "))
14859 (set-function (org-set-property-function property))
14860 (val (if allowed
14861 (funcall set-function prompt allowed nil
14862 (not (get-text-property 0 'org-unrestricted
14863 (caar allowed))))
14864 (let (org-completion-use-ido org-completion-use-iswitchb)
14865 (funcall set-function prompt
14866 (mapcar 'list (org-property-values property))
14867 nil nil "" nil cur)))))
14868 (if (equal val "")
14870 val)))
14872 (defvar org-last-set-property nil)
14873 (defun org-read-property-name ()
14874 "Read a property name."
14875 (let* ((completion-ignore-case t)
14876 (keys (org-buffer-property-keys nil t t))
14877 (default-prop (or (save-excursion
14878 (save-match-data
14879 (beginning-of-line)
14880 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14881 (null (string= (match-string 1) "END"))
14882 (match-string 1))))
14883 org-last-set-property))
14884 (property (org-icompleting-read
14885 (concat "Property"
14886 (if default-prop (concat " [" default-prop "]") "")
14887 ": ")
14888 (mapcar 'list keys)
14889 nil nil nil nil
14890 default-prop
14892 (if (member property keys)
14893 property
14894 (or (cdr (assoc (downcase property)
14895 (mapcar (lambda (x) (cons (downcase x) x))
14896 keys)))
14897 property))))
14899 (defun org-set-property (property value)
14900 "In the current entry, set PROPERTY to VALUE.
14901 When called interactively, this will prompt for a property name, offering
14902 completion on existing and default properties. And then it will prompt
14903 for a value, offering completion either on allowed values (via an inherited
14904 xxx_ALL property) or on existing values in other instances of this property
14905 in the current file."
14906 (interactive (list nil nil))
14907 (let* ((property (or property (org-read-property-name)))
14908 (value (or value (org-read-property-value property)))
14909 (fn (cdr (assoc property org-properties-postprocess-alist))))
14910 (setq org-last-set-property property)
14911 ;; Possibly postprocess the inserted value:
14912 (when fn (setq value (funcall fn value)))
14913 (unless (equal (org-entry-get nil property) value)
14914 (org-entry-put nil property value))))
14916 (defun org-delete-property (property)
14917 "In the current entry, delete PROPERTY."
14918 (interactive
14919 (let* ((completion-ignore-case t)
14920 (prop (org-icompleting-read "Property: "
14921 (org-entry-properties nil 'standard))))
14922 (list prop)))
14923 (message "Property %s %s" property
14924 (if (org-entry-delete nil property)
14925 "deleted"
14926 "was not present in the entry")))
14928 (defun org-delete-property-globally (property)
14929 "Remove PROPERTY globally, from all entries."
14930 (interactive
14931 (let* ((completion-ignore-case t)
14932 (prop (org-icompleting-read
14933 "Globally remove property: "
14934 (mapcar 'list (org-buffer-property-keys)))))
14935 (list prop)))
14936 (save-excursion
14937 (save-restriction
14938 (widen)
14939 (goto-char (point-min))
14940 (let ((cnt 0))
14941 (while (re-search-forward
14942 (org-re-property property)
14943 nil t)
14944 (setq cnt (1+ cnt))
14945 (delete-region (match-beginning 0) (1+ (point-at-eol))))
14946 (message "Property \"%s\" removed from %d entries" property cnt)))))
14948 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14950 (defun org-compute-property-at-point ()
14951 "Compute the property at point.
14952 This looks for an enclosing column format, extracts the operator and
14953 then applies it to the property in the column format's scope."
14954 (interactive)
14955 (unless (org-at-property-p)
14956 (error "Not at a property"))
14957 (let ((prop (org-match-string-no-properties 2)))
14958 (org-columns-get-format-and-top-level)
14959 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14960 (error "No operator defined for property %s" prop))
14961 (org-columns-compute prop)))
14963 (defvar org-property-allowed-value-functions nil
14964 "Hook for functions supplying allowed values for a specific property.
14965 The functions must take a single argument, the name of the property, and
14966 return a flat list of allowed values. If \":ETC\" is one of
14967 the values, this means that these values are intended as defaults for
14968 completion, but that other values should be allowed too.
14969 The functions must return nil if they are not responsible for this
14970 property.")
14972 (defun org-property-get-allowed-values (pom property &optional table)
14973 "Get allowed values for the property PROPERTY.
14974 When TABLE is non-nil, return an alist that can directly be used for
14975 completion."
14976 (let (vals)
14977 (cond
14978 ((equal property "TODO")
14979 (setq vals (org-with-point-at pom
14980 (append org-todo-keywords-1 '("")))))
14981 ((equal property "PRIORITY")
14982 (let ((n org-lowest-priority))
14983 (while (>= n org-highest-priority)
14984 (push (char-to-string n) vals)
14985 (setq n (1- n)))))
14986 ((member property org-special-properties))
14987 ((setq vals (run-hook-with-args-until-success
14988 'org-property-allowed-value-functions property)))
14990 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14991 (when (and vals (string-match "\\S-" vals))
14992 (setq vals (car (read-from-string (concat "(" vals ")"))))
14993 (setq vals (mapcar (lambda (x)
14994 (cond ((stringp x) x)
14995 ((numberp x) (number-to-string x))
14996 ((symbolp x) (symbol-name x))
14997 (t "???")))
14998 vals)))))
14999 (when (member ":ETC" vals)
15000 (setq vals (remove ":ETC" vals))
15001 (org-add-props (car vals) '(org-unrestricted t)))
15002 (if table (mapcar 'list vals) vals)))
15004 (defun org-property-previous-allowed-value (&optional previous)
15005 "Switch to the next allowed value for this property."
15006 (interactive)
15007 (org-property-next-allowed-value t))
15009 (defun org-property-next-allowed-value (&optional previous)
15010 "Switch to the next allowed value for this property."
15011 (interactive)
15012 (unless (org-at-property-p)
15013 (error "Not at a property"))
15014 (let* ((key (match-string 2))
15015 (value (match-string 3))
15016 (allowed (or (org-property-get-allowed-values (point) key)
15017 (and (member value '("[ ]" "[-]" "[X]"))
15018 '("[ ]" "[X]"))))
15019 nval)
15020 (unless allowed
15021 (error "Allowed values for this property have not been defined"))
15022 (if previous (setq allowed (reverse allowed)))
15023 (if (member value allowed)
15024 (setq nval (car (cdr (member value allowed)))))
15025 (setq nval (or nval (car allowed)))
15026 (if (equal nval value)
15027 (error "Only one allowed value for this property"))
15028 (org-at-property-p)
15029 (replace-match (concat " :" key ": " nval) t t)
15030 (org-indent-line)
15031 (beginning-of-line 1)
15032 (skip-chars-forward " \t")
15033 (run-hook-with-args 'org-property-changed-functions key nval)))
15035 (defun org-find-olp (path &optional this-buffer)
15036 "Return a marker pointing to the entry at outline path OLP.
15037 If anything goes wrong, throw an error.
15038 You can wrap this call to catch the error like this:
15040 (condition-case msg
15041 (org-mobile-locate-entry (match-string 4))
15042 (error (nth 1 msg)))
15044 The return value will then be either a string with the error message,
15045 or a marker if everything is OK.
15047 If THIS-BUFFER is set, the outline path does not contain a file,
15048 only headings."
15049 (let* ((file (if this-buffer buffer-file-name (pop path)))
15050 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15051 (level 1)
15052 (lmin 1)
15053 (lmax 1)
15054 limit re end found pos heading cnt flevel)
15055 (unless buffer (error "File not found :%s" file))
15056 (with-current-buffer buffer
15057 (save-excursion
15058 (save-restriction
15059 (widen)
15060 (setq limit (point-max))
15061 (goto-char (point-min))
15062 (while (setq heading (pop path))
15063 (setq re (format org-complex-heading-regexp-format
15064 (regexp-quote heading)))
15065 (setq cnt 0 pos (point))
15066 (while (re-search-forward re end t)
15067 (setq level (- (match-end 1) (match-beginning 1)))
15068 (if (and (>= level lmin) (<= level lmax))
15069 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15070 (when (= cnt 0) (error "Heading not found on level %d: %s"
15071 lmax heading))
15072 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15073 lmax heading))
15074 (goto-char found)
15075 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15076 (setq end (save-excursion (org-end-of-subtree t t))))
15077 (when (org-at-heading-p)
15078 (point-marker)))))))
15080 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15081 "Find node HEADING in BUFFER.
15082 Return a marker to the heading if it was found, or nil if not.
15083 If POS-ONLY is set, return just the position instead of a marker.
15085 The heading text must match exact, but it may have a TODO keyword,
15086 a priority cookie and tags in the standard locations."
15087 (with-current-buffer (or buffer (current-buffer))
15088 (save-excursion
15089 (save-restriction
15090 (widen)
15091 (goto-char (point-min))
15092 (let (case-fold-search)
15093 (if (re-search-forward
15094 (format org-complex-heading-regexp-format
15095 (regexp-quote heading)) nil t)
15096 (if pos-only
15097 (match-beginning 0)
15098 (move-marker (make-marker) (match-beginning 0)))))))))
15100 (defun org-find-exact-heading-in-directory (heading &optional dir)
15101 "Find Org node headline HEADING in all .org files in directory DIR.
15102 When the target headline is found, return a marker to this location."
15103 (let ((files (directory-files (or dir default-directory)
15104 nil "\\`[^.#].*\\.org\\'"))
15105 file visiting m buffer)
15106 (catch 'found
15107 (while (setq file (pop files))
15108 (message "trying %s" file)
15109 (setq visiting (org-find-base-buffer-visiting file))
15110 (setq buffer (or visiting (find-file-noselect file)))
15111 (setq m (org-find-exact-headline-in-buffer
15112 heading buffer))
15113 (when (and (not m) (not visiting)) (kill-buffer buffer))
15114 (and m (throw 'found m))))))
15116 (defun org-find-entry-with-id (ident)
15117 "Locate the entry that contains the ID property with exact value IDENT.
15118 IDENT can be a string, a symbol or a number, this function will search for
15119 the string representation of it.
15120 Return the position where this entry starts, or nil if there is no such entry."
15121 (interactive "sID: ")
15122 (let ((id (cond
15123 ((stringp ident) ident)
15124 ((symbol-name ident) (symbol-name ident))
15125 ((numberp ident) (number-to-string ident))
15126 (t (error "IDENT %s must be a string, symbol or number" ident))))
15127 (case-fold-search nil))
15128 (save-excursion
15129 (save-restriction
15130 (widen)
15131 (goto-char (point-min))
15132 (when (re-search-forward
15133 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15134 nil t)
15135 (org-back-to-heading t)
15136 (point))))))
15138 ;;;; Timestamps
15140 (defvar org-last-changed-timestamp nil)
15141 (defvar org-last-inserted-timestamp nil
15142 "The last time stamp inserted with `org-insert-time-stamp'.")
15143 (defvar org-time-was-given) ; dynamically scoped parameter
15144 (defvar org-end-time-was-given) ; dynamically scoped parameter
15145 (defvar org-ts-what) ; dynamically scoped parameter
15147 (defun org-time-stamp (arg &optional inactive)
15148 "Prompt for a date/time and insert a time stamp.
15149 If the user specifies a time like HH:MM or if this command is
15150 called with at least one prefix argument, the time stamp contains
15151 the date and the time. Otherwise, only the date is be included.
15153 All parts of a date not specified by the user is filled in from
15154 the current date/time. So if you just press return without
15155 typing anything, the time stamp will represent the current
15156 date/time.
15158 If there is already a timestamp at the cursor, it will be
15159 modified.
15161 With two universal prefix arguments, insert an active timestamp
15162 with the current time without prompting the user."
15163 (interactive "P")
15164 (let* ((ts nil)
15165 (default-time
15166 ;; Default time is either today, or, when entering a range,
15167 ;; the range start.
15168 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15169 (save-excursion
15170 (re-search-backward
15171 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15172 (- (point) 20) t)))
15173 (apply 'encode-time (org-parse-time-string (match-string 1)))
15174 (current-time)))
15175 (default-input (and ts (org-get-compact-tod ts)))
15176 (repeater (save-excursion
15177 (save-match-data
15178 (beginning-of-line)
15179 (when (re-search-forward
15180 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15181 (save-excursion (progn (end-of-line) (point))) t)
15182 (match-string 0)))))
15183 org-time-was-given org-end-time-was-given time)
15184 (cond
15185 ((and (org-at-timestamp-p t)
15186 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15187 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15188 (insert "--")
15189 (setq time (let ((this-command this-command))
15190 (org-read-date arg 'totime nil nil
15191 default-time default-input inactive)))
15192 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15193 ((org-at-timestamp-p t)
15194 (setq time (let ((this-command this-command))
15195 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15196 (when (org-at-timestamp-p t) ; just to get the match data
15197 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15198 (replace-match "")
15199 (setq org-last-changed-timestamp
15200 (org-insert-time-stamp
15201 time (or org-time-was-given arg)
15202 inactive nil nil (list org-end-time-was-given)))
15203 (when repeater (goto-char (1- (point))) (insert " " repeater)
15204 (setq org-last-changed-timestamp
15205 (concat (substring org-last-inserted-timestamp 0 -1)
15206 " " repeater ">"))))
15207 (message "Timestamp updated"))
15208 ((equal arg '(16))
15209 (org-insert-time-stamp (current-time) t))
15211 (setq time (let ((this-command this-command))
15212 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15213 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15214 nil nil (list org-end-time-was-given))))))
15216 ;; FIXME: can we use this for something else, like computing time differences?
15217 (defun org-get-compact-tod (s)
15218 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15219 (let* ((t1 (match-string 1 s))
15220 (h1 (string-to-number (match-string 2 s)))
15221 (m1 (string-to-number (match-string 3 s)))
15222 (t2 (and (match-end 4) (match-string 5 s)))
15223 (h2 (and t2 (string-to-number (match-string 6 s))))
15224 (m2 (and t2 (string-to-number (match-string 7 s))))
15225 dh dm)
15226 (if (not t2)
15228 (setq dh (- h2 h1) dm (- m2 m1))
15229 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15230 (concat t1 "+" (number-to-string dh)
15231 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15233 (defun org-time-stamp-inactive (&optional arg)
15234 "Insert an inactive time stamp.
15235 An inactive time stamp is enclosed in square brackets instead of angle
15236 brackets. It is inactive in the sense that it does not trigger agenda entries,
15237 does not link to the calendar and cannot be changed with the S-cursor keys.
15238 So these are more for recording a certain time/date."
15239 (interactive "P")
15240 (org-time-stamp arg 'inactive))
15242 (defvar org-date-ovl (make-overlay 1 1))
15243 (overlay-put org-date-ovl 'face 'org-date-selected)
15244 (org-detach-overlay org-date-ovl)
15246 (defvar org-ans1) ; dynamically scoped parameter
15247 (defvar org-ans2) ; dynamically scoped parameter
15249 (defvar org-plain-time-of-day-regexp) ; defined below
15251 (defvar org-overriding-default-time nil) ; dynamically scoped
15252 (defvar org-read-date-overlay nil)
15253 (defvar org-dcst nil) ; dynamically scoped
15254 (defvar org-read-date-history nil)
15255 (defvar org-read-date-final-answer nil)
15256 (defvar org-read-date-analyze-futurep nil)
15257 (defvar org-read-date-analyze-forced-year nil)
15258 (defvar org-read-date-inactive)
15260 (defun org-read-date (&optional org-with-time to-time from-string prompt
15261 default-time default-input inactive)
15262 "Read a date, possibly a time, and make things smooth for the user.
15263 The prompt will suggest to enter an ISO date, but you can also enter anything
15264 which will at least partially be understood by `parse-time-string'.
15265 Unrecognized parts of the date will default to the current day, month, year,
15266 hour and minute. If this command is called to replace a timestamp at point,
15267 or to enter the second timestamp of a range, the default time is taken
15268 from the existing stamp. Furthermore, the command prefers the future,
15269 so if you are giving a date where the year is not given, and the day-month
15270 combination is already past in the current year, it will assume you
15271 mean next year. For details, see the manual. A few examples:
15273 3-2-5 --> 2003-02-05
15274 feb 15 --> currentyear-02-15
15275 2/15 --> currentyear-02-15
15276 sep 12 9 --> 2009-09-12
15277 12:45 --> today 12:45
15278 22 sept 0:34 --> currentyear-09-22 0:34
15279 12 --> currentyear-currentmonth-12
15280 Fri --> nearest Friday (today or later)
15281 etc.
15283 Furthermore you can specify a relative date by giving, as the *first* thing
15284 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15285 change in days weeks, months, years.
15286 With a single plus or minus, the date is relative to today. With a double
15287 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15288 +4d --> four days from today
15289 +4 --> same as above
15290 +2w --> two weeks from today
15291 ++5 --> five days from default date
15293 The function understands only English month and weekday abbreviations.
15295 While prompting, a calendar is popped up - you can also select the
15296 date with the mouse (button 1). The calendar shows a period of three
15297 months. To scroll it to other months, use the keys `>' and `<'.
15298 If you don't like the calendar, turn it off with
15299 \(setq org-read-date-popup-calendar nil)
15301 With optional argument TO-TIME, the date will immediately be converted
15302 to an internal time.
15303 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15304 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15305 still enter a time, and this function will inform the calling routine
15306 about this change. The calling routine may then choose to change the
15307 format used to insert the time stamp into the buffer to include the time.
15308 With optional argument FROM-STRING, read from this string instead from
15309 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15310 the time/date that is used for everything that is not specified by the
15311 user."
15312 (require 'parse-time)
15313 (let* ((org-time-stamp-rounding-minutes
15314 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15315 (org-dcst org-display-custom-times)
15316 (ct (org-current-time))
15317 (org-def (or org-overriding-default-time default-time ct))
15318 (org-defdecode (decode-time org-def))
15319 (dummy (progn
15320 (when (< (nth 2 org-defdecode) org-extend-today-until)
15321 (setcar (nthcdr 2 org-defdecode) -1)
15322 (setcar (nthcdr 1 org-defdecode) 59)
15323 (setq org-def (apply 'encode-time org-defdecode)
15324 org-defdecode (decode-time org-def)))))
15325 (calendar-frame-setup nil)
15326 (calendar-setup nil)
15327 (calendar-move-hook nil)
15328 (calendar-view-diary-initially-flag nil)
15329 (calendar-view-holidays-initially-flag nil)
15330 (timestr (format-time-string
15331 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15332 (prompt (concat (if prompt (concat prompt " ") "")
15333 (format "Date+time [%s]: " timestr)))
15334 ans (org-ans0 "") org-ans1 org-ans2 final)
15336 (cond
15337 (from-string (setq ans from-string))
15338 (org-read-date-popup-calendar
15339 (save-excursion
15340 (save-window-excursion
15341 (calendar)
15342 (org-eval-in-calendar '(setq cursor-type nil) t)
15343 (unwind-protect
15344 (progn
15345 (calendar-forward-day (- (time-to-days org-def)
15346 (calendar-absolute-from-gregorian
15347 (calendar-current-date))))
15348 (org-eval-in-calendar nil t)
15349 (let* ((old-map (current-local-map))
15350 (map (copy-keymap calendar-mode-map))
15351 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15352 (org-defkey map (kbd "RET") 'org-calendar-select)
15353 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15354 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15355 (org-defkey minibuffer-local-map [(meta shift left)]
15356 (lambda () (interactive)
15357 (org-eval-in-calendar '(calendar-backward-month 1))))
15358 (org-defkey minibuffer-local-map [(meta shift right)]
15359 (lambda () (interactive)
15360 (org-eval-in-calendar '(calendar-forward-month 1))))
15361 (org-defkey minibuffer-local-map [(meta shift up)]
15362 (lambda () (interactive)
15363 (org-eval-in-calendar '(calendar-backward-year 1))))
15364 (org-defkey minibuffer-local-map [(meta shift down)]
15365 (lambda () (interactive)
15366 (org-eval-in-calendar '(calendar-forward-year 1))))
15367 (org-defkey minibuffer-local-map [?\e (shift left)]
15368 (lambda () (interactive)
15369 (org-eval-in-calendar '(calendar-backward-month 1))))
15370 (org-defkey minibuffer-local-map [?\e (shift right)]
15371 (lambda () (interactive)
15372 (org-eval-in-calendar '(calendar-forward-month 1))))
15373 (org-defkey minibuffer-local-map [?\e (shift up)]
15374 (lambda () (interactive)
15375 (org-eval-in-calendar '(calendar-backward-year 1))))
15376 (org-defkey minibuffer-local-map [?\e (shift down)]
15377 (lambda () (interactive)
15378 (org-eval-in-calendar '(calendar-forward-year 1))))
15379 (org-defkey minibuffer-local-map [(shift up)]
15380 (lambda () (interactive)
15381 (org-eval-in-calendar '(calendar-backward-week 1))))
15382 (org-defkey minibuffer-local-map [(shift down)]
15383 (lambda () (interactive)
15384 (org-eval-in-calendar '(calendar-forward-week 1))))
15385 (org-defkey minibuffer-local-map [(shift left)]
15386 (lambda () (interactive)
15387 (org-eval-in-calendar '(calendar-backward-day 1))))
15388 (org-defkey minibuffer-local-map [(shift right)]
15389 (lambda () (interactive)
15390 (org-eval-in-calendar '(calendar-forward-day 1))))
15391 (org-defkey minibuffer-local-map ">"
15392 (lambda () (interactive)
15393 (org-eval-in-calendar '(scroll-calendar-left 1))))
15394 (org-defkey minibuffer-local-map "<"
15395 (lambda () (interactive)
15396 (org-eval-in-calendar '(scroll-calendar-right 1))))
15397 (org-defkey minibuffer-local-map "\C-v"
15398 (lambda () (interactive)
15399 (org-eval-in-calendar
15400 '(calendar-scroll-left-three-months 1))))
15401 (org-defkey minibuffer-local-map "\M-v"
15402 (lambda () (interactive)
15403 (org-eval-in-calendar
15404 '(calendar-scroll-right-three-months 1))))
15405 (run-hooks 'org-read-date-minibuffer-setup-hook)
15406 (unwind-protect
15407 (progn
15408 (use-local-map map)
15409 (setq org-read-date-inactive inactive)
15410 (add-hook 'post-command-hook 'org-read-date-display)
15411 (setq org-ans0 (read-string prompt default-input
15412 'org-read-date-history nil))
15413 ;; org-ans0: from prompt
15414 ;; org-ans1: from mouse click
15415 ;; org-ans2: from calendar motion
15416 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15417 (remove-hook 'post-command-hook 'org-read-date-display)
15418 (use-local-map old-map)
15419 (when org-read-date-overlay
15420 (delete-overlay org-read-date-overlay)
15421 (setq org-read-date-overlay nil)))))
15422 (bury-buffer "*Calendar*")))))
15424 (t ; Naked prompt only
15425 (unwind-protect
15426 (setq ans (read-string prompt default-input
15427 'org-read-date-history timestr))
15428 (when org-read-date-overlay
15429 (delete-overlay org-read-date-overlay)
15430 (setq org-read-date-overlay nil)))))
15432 (setq final (org-read-date-analyze ans org-def org-defdecode))
15434 (when org-read-date-analyze-forced-year
15435 (message "Year was forced into %s"
15436 (if org-read-date-force-compatible-dates
15437 "compatible range (1970-2037)"
15438 "range representable on this machine"))
15439 (ding))
15441 ;; One round trip to get rid of 34th of August and stuff like that....
15442 (setq final (decode-time (apply 'encode-time final)))
15444 (setq org-read-date-final-answer ans)
15446 (if to-time
15447 (apply 'encode-time final)
15448 (if (and (boundp 'org-time-was-given) org-time-was-given)
15449 (format "%04d-%02d-%02d %02d:%02d"
15450 (nth 5 final) (nth 4 final) (nth 3 final)
15451 (nth 2 final) (nth 1 final))
15452 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15454 (defvar org-def)
15455 (defvar org-defdecode)
15456 (defvar org-with-time)
15457 (defun org-read-date-display ()
15458 "Display the current date prompt interpretation in the minibuffer."
15459 (when org-read-date-display-live
15460 (when org-read-date-overlay
15461 (delete-overlay org-read-date-overlay))
15462 (when (minibufferp (current-buffer))
15463 (save-excursion
15464 (end-of-line 1)
15465 (while (not (equal (buffer-substring
15466 (max (point-min) (- (point) 4)) (point))
15467 " "))
15468 (insert " ")))
15469 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15470 " " (or org-ans1 org-ans2)))
15471 (org-end-time-was-given nil)
15472 (f (org-read-date-analyze ans org-def org-defdecode))
15473 (fmts (if org-dcst
15474 org-time-stamp-custom-formats
15475 org-time-stamp-formats))
15476 (fmt (if (or org-with-time
15477 (and (boundp 'org-time-was-given) org-time-was-given))
15478 (cdr fmts)
15479 (car fmts)))
15480 (txt (format-time-string fmt (apply 'encode-time f)))
15481 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15482 (txt (concat "=> " txt)))
15483 (when (and org-end-time-was-given
15484 (string-match org-plain-time-of-day-regexp txt))
15485 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15486 org-end-time-was-given
15487 (substring txt (match-end 0)))))
15488 (when org-read-date-analyze-futurep
15489 (setq txt (concat txt " (=>F)")))
15490 (setq org-read-date-overlay
15491 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15492 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15494 (defun org-read-date-analyze (ans org-def org-defdecode)
15495 "Analyze the combined answer of the date prompt."
15496 ;; FIXME: cleanup and comment
15497 (let ((nowdecode (decode-time (current-time)))
15498 delta deltan deltaw deltadef year month day
15499 hour minute second wday pm h2 m2 tl wday1
15500 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15501 (setq org-read-date-analyze-futurep nil
15502 org-read-date-analyze-forced-year nil)
15503 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15504 (setq ans "+0"))
15506 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15507 (setq ans (replace-match "" t t ans)
15508 deltan (car delta)
15509 deltaw (nth 1 delta)
15510 deltadef (nth 2 delta)))
15512 ;; Check if there is an iso week date in there. If yes, store the
15513 ;; info and postpone interpreting it until the rest of the parsing
15514 ;; is done.
15515 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15516 (setq iso-year (if (match-end 1)
15517 (org-small-year-to-year
15518 (string-to-number (match-string 1 ans))))
15519 iso-weekday (if (match-end 3)
15520 (string-to-number (match-string 3 ans)))
15521 iso-week (string-to-number (match-string 2 ans)))
15522 (setq ans (replace-match "" t t ans)))
15524 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15525 (when (string-match
15526 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15527 (setq year (if (match-end 2)
15528 (string-to-number (match-string 2 ans))
15529 (progn (setq kill-year t)
15530 (string-to-number (format-time-string "%Y"))))
15531 month (string-to-number (match-string 3 ans))
15532 day (string-to-number (match-string 4 ans)))
15533 (if (< year 100) (setq year (+ 2000 year)))
15534 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15535 t nil ans)))
15537 ;; Help matching dotted european dates
15538 (when (string-match
15539 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15540 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15541 (setq kill-year t)
15542 (string-to-number (format-time-string "%Y")))
15543 day (string-to-number (match-string 1 ans))
15544 month (string-to-number (match-string 2 ans))
15545 ans (replace-match (format "%04d-%02d-%02d" year month day)
15546 t nil ans)))
15548 ;; Help matching american dates, like 5/30 or 5/30/7
15549 (when (string-match
15550 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15551 (setq year (if (match-end 4)
15552 (string-to-number (match-string 4 ans))
15553 (progn (setq kill-year t)
15554 (string-to-number (format-time-string "%Y"))))
15555 month (string-to-number (match-string 1 ans))
15556 day (string-to-number (match-string 2 ans)))
15557 (if (< year 100) (setq year (+ 2000 year)))
15558 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15559 t nil ans)))
15560 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15561 ;; If there is a time with am/pm, and *no* time without it, we convert
15562 ;; so that matching will be successful.
15563 (loop for i from 1 to 2 do ; twice, for end time as well
15564 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15565 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15566 (setq hour (string-to-number (match-string 1 ans))
15567 minute (if (match-end 3)
15568 (string-to-number (match-string 3 ans))
15570 pm (equal ?p
15571 (string-to-char (downcase (match-string 4 ans)))))
15572 (if (and (= hour 12) (not pm))
15573 (setq hour 0)
15574 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15575 (setq ans (replace-match (format "%02d:%02d" hour minute)
15576 t t ans))))
15578 ;; Check if a time range is given as a duration
15579 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15580 (setq hour (string-to-number (match-string 1 ans))
15581 h2 (+ hour (string-to-number (match-string 3 ans)))
15582 minute (string-to-number (match-string 2 ans))
15583 m2 (+ minute (if (match-end 5) (string-to-number
15584 (match-string 5 ans))0)))
15585 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15586 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15587 t t ans)))
15589 ;; Check if there is a time range
15590 (when (boundp 'org-end-time-was-given)
15591 (setq org-time-was-given nil)
15592 (when (and (string-match org-plain-time-of-day-regexp ans)
15593 (match-end 8))
15594 (setq org-end-time-was-given (match-string 8 ans))
15595 (setq ans (concat (substring ans 0 (match-beginning 7))
15596 (substring ans (match-end 7))))))
15598 (setq tl (parse-time-string ans)
15599 day (or (nth 3 tl) (nth 3 org-defdecode))
15600 month (or (nth 4 tl)
15601 (if (and org-read-date-prefer-future
15602 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15603 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15604 (nth 4 org-defdecode)))
15605 year (or (and (not kill-year) (nth 5 tl))
15606 (if (and org-read-date-prefer-future
15607 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15608 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15609 (nth 5 org-defdecode)))
15610 hour (or (nth 2 tl) (nth 2 org-defdecode))
15611 minute (or (nth 1 tl) (nth 1 org-defdecode))
15612 second (or (nth 0 tl) 0)
15613 wday (nth 6 tl))
15615 (when (and (eq org-read-date-prefer-future 'time)
15616 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15617 (equal day (nth 3 nowdecode))
15618 (equal month (nth 4 nowdecode))
15619 (equal year (nth 5 nowdecode))
15620 (nth 2 tl)
15621 (or (< (nth 2 tl) (nth 2 nowdecode))
15622 (and (= (nth 2 tl) (nth 2 nowdecode))
15623 (nth 1 tl)
15624 (< (nth 1 tl) (nth 1 nowdecode)))))
15625 (setq day (1+ day)
15626 futurep t))
15628 ;; Special date definitions below
15629 (cond
15630 (iso-week
15631 ;; There was an iso week
15632 (require 'cal-iso)
15633 (setq futurep nil)
15634 (setq year (or iso-year year)
15635 day (or iso-weekday wday 1)
15636 wday nil ; to make sure that the trigger below does not match
15637 iso-date (calendar-gregorian-from-absolute
15638 (calendar-absolute-from-iso
15639 (list iso-week day year))))
15640 ; FIXME: Should we also push ISO weeks into the future?
15641 ; (when (and org-read-date-prefer-future
15642 ; (not iso-year)
15643 ; (< (calendar-absolute-from-gregorian iso-date)
15644 ; (time-to-days (current-time))))
15645 ; (setq year (1+ year)
15646 ; iso-date (calendar-gregorian-from-absolute
15647 ; (calendar-absolute-from-iso
15648 ; (list iso-week day year)))))
15649 (setq month (car iso-date)
15650 year (nth 2 iso-date)
15651 day (nth 1 iso-date)))
15652 (deltan
15653 (setq futurep nil)
15654 (unless deltadef
15655 (let ((now (decode-time (current-time))))
15656 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15657 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15658 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15659 ((equal deltaw "m") (setq month (+ month deltan)))
15660 ((equal deltaw "y") (setq year (+ year deltan)))))
15661 ((and wday (not (nth 3 tl)))
15662 ;; Weekday was given, but no day, so pick that day in the week
15663 ;; on or after the derived date.
15664 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15665 (unless (equal wday wday1)
15666 (setq day (+ day (% (- wday wday1 -7) 7))))))
15667 (if (and (boundp 'org-time-was-given)
15668 (nth 2 tl))
15669 (setq org-time-was-given t))
15670 (if (< year 100) (setq year (+ 2000 year)))
15671 ;; Check of the date is representable
15672 (if org-read-date-force-compatible-dates
15673 (progn
15674 (if (< year 1970)
15675 (setq year 1970 org-read-date-analyze-forced-year t))
15676 (if (> year 2037)
15677 (setq year 2037 org-read-date-analyze-forced-year t)))
15678 (condition-case nil
15679 (ignore (encode-time second minute hour day month year))
15680 (error
15681 (setq year (nth 5 org-defdecode))
15682 (setq org-read-date-analyze-forced-year t))))
15683 (setq org-read-date-analyze-futurep futurep)
15684 (list second minute hour day month year)))
15686 (defvar parse-time-weekdays)
15687 (defun org-read-date-get-relative (s today default)
15688 "Check string S for special relative date string.
15689 TODAY and DEFAULT are internal times, for today and for a default.
15690 Return shift list (N what def-flag)
15691 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15692 N is the number of WHATs to shift.
15693 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15694 the DEFAULT date rather than TODAY."
15695 (require 'parse-time)
15696 (when (and
15697 (string-match
15698 (concat
15699 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15700 "\\([0-9]+\\)?"
15701 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15702 "\\([ \t]\\|$\\)") s)
15703 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15704 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15705 (string-to-char (substring (match-string 1 s) -1))
15706 ?+))
15707 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15708 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15709 (what (if (match-end 3) (match-string 3 s) "d"))
15710 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15711 (date (if rel default today))
15712 (wday (nth 6 (decode-time date)))
15713 delta)
15714 (if wday1
15715 (progn
15716 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15717 (if (= dir ?-) (setq delta (- delta 7)))
15718 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15719 (list delta "d" rel))
15720 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15722 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15723 "Turn a user-specified date into the internal representation.
15724 The internal representation needed by the calendar is (month day year).
15725 This is a wrapper to handle the brain-dead convention in calendar that
15726 user function argument order change dependent on argument order."
15727 (if (boundp 'calendar-date-style)
15728 (cond
15729 ((eq calendar-date-style 'american)
15730 (list arg1 arg2 arg3))
15731 ((eq calendar-date-style 'european)
15732 (list arg2 arg1 arg3))
15733 ((eq calendar-date-style 'iso)
15734 (list arg2 arg3 arg1)))
15735 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15736 (if (org-bound-and-true-p european-calendar-style)
15737 (list arg2 arg1 arg3)
15738 (list arg1 arg2 arg3)))))
15740 (defun org-eval-in-calendar (form &optional keepdate)
15741 "Eval FORM in the calendar window and return to current window.
15742 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15743 otherwise stick to the current value of `org-ans2'."
15744 (let ((sf (selected-frame))
15745 (sw (selected-window)))
15746 (select-window (get-buffer-window "*Calendar*" t))
15747 (eval form)
15748 (when (and (not keepdate) (calendar-cursor-to-date))
15749 (let* ((date (calendar-cursor-to-date))
15750 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15751 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15752 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15753 (select-window sw)
15754 (org-select-frame-set-input-focus sf)))
15756 (defun org-calendar-select ()
15757 "Return to `org-read-date' with the date currently selected.
15758 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15759 (interactive)
15760 (when (calendar-cursor-to-date)
15761 (let* ((date (calendar-cursor-to-date))
15762 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15763 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15764 (if (active-minibuffer-window) (exit-minibuffer))))
15766 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15767 "Insert a date stamp for the date given by the internal TIME.
15768 WITH-HM means use the stamp format that includes the time of the day.
15769 INACTIVE means use square brackets instead of angular ones, so that the
15770 stamp will not contribute to the agenda.
15771 PRE and POST are optional strings to be inserted before and after the
15772 stamp.
15773 The command returns the inserted time stamp."
15774 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15775 stamp)
15776 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15777 (insert-before-markers (or pre ""))
15778 (when (listp extra)
15779 (setq extra (car extra))
15780 (if (and (stringp extra)
15781 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15782 (setq extra (format "-%02d:%02d"
15783 (string-to-number (match-string 1 extra))
15784 (string-to-number (match-string 2 extra))))
15785 (setq extra nil)))
15786 (when extra
15787 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15788 (insert-before-markers (setq stamp (format-time-string fmt time)))
15789 (insert-before-markers (or post ""))
15790 (setq org-last-inserted-timestamp stamp)))
15792 (defun org-toggle-time-stamp-overlays ()
15793 "Toggle the use of custom time stamp formats."
15794 (interactive)
15795 (setq org-display-custom-times (not org-display-custom-times))
15796 (unless org-display-custom-times
15797 (let ((p (point-min)) (bmp (buffer-modified-p)))
15798 (while (setq p (next-single-property-change p 'display))
15799 (if (and (get-text-property p 'display)
15800 (eq (get-text-property p 'face) 'org-date))
15801 (remove-text-properties
15802 p (setq p (next-single-property-change p 'display))
15803 '(display t))))
15804 (set-buffer-modified-p bmp)))
15805 (if (featurep 'xemacs)
15806 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15807 (org-restart-font-lock)
15808 (setq org-table-may-need-update t)
15809 (if org-display-custom-times
15810 (message "Time stamps are overlaid with custom format")
15811 (message "Time stamp overlays removed")))
15813 (defun org-display-custom-time (beg end)
15814 "Overlay modified time stamp format over timestamp between BEG and END."
15815 (let* ((ts (buffer-substring beg end))
15816 t1 w1 with-hm tf time str w2 (off 0))
15817 (save-match-data
15818 (setq t1 (org-parse-time-string ts t))
15819 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15820 (setq off (- (match-end 0) (match-beginning 0)))))
15821 (setq end (- end off))
15822 (setq w1 (- end beg)
15823 with-hm (and (nth 1 t1) (nth 2 t1))
15824 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15825 time (org-fix-decoded-time t1)
15826 str (org-add-props
15827 (format-time-string
15828 (substring tf 1 -1) (apply 'encode-time time))
15829 nil 'mouse-face 'highlight)
15830 w2 (length str))
15831 (if (not (= w2 w1))
15832 (add-text-properties (1+ beg) (+ 2 beg)
15833 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15834 (if (featurep 'xemacs)
15835 (progn
15836 (put-text-property beg end 'invisible t)
15837 (put-text-property beg end 'end-glyph (make-glyph str)))
15838 (put-text-property beg end 'display str))))
15840 (defun org-translate-time (string)
15841 "Translate all timestamps in STRING to custom format.
15842 But do this only if the variable `org-display-custom-times' is set."
15843 (when org-display-custom-times
15844 (save-match-data
15845 (let* ((start 0)
15846 (re org-ts-regexp-both)
15847 t1 with-hm inactive tf time str beg end)
15848 (while (setq start (string-match re string start))
15849 (setq beg (match-beginning 0)
15850 end (match-end 0)
15851 t1 (save-match-data
15852 (org-parse-time-string (substring string beg end) t))
15853 with-hm (and (nth 1 t1) (nth 2 t1))
15854 inactive (equal (substring string beg (1+ beg)) "[")
15855 tf (funcall (if with-hm 'cdr 'car)
15856 org-time-stamp-custom-formats)
15857 time (org-fix-decoded-time t1)
15858 str (format-time-string
15859 (concat
15860 (if inactive "[" "<") (substring tf 1 -1)
15861 (if inactive "]" ">"))
15862 (apply 'encode-time time))
15863 string (replace-match str t t string)
15864 start (+ start (length str)))))))
15865 string)
15867 (defun org-fix-decoded-time (time)
15868 "Set 0 instead of nil for the first 6 elements of time.
15869 Don't touch the rest."
15870 (let ((n 0))
15871 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15873 (defun org-days-to-time (timestamp-string)
15874 "Difference between TIMESTAMP-STRING and now in days."
15875 (- (time-to-days (org-time-string-to-time timestamp-string))
15876 (time-to-days (current-time))))
15878 (defun org-deadline-close (timestamp-string &optional ndays)
15879 "Is the time in TIMESTAMP-STRING close to the current date?"
15880 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15881 (and (< (org-days-to-time timestamp-string) ndays)
15882 (not (org-entry-is-done-p))))
15884 (defun org-get-wdays (ts)
15885 "Get the deadline lead time appropriate for timestring TS."
15886 (cond
15887 ((<= org-deadline-warning-days 0)
15888 ;; 0 or negative, enforce this value no matter what
15889 (- org-deadline-warning-days))
15890 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15891 ;; lead time is specified.
15892 (floor (* (string-to-number (match-string 1 ts))
15893 (cdr (assoc (match-string 2 ts)
15894 '(("d" . 1) ("w" . 7)
15895 ("m" . 30.4) ("y" . 365.25)))))))
15896 ;; go for the default.
15897 (t org-deadline-warning-days)))
15899 (defun org-calendar-select-mouse (ev)
15900 "Return to `org-read-date' with the date currently selected.
15901 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15902 (interactive "e")
15903 (mouse-set-point ev)
15904 (when (calendar-cursor-to-date)
15905 (let* ((date (calendar-cursor-to-date))
15906 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15907 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15908 (if (active-minibuffer-window) (exit-minibuffer))))
15910 (defun org-check-deadlines (ndays)
15911 "Check if there are any deadlines due or past due.
15912 A deadline is considered due if it happens within `org-deadline-warning-days'
15913 days from today's date. If the deadline appears in an entry marked DONE,
15914 it is not shown. The prefix arg NDAYS can be used to test that many
15915 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15916 (interactive "P")
15917 (let* ((org-warn-days
15918 (cond
15919 ((equal ndays '(4)) 100000)
15920 (ndays (prefix-numeric-value ndays))
15921 (t (abs org-deadline-warning-days))))
15922 (case-fold-search nil)
15923 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15924 (callback
15925 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15927 (message "%d deadlines past-due or due within %d days"
15928 (org-occur regexp nil callback)
15929 org-warn-days)))
15931 (defsubst org-re-timestamp (type)
15932 "Return a regexp for timestamp TYPE.
15933 Allowed values for TYPE are:
15935 all: all timestamps
15936 active: only active timestamps (<...>)
15937 inactive: only inactive timestamps ([...])
15938 scheduled: only scheduled timestamps
15939 deadline: only deadline timestamps
15941 When TYPE is nil, fall back on returning a regexp that matches
15942 both scheduled and deadline timestamps."
15943 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
15944 ((eq type 'active) org-ts-regexp)
15945 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
15946 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
15947 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15948 ((eq type 'scheduled-or-deadline)
15949 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
15951 (defun org-check-before-date (date)
15952 "Check if there are deadlines or scheduled entries before DATE."
15953 (interactive (list (org-read-date)))
15954 (let ((case-fold-search nil)
15955 (regexp (org-re-timestamp org-ts-type))
15956 (callback
15957 (lambda () (time-less-p
15958 (org-time-string-to-time (match-string 1))
15959 (org-time-string-to-time date)))))
15960 (message "%d entries before %s"
15961 (org-occur regexp nil callback) date)))
15963 (defun org-check-after-date (date)
15964 "Check if there are deadlines or scheduled entries after DATE."
15965 (interactive (list (org-read-date)))
15966 (let ((case-fold-search nil)
15967 (regexp (org-re-timestamp org-ts-type))
15968 (callback
15969 (lambda () (not
15970 (time-less-p
15971 (org-time-string-to-time (match-string 1))
15972 (org-time-string-to-time date))))))
15973 (message "%d entries after %s"
15974 (org-occur regexp nil callback) date)))
15976 (defun org-check-dates-range (start-date end-date)
15977 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
15978 (interactive (list (org-read-date nil nil nil "Range starts")
15979 (org-read-date nil nil nil "Range end")))
15980 (let ((case-fold-search nil)
15981 (regexp (org-re-timestamp org-ts-type))
15982 (callback
15983 (lambda ()
15984 (let ((match (match-string 1)))
15985 (and
15986 (not (time-less-p
15987 (org-time-string-to-time match)
15988 (org-time-string-to-time start-date)))
15989 (time-less-p
15990 (org-time-string-to-time match)
15991 (org-time-string-to-time end-date)))))))
15992 (message "%d entries between %s and %s"
15993 (org-occur regexp nil callback) start-date end-date)))
15995 (defun org-evaluate-time-range (&optional to-buffer)
15996 "Evaluate a time range by computing the difference between start and end.
15997 Normally the result is just printed in the echo area, but with prefix arg
15998 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15999 If the time range is actually in a table, the result is inserted into the
16000 next column.
16001 For time difference computation, a year is assumed to be exactly 365
16002 days in order to avoid rounding problems."
16003 (interactive "P")
16005 (org-clock-update-time-maybe)
16006 (save-excursion
16007 (unless (org-at-date-range-p t)
16008 (goto-char (point-at-bol))
16009 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16010 (if (not (org-at-date-range-p t))
16011 (error "Not at a time-stamp range, and none found in current line")))
16012 (let* ((ts1 (match-string 1))
16013 (ts2 (match-string 2))
16014 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16015 (match-end (match-end 0))
16016 (time1 (org-time-string-to-time ts1))
16017 (time2 (org-time-string-to-time ts2))
16018 (t1 (org-float-time time1))
16019 (t2 (org-float-time time2))
16020 (diff (abs (- t2 t1)))
16021 (negative (< (- t2 t1) 0))
16022 ;; (ys (floor (* 365 24 60 60)))
16023 (ds (* 24 60 60))
16024 (hs (* 60 60))
16025 (fy "%dy %dd %02d:%02d")
16026 (fy1 "%dy %dd")
16027 (fd "%dd %02d:%02d")
16028 (fd1 "%dd")
16029 (fh "%02d:%02d")
16030 y d h m align)
16031 (if havetime
16032 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16034 d (floor (/ diff ds)) diff (mod diff ds)
16035 h (floor (/ diff hs)) diff (mod diff hs)
16036 m (floor (/ diff 60)))
16037 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16039 d (floor (+ (/ diff ds) 0.5))
16040 h 0 m 0))
16041 (if (not to-buffer)
16042 (message "%s" (org-make-tdiff-string y d h m))
16043 (if (org-at-table-p)
16044 (progn
16045 (goto-char match-end)
16046 (setq align t)
16047 (and (looking-at " *|") (goto-char (match-end 0))))
16048 (goto-char match-end))
16049 (if (looking-at
16050 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16051 (replace-match ""))
16052 (if negative (insert " -"))
16053 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16054 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16055 (insert " " (format fh h m))))
16056 (if align (org-table-align))
16057 (message "Time difference inserted")))))
16059 (defun org-make-tdiff-string (y d h m)
16060 (let ((fmt "")
16061 (l nil))
16062 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16063 l (push y l)))
16064 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16065 l (push d l)))
16066 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16067 l (push h l)))
16068 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16069 l (push m l)))
16070 (apply 'format fmt (nreverse l))))
16072 (defun org-time-string-to-time (s &optional buffer pos)
16073 "Convert a timestamp string into internal time."
16074 (condition-case errdata
16075 (apply 'encode-time (org-parse-time-string s))
16076 (error (error "Bad timestamp `%s'%s\nError was: %s"
16077 s (if (not (and buffer pos))
16079 (format " at %d in buffer `%s'" pos buffer))
16080 (cdr errdata)))))
16082 (defun org-time-string-to-seconds (s)
16083 "Convert a timestamp string to a number of seconds."
16084 (org-float-time (org-time-string-to-time s)))
16086 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16087 "Convert a time stamp to an absolute day number.
16088 If there is a specifier for a cyclic time stamp, get the closest date to
16089 DAYNR.
16090 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16091 The variable date is bound by the calendar when this is called."
16092 (cond
16093 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16094 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16095 daynr
16096 (+ daynr 1000)))
16097 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16098 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16099 (time-to-days (current-time))) (match-string 0 s)
16100 prefer show-all))
16101 (t (time-to-days
16102 (condition-case errdata
16103 (apply 'encode-time (org-parse-time-string s))
16104 (error (error "Bad timestamp `%s'%s\nError was: %s"
16105 s (if (not (and buffer pos))
16107 (format " at %d in buffer `%s'" pos buffer))
16108 (cdr errdata))))))))
16110 (defun org-days-to-iso-week (days)
16111 "Return the iso week number."
16112 (require 'cal-iso)
16113 (car (calendar-iso-from-absolute days)))
16115 (defun org-small-year-to-year (year)
16116 "Convert 2-digit years into 4-digit years.
16117 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16118 The year 2000 cannot be abbreviated. Any year larger than 99
16119 is returned unchanged."
16120 (if (< year 38)
16121 (setq year (+ 2000 year))
16122 (if (< year 100)
16123 (setq year (+ 1900 year))))
16124 year)
16126 (defun org-time-from-absolute (d)
16127 "Return the time corresponding to date D.
16128 D may be an absolute day number, or a calendar-type list (month day year)."
16129 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16130 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16132 (defun org-calendar-holiday ()
16133 "List of holidays, for Diary display in Org-mode."
16134 (require 'holidays)
16135 (let ((hl (funcall
16136 (if (fboundp 'calendar-check-holidays)
16137 'calendar-check-holidays 'check-calendar-holidays) date)))
16138 (if hl (mapconcat 'identity hl "; "))))
16140 (defun org-diary-sexp-entry (sexp entry date)
16141 "Process a SEXP diary ENTRY for DATE."
16142 (require 'diary-lib)
16143 (let ((result (if calendar-debug-sexp
16144 (let ((stack-trace-on-error t))
16145 (eval (car (read-from-string sexp))))
16146 (condition-case nil
16147 (eval (car (read-from-string sexp)))
16148 (error
16149 (beep)
16150 (message "Bad sexp at line %d in %s: %s"
16151 (org-current-line)
16152 (buffer-file-name) sexp)
16153 (sleep-for 2))))))
16154 (cond ((stringp result) (split-string result "; "))
16155 ((and (consp result)
16156 (not (consp (cdr result)))
16157 (stringp (cdr result))) (cdr result))
16158 ((and (consp result)
16159 (stringp (car result))) result)
16160 (result entry))))
16162 (defun org-diary-to-ical-string (frombuf)
16163 "Get iCalendar entries from diary entries in buffer FROMBUF.
16164 This uses the icalendar.el library."
16165 (let* ((tmpdir (if (featurep 'xemacs)
16166 (temp-directory)
16167 temporary-file-directory))
16168 (tmpfile (make-temp-name
16169 (expand-file-name "orgics" tmpdir)))
16170 buf rtn b e)
16171 (with-current-buffer frombuf
16172 (icalendar-export-region (point-min) (point-max) tmpfile)
16173 (setq buf (find-buffer-visiting tmpfile))
16174 (set-buffer buf)
16175 (goto-char (point-min))
16176 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16177 (setq b (match-beginning 0)))
16178 (goto-char (point-max))
16179 (if (re-search-backward "^END:VEVENT" nil t)
16180 (setq e (match-end 0)))
16181 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16182 (kill-buffer buf)
16183 (delete-file tmpfile)
16184 rtn))
16186 (defun org-closest-date (start current change prefer show-all)
16187 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16188 When PREFER is `past', return a date that is either CURRENT or past.
16189 When PREFER is `future', return a date that is either CURRENT or future.
16190 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16191 ;; Make the proper lists from the dates
16192 (catch 'exit
16193 (let ((a1 '(("h" . hour)
16194 ("d" . day)
16195 ("w" . week)
16196 ("m" . month)
16197 ("y" . year)))
16198 (shour (nth 2 (org-parse-time-string start)))
16199 dn dw sday cday n1 n2 n0
16200 d m y y1 y2 date1 date2 nmonths nm ny m2)
16202 (setq start (org-date-to-gregorian start)
16203 current (org-date-to-gregorian
16204 (if show-all
16205 current
16206 (time-to-days (current-time))))
16207 sday (calendar-absolute-from-gregorian start)
16208 cday (calendar-absolute-from-gregorian current))
16210 (if (<= cday sday) (throw 'exit sday))
16212 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16213 (setq dn (string-to-number (match-string 1 change))
16214 dw (cdr (assoc (match-string 2 change) a1)))
16215 (error "Invalid change specifier: %s" change))
16216 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16217 (cond
16218 ((eq dw 'hour)
16219 (let ((missing-hours
16220 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16221 dn)))
16222 (setq n1 (if (zerop missing-hours) cday
16223 (- cday (1+ (floor (/ missing-hours 24)))))
16224 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16225 ((eq dw 'day)
16226 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16227 n2 (+ n1 dn)))
16228 ((eq dw 'year)
16229 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16230 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16231 (setq date1 (list m d y1)
16232 n1 (calendar-absolute-from-gregorian date1)
16233 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16234 n2 (calendar-absolute-from-gregorian date2)))
16235 ((eq dw 'month)
16236 ;; approx number of month between the two dates
16237 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16238 ;; How often does dn fit in there?
16239 (setq d (nth 1 start) m (car start) y (nth 2 start)
16240 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16241 m (+ m nm)
16242 ny (floor (/ m 12))
16243 y (+ y ny)
16244 m (- m (* ny 12)))
16245 (while (> m 12) (setq m (- m 12) y (1+ y)))
16246 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16247 (setq m2 (+ m dn) y2 y)
16248 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16249 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16250 (while (<= n2 cday)
16251 (setq n1 n2 m m2 y y2)
16252 (setq m2 (+ m dn) y2 y)
16253 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16254 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16255 ;; Make sure n1 is the earlier date
16256 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16257 (if show-all
16258 (cond
16259 ((eq prefer 'past) (if (= cday n2) n2 n1))
16260 ((eq prefer 'future) (if (= cday n1) n1 n2))
16261 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16262 (cond
16263 ((eq prefer 'past) (if (= cday n2) n2 n1))
16264 ((eq prefer 'future) (if (= cday n1) n1 n2))
16265 (t (if (= cday n1) n1 n2)))))))
16267 (defun org-date-to-gregorian (date)
16268 "Turn any specification of DATE into a Gregorian date for the calendar."
16269 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16270 ((and (listp date) (= (length date) 3)) date)
16271 ((stringp date)
16272 (setq date (org-parse-time-string date))
16273 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16274 ((listp date)
16275 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16277 (defun org-parse-time-string (s &optional nodefault)
16278 "Parse the standard Org-mode time string.
16279 This should be a lot faster than the normal `parse-time-string'.
16280 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16281 hour and minute fields will be nil if not given."
16282 (if (string-match org-ts-regexp0 s)
16283 (list 0
16284 (if (or (match-beginning 8) (not nodefault))
16285 (string-to-number (or (match-string 8 s) "0")))
16286 (if (or (match-beginning 7) (not nodefault))
16287 (string-to-number (or (match-string 7 s) "0")))
16288 (string-to-number (match-string 4 s))
16289 (string-to-number (match-string 3 s))
16290 (string-to-number (match-string 2 s))
16291 nil nil nil)
16292 (error "Not a standard Org-mode time string: %s" s)))
16294 (defun org-timestamp-up (&optional arg)
16295 "Increase the date item at the cursor by one.
16296 If the cursor is on the year, change the year. If it is on the month,
16297 the day or the time, change that.
16298 With prefix ARG, change by that many units."
16299 (interactive "p")
16300 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16302 (defun org-timestamp-down (&optional arg)
16303 "Decrease the date item at the cursor by one.
16304 If the cursor is on the year, change the year. If it is on the month,
16305 the day or the time, change that.
16306 With prefix ARG, change by that many units."
16307 (interactive "p")
16308 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16310 (defun org-timestamp-up-day (&optional arg)
16311 "Increase the date in the time stamp by one day.
16312 With prefix ARG, change that many days."
16313 (interactive "p")
16314 (if (and (not (org-at-timestamp-p t))
16315 (org-at-heading-p))
16316 (org-todo 'up)
16317 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16319 (defun org-timestamp-down-day (&optional arg)
16320 "Decrease the date in the time stamp by one day.
16321 With prefix ARG, change that many days."
16322 (interactive "p")
16323 (if (and (not (org-at-timestamp-p t))
16324 (org-at-heading-p))
16325 (org-todo 'down)
16326 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16328 (defun org-at-timestamp-p (&optional inactive-ok)
16329 "Determine if the cursor is in or at a timestamp."
16330 (interactive)
16331 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16332 (pos (point))
16333 (ans (or (looking-at tsr)
16334 (save-excursion
16335 (skip-chars-backward "^[<\n\r\t")
16336 (if (> (point) (point-min)) (backward-char 1))
16337 (and (looking-at tsr)
16338 (> (- (match-end 0) pos) -1))))))
16339 (and ans
16340 (boundp 'org-ts-what)
16341 (setq org-ts-what
16342 (cond
16343 ((= pos (match-beginning 0)) 'bracket)
16344 ;; Point is considered to be "on the bracket" whether
16345 ;; it's really on it or right after it.
16346 ((= pos (1- (match-end 0))) 'bracket)
16347 ((= pos (match-end 0)) 'after)
16348 ((org-pos-in-match-range pos 2) 'year)
16349 ((org-pos-in-match-range pos 3) 'month)
16350 ((org-pos-in-match-range pos 7) 'hour)
16351 ((org-pos-in-match-range pos 8) 'minute)
16352 ((or (org-pos-in-match-range pos 4)
16353 (org-pos-in-match-range pos 5)) 'day)
16354 ((and (> pos (or (match-end 8) (match-end 5)))
16355 (< pos (match-end 0)))
16356 (- pos (or (match-end 8) (match-end 5))))
16357 (t 'day))))
16358 ans))
16360 (defun org-toggle-timestamp-type ()
16361 "Toggle the type (<active> or [inactive]) of a time stamp."
16362 (interactive)
16363 (when (org-at-timestamp-p t)
16364 (let ((beg (match-beginning 0)) (end (match-end 0))
16365 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16366 (save-excursion
16367 (goto-char beg)
16368 (while (re-search-forward "[][<>]" end t)
16369 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16370 t t)))
16371 (message "Timestamp is now %sactive"
16372 (if (equal (char-after beg) ?<) "" "in")))))
16374 (defvar org-clock-history) ; defined in org-clock.el
16375 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16376 (defun org-timestamp-change (n &optional what updown)
16377 "Change the date in the time stamp at point.
16378 The date will be changed by N times WHAT. WHAT can be `day', `month',
16379 `year', `minute', `second'. If WHAT is not given, the cursor position
16380 in the timestamp determines what will be changed."
16381 (let ((origin (point)) origin-cat
16382 with-hm inactive
16383 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16384 org-ts-what
16385 extra rem
16386 ts time time0 fixnext clrgx)
16387 (if (not (org-at-timestamp-p t))
16388 (error "Not at a timestamp"))
16389 (if (and (not what) (eq org-ts-what 'bracket))
16390 (org-toggle-timestamp-type)
16391 ;; Point isn't on brackets. Remember the part of the time-stamp
16392 ;; the point was in. Indeed, size of time-stamps may change,
16393 ;; but point must be kept in the same category nonetheless.
16394 (setq origin-cat org-ts-what)
16395 (if (and (not what) (not (eq org-ts-what 'day))
16396 org-display-custom-times
16397 (get-text-property (point) 'display)
16398 (not (get-text-property (1- (point)) 'display)))
16399 (setq org-ts-what 'day))
16400 (setq org-ts-what (or what org-ts-what)
16401 inactive (= (char-after (match-beginning 0)) ?\[)
16402 ts (match-string 0))
16403 (replace-match "")
16404 (if (string-match
16405 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16407 (setq extra (match-string 1 ts)))
16408 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16409 (setq with-hm t))
16410 (setq time0 (org-parse-time-string ts))
16411 (when (and updown
16412 (eq org-ts-what 'minute)
16413 (not current-prefix-arg))
16414 ;; This looks like s-up and s-down. Change by one rounding step.
16415 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16416 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16417 (setcar (cdr time0) (+ (nth 1 time0)
16418 (if (> n 0) (- rem) (- dm rem))))))
16419 (setq time
16420 (encode-time (or (car time0) 0)
16421 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16422 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16423 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16424 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16425 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16426 (nthcdr 6 time0)))
16427 (when (and (member org-ts-what '(hour minute))
16428 extra
16429 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16430 (setq extra (org-modify-ts-extra
16431 extra
16432 (if (eq org-ts-what 'hour) 2 5)
16433 n dm)))
16434 (when (integerp org-ts-what)
16435 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16436 (if (eq what 'calendar)
16437 (let ((cal-date (org-get-date-from-calendar)))
16438 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16439 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16440 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16441 (setcar time0 (or (car time0) 0))
16442 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16443 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16444 (setq time (apply 'encode-time time0))))
16445 ;; Insert the new time-stamp, and ensure point stays in the same
16446 ;; category as before (i.e. not after the last position in that
16447 ;; category).
16448 (let ((pos (point)))
16449 ;; Stay before inserted string. `save-excursion' is of no use.
16450 (setq org-last-changed-timestamp
16451 (org-insert-time-stamp time with-hm inactive nil nil extra))
16452 (goto-char pos))
16453 (save-match-data
16454 (looking-at org-ts-regexp3)
16455 (goto-char (cond
16456 ;; `day' category ends before `hour' if any, or at
16457 ;; the end of the day name.
16458 ((eq origin-cat 'day)
16459 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16460 ((eq origin-cat 'hour) (min (match-end 7) origin))
16461 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16462 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16463 ;; `year' and `month' have both fixed size: point
16464 ;; couldn't have moved into another part.
16465 (t origin))))
16466 ;; Update clock if on a CLOCK line.
16467 (org-clock-update-time-maybe)
16468 ;; Maybe adjust the closest clock in `org-clock-history'
16469 (when org-clock-adjust-closest
16470 (if (not (and (org-at-clock-log-p)
16471 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16472 org-clock-history))))))
16473 (message "No clock to adjust")
16474 (cond ((save-excursion ; fix previous clock?
16475 (re-search-backward org-ts-regexp0 nil t)
16476 (org-looking-back (concat org-clock-string " \\[")))
16477 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16478 ((save-excursion ; fix next clock?
16479 (re-search-backward org-ts-regexp0 nil t)
16480 (looking-at (concat org-ts-regexp0 "\\] =>")))
16481 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16482 (save-window-excursion
16483 ;; Find closest clock to point, adjust the previous/next one in history
16484 (let* ((p (save-excursion (org-back-to-heading t)))
16485 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16486 (clfixnth
16487 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16488 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16489 (if (not clfixpos)
16490 (message "No clock to adjust")
16491 (save-excursion
16492 (org-goto-marker-or-bmk clfixpos)
16493 (org-show-subtree)
16494 (when (re-search-forward clrgx nil t)
16495 (goto-char (match-beginning 1))
16496 (let (org-clock-adjust-closest)
16497 (org-timestamp-change n org-ts-what updown))
16498 (message "Clock adjusted in %s for heading: %s"
16499 (file-name-nondirectory (buffer-file-name))
16500 (org-get-heading t t)))))))))
16501 ;; Try to recenter the calendar window, if any.
16502 (if (and org-calendar-follow-timestamp-change
16503 (get-buffer-window "*Calendar*" t)
16504 (memq org-ts-what '(day month year)))
16505 (org-recenter-calendar (time-to-days time))))))
16507 (defun org-modify-ts-extra (s pos n dm)
16508 "Change the different parts of the lead-time and repeat fields in timestamp."
16509 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16510 ng h m new rem)
16511 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16512 (cond
16513 ((or (org-pos-in-match-range pos 2)
16514 (org-pos-in-match-range pos 3))
16515 (setq m (string-to-number (match-string 3 s))
16516 h (string-to-number (match-string 2 s)))
16517 (if (org-pos-in-match-range pos 2)
16518 (setq h (+ h n))
16519 (setq n (* dm (org-no-warnings (signum n))))
16520 (when (not (= 0 (setq rem (% m dm))))
16521 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16522 (setq m (+ m n)))
16523 (if (< m 0) (setq m (+ m 60) h (1- h)))
16524 (if (> m 59) (setq m (- m 60) h (1+ h)))
16525 (setq h (min 24 (max 0 h)))
16526 (setq ng 1 new (format "-%02d:%02d" h m)))
16527 ((org-pos-in-match-range pos 6)
16528 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16529 ((org-pos-in-match-range pos 5)
16530 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16532 ((org-pos-in-match-range pos 9)
16533 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16534 ((org-pos-in-match-range pos 8)
16535 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16537 (when ng
16538 (setq s (concat
16539 (substring s 0 (match-beginning ng))
16541 (substring s (match-end ng))))))
16544 (defun org-recenter-calendar (date)
16545 "If the calendar is visible, recenter it to DATE."
16546 (let ((cwin (get-buffer-window "*Calendar*" t)))
16547 (when cwin
16548 (let ((calendar-move-hook nil))
16549 (with-selected-window cwin
16550 (calendar-goto-date (if (listp date) date
16551 (calendar-gregorian-from-absolute date))))))))
16553 (defun org-goto-calendar (&optional arg)
16554 "Go to the Emacs calendar at the current date.
16555 If there is a time stamp in the current line, go to that date.
16556 A prefix ARG can be used to force the current date."
16557 (interactive "P")
16558 (let ((tsr org-ts-regexp) diff
16559 (calendar-move-hook nil)
16560 (calendar-view-holidays-initially-flag nil)
16561 (calendar-view-diary-initially-flag nil))
16562 (if (or (org-at-timestamp-p)
16563 (save-excursion
16564 (beginning-of-line 1)
16565 (looking-at (concat ".*" tsr))))
16566 (let ((d1 (time-to-days (current-time)))
16567 (d2 (time-to-days
16568 (org-time-string-to-time (match-string 1)))))
16569 (setq diff (- d2 d1))))
16570 (calendar)
16571 (calendar-goto-today)
16572 (if (and diff (not arg)) (calendar-forward-day diff))))
16574 (defun org-get-date-from-calendar ()
16575 "Return a list (month day year) of date at point in calendar."
16576 (with-current-buffer "*Calendar*"
16577 (save-match-data
16578 (calendar-cursor-to-date))))
16580 (defun org-date-from-calendar ()
16581 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16582 If there is already a time stamp at the cursor position, update it."
16583 (interactive)
16584 (if (org-at-timestamp-p t)
16585 (org-timestamp-change 0 'calendar)
16586 (let ((cal-date (org-get-date-from-calendar)))
16587 (org-insert-time-stamp
16588 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16590 (defun org-minutes-to-hh:mm-string (m)
16591 "Compute H:MM from a number of minutes."
16592 (let ((h (/ m 60)))
16593 (setq m (- m (* 60 h)))
16594 (format org-time-clocksum-format h m)))
16596 (defun org-hh:mm-string-to-minutes (s)
16597 "Convert a string H:MM to a number of minutes.
16598 If the string is just a number, interpret it as minutes.
16599 In fact, the first hh:mm or number in the string will be taken,
16600 there can be extra stuff in the string.
16601 If no number is found, the return value is 0."
16602 (cond
16603 ((integerp s) s)
16604 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16605 (+ (* (string-to-number (match-string 1 s)) 60)
16606 (string-to-number (match-string 2 s))))
16607 ((string-match "\\([0-9]+\\)" s)
16608 (string-to-number (match-string 1 s)))
16609 (t 0)))
16611 (defcustom org-effort-durations
16612 `(("h" . 60)
16613 ("d" . ,(* 60 8))
16614 ("w" . ,(* 60 8 5))
16615 ("m" . ,(* 60 8 5 4))
16616 ("y" . ,(* 60 8 5 40)))
16617 "Conversion factor to minutes for an effort modifier.
16619 Each entry has the form (MODIFIER . MINUTES).
16621 In an effort string, a number followed by MODIFIER is multiplied
16622 by the specified number of MINUTES to obtain an effort in
16623 minutes.
16625 For example, if the value of this variable is ((\"hours\" . 60)), then an
16626 effort string \"2hours\" is equivalent to 120 minutes."
16627 :group 'org-agenda
16628 :version "24.1"
16629 :type '(alist :key-type (string :tag "Modifier")
16630 :value-type (number :tag "Minutes")))
16632 (defun org-duration-string-to-minutes (s &optional output-to-string)
16633 "Convert a duration string S to minutes.
16635 A bare number is interpreted as minutes, modifiers can be set by
16636 customizing `org-effort-durations' (which see).
16638 Entries containing a colon are interpreted as H:MM by
16639 `org-hh:mm-string-to-minutes'."
16640 (let ((result 0)
16641 (re (concat "\\([0-9.]+\\) *\\("
16642 (regexp-opt (mapcar 'car org-effort-durations))
16643 "\\)")))
16644 (while (string-match re s)
16645 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16646 (string-to-number (match-string 1 s))))
16647 (setq s (replace-match "" nil t s)))
16648 (setq result (floor result))
16649 (incf result (org-hh:mm-string-to-minutes s))
16650 (if output-to-string (number-to-string result) result)))
16652 ;;;; Files
16654 (defun org-save-all-org-buffers ()
16655 "Save all Org-mode buffers without user confirmation."
16656 (interactive)
16657 (message "Saving all Org-mode buffers...")
16658 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16659 (when (featurep 'org-id) (org-id-locations-save))
16660 (message "Saving all Org-mode buffers... done"))
16662 (defun org-revert-all-org-buffers ()
16663 "Revert all Org-mode buffers.
16664 Prompt for confirmation when there are unsaved changes.
16665 Be sure you know what you are doing before letting this function
16666 overwrite your changes.
16668 This function is useful in a setup where one tracks org files
16669 with a version control system, to revert on one machine after pulling
16670 changes from another. I believe the procedure must be like this:
16672 1. M-x org-save-all-org-buffers
16673 2. Pull changes from the other machine, resolve conflicts
16674 3. M-x org-revert-all-org-buffers"
16675 (interactive)
16676 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16677 (error "Abort"))
16678 (save-excursion
16679 (save-window-excursion
16680 (mapc
16681 (lambda (b)
16682 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16683 (with-current-buffer b buffer-file-name))
16684 (org-pop-to-buffer-same-window b)
16685 (revert-buffer t 'no-confirm)))
16686 (buffer-list))
16687 (when (and (featurep 'org-id) org-id-track-globally)
16688 (org-id-locations-load)))))
16690 ;;;; Agenda files
16692 ;;;###autoload
16693 (defun org-switchb (&optional arg)
16694 "Switch between Org buffers.
16695 With one prefix argument, restrict available buffers to files.
16696 With two prefix arguments, restrict available buffers to agenda files.
16698 Defaults to `iswitchb' for buffer name completion.
16699 Set `org-completion-use-ido' to make it use ido instead."
16700 (interactive "P")
16701 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16702 ((equal arg '(16)) (org-buffer-list 'agenda))
16703 (t (org-buffer-list))))
16704 (org-completion-use-iswitchb org-completion-use-iswitchb)
16705 (org-completion-use-ido org-completion-use-ido))
16706 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16707 (setq org-completion-use-iswitchb t))
16708 (org-pop-to-buffer-same-window
16709 (org-icompleting-read "Org buffer: "
16710 (mapcar 'list (mapcar 'buffer-name blist))
16711 nil t))))
16713 ;;; Define some older names previously used for this functionality
16714 ;;;###autoload
16715 (defalias 'org-ido-switchb 'org-switchb)
16716 ;;;###autoload
16717 (defalias 'org-iswitchb 'org-switchb)
16719 (defun org-buffer-list (&optional predicate exclude-tmp)
16720 "Return a list of Org buffers.
16721 PREDICATE can be `export', `files' or `agenda'.
16723 export restrict the list to Export buffers.
16724 files restrict the list to buffers visiting Org files.
16725 agenda restrict the list to buffers visiting agenda files.
16727 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16728 (let* ((bfn nil)
16729 (agenda-files (and (eq predicate 'agenda)
16730 (mapcar 'file-truename (org-agenda-files t))))
16731 (filter
16732 (cond
16733 ((eq predicate 'files)
16734 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16735 ((eq predicate 'export)
16736 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16737 ((eq predicate 'agenda)
16738 (lambda (b)
16739 (with-current-buffer b
16740 (and (derived-mode-p 'org-mode)
16741 (setq bfn (buffer-file-name b))
16742 (member (file-truename bfn) agenda-files)))))
16743 (t (lambda (b) (with-current-buffer b
16744 (or (derived-mode-p 'org-mode)
16745 (string-match "\*Org .*Export"
16746 (buffer-name b)))))))))
16747 (delq nil
16748 (mapcar
16749 (lambda(b)
16750 (if (and (funcall filter b)
16751 (or (not exclude-tmp)
16752 (not (string-match "tmp" (buffer-name b)))))
16754 nil))
16755 (buffer-list)))))
16757 (defun org-agenda-files (&optional unrestricted archives)
16758 "Get the list of agenda files.
16759 Optional UNRESTRICTED means return the full list even if a restriction
16760 is currently in place.
16761 When ARCHIVES is t, include all archive files that are really being
16762 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16763 `org-agenda-archives-mode' is t."
16764 (let ((files
16765 (cond
16766 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16767 ((stringp org-agenda-files) (org-read-agenda-file-list))
16768 ((listp org-agenda-files) org-agenda-files)
16769 (t (error "Invalid value of `org-agenda-files'")))))
16770 (setq files (apply 'append
16771 (mapcar (lambda (f)
16772 (if (file-directory-p f)
16773 (directory-files
16774 f t org-agenda-file-regexp)
16775 (list f)))
16776 files)))
16777 (when org-agenda-skip-unavailable-files
16778 (setq files (delq nil
16779 (mapcar (function
16780 (lambda (file)
16781 (and (file-readable-p file) file)))
16782 files))))
16783 (when (or (eq archives t)
16784 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16785 (setq files (org-add-archive-files files)))
16786 files))
16788 (defun org-agenda-file-p (&optional file)
16789 "Return non-nil, if FILE is an agenda file.
16790 If FILE is omitted, use the file associated with the current
16791 buffer."
16792 (member (or file (buffer-file-name))
16793 (org-agenda-files t)))
16795 (defun org-edit-agenda-file-list ()
16796 "Edit the list of agenda files.
16797 Depending on setup, this either uses customize to edit the variable
16798 `org-agenda-files', or it visits the file that is holding the list. In the
16799 latter case, the buffer is set up in a way that saving it automatically kills
16800 the buffer and restores the previous window configuration."
16801 (interactive)
16802 (if (stringp org-agenda-files)
16803 (let ((cw (current-window-configuration)))
16804 (find-file org-agenda-files)
16805 (org-set-local 'org-window-configuration cw)
16806 (org-add-hook 'after-save-hook
16807 (lambda ()
16808 (set-window-configuration
16809 (prog1 org-window-configuration
16810 (kill-buffer (current-buffer))))
16811 (org-install-agenda-files-menu)
16812 (message "New agenda file list installed"))
16813 nil 'local)
16814 (message "%s" (substitute-command-keys
16815 "Edit list and finish with \\[save-buffer]")))
16816 (customize-variable 'org-agenda-files)))
16818 (defun org-store-new-agenda-file-list (list)
16819 "Set new value for the agenda file list and save it correctly."
16820 (if (stringp org-agenda-files)
16821 (let ((fe (org-read-agenda-file-list t)) b u)
16822 (while (setq b (find-buffer-visiting org-agenda-files))
16823 (kill-buffer b))
16824 (with-temp-file org-agenda-files
16825 (insert
16826 (mapconcat
16827 (lambda (f) ;; Keep un-expanded entries.
16828 (if (setq u (assoc f fe))
16829 (cdr u)
16831 list "\n")
16832 "\n")))
16833 (let ((org-mode-hook nil) (org-inhibit-startup t)
16834 (org-insert-mode-line-in-empty-file nil))
16835 (setq org-agenda-files list)
16836 (customize-save-variable 'org-agenda-files org-agenda-files))))
16838 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16839 "Read the list of agenda files from a file.
16840 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16841 filenames, used by `org-store-new-agenda-file-list' to write back
16842 un-expanded file names."
16843 (when (file-directory-p org-agenda-files)
16844 (error "`org-agenda-files' cannot be a single directory"))
16845 (when (stringp org-agenda-files)
16846 (with-temp-buffer
16847 (insert-file-contents org-agenda-files)
16848 (mapcar
16849 (lambda (f)
16850 (let ((e (expand-file-name (substitute-in-file-name f)
16851 org-directory)))
16852 (if pair-with-expansion
16853 (cons e f)
16854 e)))
16855 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16857 ;;;###autoload
16858 (defun org-cycle-agenda-files ()
16859 "Cycle through the files in `org-agenda-files'.
16860 If the current buffer visits an agenda file, find the next one in the list.
16861 If the current buffer does not, find the first agenda file."
16862 (interactive)
16863 (let* ((fs (org-agenda-files t))
16864 (files (append fs (list (car fs))))
16865 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16866 file)
16867 (unless files (error "No agenda files"))
16868 (catch 'exit
16869 (while (setq file (pop files))
16870 (if (equal (file-truename file) tcf)
16871 (when (car files)
16872 (find-file (car files))
16873 (throw 'exit t))))
16874 (find-file (car fs)))
16875 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16877 (defun org-agenda-file-to-front (&optional to-end)
16878 "Move/add the current file to the top of the agenda file list.
16879 If the file is not present in the list, it is added to the front. If it is
16880 present, it is moved there. With optional argument TO-END, add/move to the
16881 end of the list."
16882 (interactive "P")
16883 (let ((org-agenda-skip-unavailable-files nil)
16884 (file-alist (mapcar (lambda (x)
16885 (cons (file-truename x) x))
16886 (org-agenda-files t)))
16887 (ctf (file-truename
16888 (or buffer-file-name
16889 (error "Please save the current buffer to a file"))))
16890 x had)
16891 (setq x (assoc ctf file-alist) had x)
16893 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16894 (if to-end
16895 (setq file-alist (append (delq x file-alist) (list x)))
16896 (setq file-alist (cons x (delq x file-alist))))
16897 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16898 (org-install-agenda-files-menu)
16899 (message "File %s to %s of agenda file list"
16900 (if had "moved" "added") (if to-end "end" "front"))))
16902 (defun org-remove-file (&optional file)
16903 "Remove current file from the list of files in variable `org-agenda-files'.
16904 These are the files which are being checked for agenda entries.
16905 Optional argument FILE means use this file instead of the current."
16906 (interactive)
16907 (let* ((org-agenda-skip-unavailable-files nil)
16908 (file (or file buffer-file-name
16909 (error "Current buffer does not visit a file")))
16910 (true-file (file-truename file))
16911 (afile (abbreviate-file-name file))
16912 (files (delq nil (mapcar
16913 (lambda (x)
16914 (if (equal true-file
16915 (file-truename x))
16916 nil x))
16917 (org-agenda-files t)))))
16918 (if (not (= (length files) (length (org-agenda-files t))))
16919 (progn
16920 (org-store-new-agenda-file-list files)
16921 (org-install-agenda-files-menu)
16922 (message "Removed file: %s" afile))
16923 (message "File was not in list: %s (not removed)" afile))))
16925 (defun org-file-menu-entry (file)
16926 (vector file (list 'find-file file) t))
16928 (defun org-check-agenda-file (file)
16929 "Make sure FILE exists. If not, ask user what to do."
16930 (when (not (file-exists-p file))
16931 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
16932 (abbreviate-file-name file))
16933 (let ((r (downcase (read-char-exclusive))))
16934 (cond
16935 ((equal r ?r)
16936 (org-remove-file file)
16937 (throw 'nextfile t))
16938 (t (error "Abort"))))))
16940 (defun org-get-agenda-file-buffer (file)
16941 "Get a buffer visiting FILE. If the buffer needs to be created, add
16942 it to the list of buffers which might be released later."
16943 (let ((buf (org-find-base-buffer-visiting file)))
16944 (if buf
16945 buf ; just return it
16946 ;; Make a new buffer and remember it
16947 (setq buf (find-file-noselect file))
16948 (if buf (push buf org-agenda-new-buffers))
16949 buf)))
16951 (defun org-release-buffers (blist)
16952 "Release all buffers in list, asking the user for confirmation when needed.
16953 When a buffer is unmodified, it is just killed. When modified, it is saved
16954 \(if the user agrees) and then killed."
16955 (let (buf file)
16956 (while (setq buf (pop blist))
16957 (setq file (buffer-file-name buf))
16958 (when (and (buffer-modified-p buf)
16959 file
16960 (y-or-n-p (format "Save file %s? " file)))
16961 (with-current-buffer buf (save-buffer)))
16962 (kill-buffer buf))))
16964 (defun org-agenda-prepare-buffers (files)
16965 "Create buffers for all agenda files, protect archived trees and comments."
16966 (interactive)
16967 (let ((pa '(:org-archived t))
16968 (pc '(:org-comment t))
16969 (pall '(:org-archived t :org-comment t))
16970 (inhibit-read-only t)
16971 (rea (concat ":" org-archive-tag ":"))
16972 bmp file re)
16973 (save-excursion
16974 (save-restriction
16975 (while (setq file (pop files))
16976 (catch 'nextfile
16977 (if (bufferp file)
16978 (set-buffer file)
16979 (org-check-agenda-file file)
16980 (set-buffer (org-get-agenda-file-buffer file)))
16981 (widen)
16982 (setq bmp (buffer-modified-p))
16983 (org-refresh-category-properties)
16984 (setq org-todo-keywords-for-agenda
16985 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16986 (setq org-done-keywords-for-agenda
16987 (append org-done-keywords-for-agenda org-done-keywords))
16988 (setq org-todo-keyword-alist-for-agenda
16989 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16990 (setq org-drawers-for-agenda
16991 (append org-drawers-for-agenda org-drawers))
16992 (setq org-tag-alist-for-agenda
16993 (append org-tag-alist-for-agenda org-tag-alist))
16995 (save-excursion
16996 (remove-text-properties (point-min) (point-max) pall)
16997 (when org-agenda-skip-archived-trees
16998 (goto-char (point-min))
16999 (while (re-search-forward rea nil t)
17000 (if (org-at-heading-p t)
17001 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17002 (goto-char (point-min))
17003 (setq re (format org-heading-keyword-regexp-format
17004 org-comment-string))
17005 (while (re-search-forward re nil t)
17006 (add-text-properties
17007 (match-beginning 0) (org-end-of-subtree t) pc)))
17008 (set-buffer-modified-p bmp)))))
17009 (setq org-todo-keywords-for-agenda
17010 (org-uniquify org-todo-keywords-for-agenda))
17011 (setq org-todo-keyword-alist-for-agenda
17012 (org-uniquify org-todo-keyword-alist-for-agenda)
17013 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17015 ;;;; Embedded LaTeX
17017 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17018 "Keymap for the minor `org-cdlatex-mode'.")
17020 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17021 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17022 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17023 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17024 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17026 (defvar org-cdlatex-texmathp-advice-is-done nil
17027 "Flag remembering if we have applied the advice to texmathp already.")
17029 (define-minor-mode org-cdlatex-mode
17030 "Toggle the minor `org-cdlatex-mode'.
17031 This mode supports entering LaTeX environment and math in LaTeX fragments
17032 in Org-mode.
17033 \\{org-cdlatex-mode-map}"
17034 nil " OCDL" nil
17035 (when org-cdlatex-mode
17036 (require 'cdlatex)
17037 (run-hooks 'cdlatex-mode-hook)
17038 (cdlatex-compute-tables))
17039 (unless org-cdlatex-texmathp-advice-is-done
17040 (setq org-cdlatex-texmathp-advice-is-done t)
17041 (defadvice texmathp (around org-math-always-on activate)
17042 "Always return t in org-mode buffers.
17043 This is because we want to insert math symbols without dollars even outside
17044 the LaTeX math segments. If Orgmode thinks that point is actually inside
17045 an embedded LaTeX fragment, let texmathp do its job.
17046 \\[org-cdlatex-mode-map]"
17047 (interactive)
17048 (let (p)
17049 (cond
17050 ((not (derived-mode-p 'org-mode)) ad-do-it)
17051 ((eq this-command 'cdlatex-math-symbol)
17052 (setq ad-return-value t
17053 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17055 (let ((p (org-inside-LaTeX-fragment-p)))
17056 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17057 (setq ad-return-value t
17058 texmathp-why '("Org-mode embedded math" . 0))
17059 (if p ad-do-it)))))))))
17061 (defun turn-on-org-cdlatex ()
17062 "Unconditionally turn on `org-cdlatex-mode'."
17063 (org-cdlatex-mode 1))
17065 (defun org-inside-LaTeX-fragment-p ()
17066 "Test if point is inside a LaTeX fragment.
17067 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17068 sequence appearing also before point.
17069 Even though the matchers for math are configurable, this function assumes
17070 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17071 delimiters are skipped when they have been removed by customization.
17072 The return value is nil, or a cons cell with the delimiter and the
17073 position of this delimiter.
17075 This function does a reasonably good job, but can locally be fooled by
17076 for example currency specifications. For example it will assume being in
17077 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17078 fragments that are properly closed, but during editing, we have to live
17079 with the uncertainty caused by missing closing delimiters. This function
17080 looks only before point, not after."
17081 (catch 'exit
17082 (let ((pos (point))
17083 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17084 (lim (progn
17085 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17086 (point)))
17087 dd-on str (start 0) m re)
17088 (goto-char pos)
17089 (when dodollar
17090 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17091 re (nth 1 (assoc "$" org-latex-regexps)))
17092 (while (string-match re str start)
17093 (cond
17094 ((= (match-end 0) (length str))
17095 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17096 ((= (match-end 0) (- (length str) 5))
17097 (throw 'exit nil))
17098 (t (setq start (match-end 0))))))
17099 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17100 (goto-char pos)
17101 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17102 (and (match-beginning 2) (throw 'exit nil))
17103 ;; count $$
17104 (while (re-search-backward "\\$\\$" lim t)
17105 (setq dd-on (not dd-on)))
17106 (goto-char pos)
17107 (if dd-on (cons "$$" m))))))
17109 (defun org-inside-latex-macro-p ()
17110 "Is point inside a LaTeX macro or its arguments?"
17111 (save-match-data
17112 (org-in-regexp
17113 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17115 (defun org-try-cdlatex-tab ()
17116 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17117 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17118 - inside a LaTeX fragment, or
17119 - after the first word in a line, where an abbreviation expansion could
17120 insert a LaTeX environment."
17121 (when org-cdlatex-mode
17122 (cond
17123 ;; Before any word on the line: No expansion possible.
17124 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17125 ;; Just after first word on the line: Expand it. Make sure it
17126 ;; cannot happen on headlines, though.
17127 ((save-excursion
17128 (skip-chars-backward "a-zA-Z0-9*")
17129 (skip-chars-backward " \t")
17130 (and (bolp) (not (org-at-heading-p))))
17131 (cdlatex-tab) t)
17132 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17134 (defun org-cdlatex-underscore-caret (&optional arg)
17135 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17136 Revert to the normal definition outside of these fragments."
17137 (interactive "P")
17138 (if (org-inside-LaTeX-fragment-p)
17139 (call-interactively 'cdlatex-sub-superscript)
17140 (let (org-cdlatex-mode)
17141 (call-interactively (key-binding (vector last-input-event))))))
17143 (defun org-cdlatex-math-modify (&optional arg)
17144 "Execute `cdlatex-math-modify' in LaTeX fragments.
17145 Revert to the normal definition outside of these fragments."
17146 (interactive "P")
17147 (if (org-inside-LaTeX-fragment-p)
17148 (call-interactively 'cdlatex-math-modify)
17149 (let (org-cdlatex-mode)
17150 (call-interactively (key-binding (vector last-input-event))))))
17152 (defvar org-latex-fragment-image-overlays nil
17153 "List of overlays carrying the images of latex fragments.")
17154 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17156 (defun org-remove-latex-fragment-image-overlays ()
17157 "Remove all overlays with LaTeX fragment images in current buffer."
17158 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17159 (setq org-latex-fragment-image-overlays nil))
17161 (defun org-preview-latex-fragment (&optional subtree)
17162 "Preview the LaTeX fragment at point, or all locally or globally.
17163 If the cursor is in a LaTeX fragment, create the image and overlay
17164 it over the source code. If there is no fragment at point, display
17165 all fragments in the current text, from one headline to the next. With
17166 prefix SUBTREE, display all fragments in the current subtree. With a
17167 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17168 the cursor is before the first headline,
17169 display all fragments in the buffer.
17170 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17171 (interactive "P")
17172 (unless buffer-file-name
17173 (error "Can't preview LaTeX fragment in a non-file buffer"))
17174 (org-remove-latex-fragment-image-overlays)
17175 (save-excursion
17176 (save-restriction
17177 (let (beg end at msg)
17178 (cond
17179 ((or (equal subtree '(16))
17180 (not (save-excursion
17181 (re-search-backward org-outline-regexp-bol nil t))))
17182 (setq beg (point-min) end (point-max)
17183 msg "Creating images for buffer...%s"))
17184 ((equal subtree '(4))
17185 (org-back-to-heading)
17186 (setq beg (point) end (org-end-of-subtree t)
17187 msg "Creating images for subtree...%s"))
17189 (if (setq at (org-inside-LaTeX-fragment-p))
17190 (goto-char (max (point-min) (- (cdr at) 2)))
17191 (org-back-to-heading))
17192 (setq beg (point) end (progn (outline-next-heading) (point))
17193 msg (if at "Creating image...%s"
17194 "Creating images for entry...%s"))))
17195 (message msg "")
17196 (narrow-to-region beg end)
17197 (goto-char beg)
17198 (org-format-latex
17199 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17200 (file-name-nondirectory
17201 buffer-file-name)))
17202 default-directory 'overlays msg at 'forbuffer
17203 org-latex-create-formula-image-program)
17204 (message msg "done. Use `C-c C-c' to remove images.")))))
17206 (defvar org-latex-regexps
17207 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17208 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17209 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17210 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17211 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17212 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17213 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17214 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17215 "Regular expressions for matching embedded LaTeX.")
17217 (defvar org-export-have-math nil) ;; dynamic scoping
17218 (defun org-format-latex (prefix &optional dir overlays msg at
17219 forbuffer processing-type)
17220 "Replace LaTeX fragments with links to an image, and produce images.
17221 Some of the options can be changed using the variable
17222 `org-format-latex-options'."
17223 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17224 (let* ((prefixnodir (file-name-nondirectory prefix))
17225 (absprefix (expand-file-name prefix dir))
17226 (todir (file-name-directory absprefix))
17227 (opt org-format-latex-options)
17228 (matchers (plist-get opt :matchers))
17229 (re-list org-latex-regexps)
17230 (org-format-latex-header-extra
17231 (plist-get (org-infile-export-plist) :latex-header-extra))
17232 (cnt 0) txt hash link beg end re e checkdir
17233 executables-checked string
17234 m n block-type block linkfile movefile ov)
17235 ;; Check the different regular expressions
17236 (while (setq e (pop re-list))
17237 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17238 block (if block-type "\n\n" ""))
17239 (when (member m matchers)
17240 (goto-char (point-min))
17241 (while (re-search-forward re nil t)
17242 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17243 (not (get-text-property (match-beginning n)
17244 'org-protected))
17245 (or (not overlays)
17246 (not (eq (get-char-property (match-beginning n)
17247 'org-overlay-type)
17248 'org-latex-overlay))))
17249 (setq org-export-have-math t)
17250 (cond
17251 ((eq processing-type 'verbatim)
17252 ;; Leave the text verbatim, just protect it
17253 (add-text-properties (match-beginning n) (match-end n)
17254 '(org-protected t)))
17255 ((eq processing-type 'mathjax)
17256 ;; Prepare for MathJax processing
17257 (setq string (match-string n))
17258 (if (member m '("$" "$1"))
17259 (save-excursion
17260 (delete-region (match-beginning n) (match-end n))
17261 (goto-char (match-beginning n))
17262 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17263 "\\)")
17264 '(org-protected t))))
17265 (add-text-properties (match-beginning n) (match-end n)
17266 '(org-protected t))))
17267 ((or (eq processing-type 'dvipng)
17268 (eq processing-type 'imagemagick))
17269 ;; Process to an image
17270 (setq txt (match-string n)
17271 beg (match-beginning n) end (match-end n)
17272 cnt (1+ cnt))
17273 (let (print-length print-level) ; make sure full list is printed
17274 (setq hash (sha1 (prin1-to-string
17275 (list org-format-latex-header
17276 org-format-latex-header-extra
17277 org-export-latex-default-packages-alist
17278 org-export-latex-packages-alist
17279 org-format-latex-options
17280 forbuffer txt)))
17281 linkfile (format "%s_%s.png" prefix hash)
17282 movefile (format "%s_%s.png" absprefix hash)))
17283 (setq link (concat block "[[file:" linkfile "]]" block))
17284 (if msg (message msg cnt))
17285 (goto-char beg)
17286 (unless checkdir ; make sure the directory exists
17287 (setq checkdir t)
17288 (or (file-directory-p todir) (make-directory todir t)))
17289 (cond
17290 ((eq processing-type 'dvipng)
17291 (unless executables-checked
17292 (org-check-external-command
17293 "latex" "needed to convert LaTeX fragments to images")
17294 (org-check-external-command
17295 "dvipng" "needed to convert LaTeX fragments to images")
17296 (setq executables-checked t))
17297 (unless (file-exists-p movefile)
17298 (org-create-formula-image-with-dvipng
17299 txt movefile opt forbuffer)))
17300 ((eq processing-type 'imagemagick)
17301 (unless executables-checked
17302 (org-check-external-command
17303 "convert" "you need to install imagemagick")
17304 (setq executables-checked t))
17305 (unless (file-exists-p movefile)
17306 (org-create-formula-image-with-imagemagick
17307 txt movefile opt forbuffer))))
17308 (if overlays
17309 (progn
17310 (mapc (lambda (o)
17311 (if (eq (overlay-get o 'org-overlay-type)
17312 'org-latex-overlay)
17313 (delete-overlay o)))
17314 (overlays-in beg end))
17315 (setq ov (make-overlay beg end))
17316 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17317 (if (featurep 'xemacs)
17318 (progn
17319 (overlay-put ov 'invisible t)
17320 (overlay-put
17321 ov 'end-glyph
17322 (make-glyph (vector 'png :file movefile))))
17323 (overlay-put
17324 ov 'display
17325 (list 'image :type 'png :file movefile :ascent 'center)))
17326 (push ov org-latex-fragment-image-overlays)
17327 (goto-char end))
17328 (delete-region beg end)
17329 (insert (org-add-props link
17330 (list 'org-latex-src
17331 (replace-regexp-in-string
17332 "\"" "" txt)
17333 'org-latex-src-embed-type
17334 (if block-type 'paragraph 'character))))))
17335 ((eq processing-type 'mathml)
17336 ;; Process to MathML
17337 (unless executables-checked
17338 (unless (save-match-data (org-format-latex-mathml-available-p))
17339 (error "LaTeX to MathML converter not configured"))
17340 (setq executables-checked t))
17341 (setq txt (match-string n)
17342 beg (match-beginning n) end (match-end n)
17343 cnt (1+ cnt))
17344 (if msg (message msg cnt))
17345 (goto-char beg)
17346 (delete-region beg end)
17347 (insert (org-format-latex-as-mathml
17348 txt block-type prefix dir)))
17350 (error "Unknown conversion type %s for latex fragments"
17351 processing-type)))))))))
17353 (defun org-create-math-formula (latex-frag &optional mathml-file)
17354 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17355 Use `org-latex-to-mathml-convert-command'. If the conversion is
17356 sucessful, return the portion between \"<math...> </math>\"
17357 elements otherwise return nil. When MATHML-FILE is specified,
17358 write the results in to that file. When invoked as an
17359 interactive command, prompt for LATEX-FRAG, with initial value
17360 set to the current active region and echo the results for user
17361 inspection."
17362 (interactive (list (let ((frag (when (org-region-active-p)
17363 (buffer-substring-no-properties
17364 (region-beginning) (region-end)))))
17365 (read-string "LaTeX Fragment: " frag nil frag))))
17366 (unless latex-frag (error "Invalid latex-frag"))
17367 (let* ((tmp-in-file (file-relative-name
17368 (make-temp-name (expand-file-name "ltxmathml-in"))))
17369 (ignore (write-region latex-frag nil tmp-in-file))
17370 (tmp-out-file (file-relative-name
17371 (make-temp-name (expand-file-name "ltxmathml-out"))))
17372 (cmd (format-spec
17373 org-latex-to-mathml-convert-command
17374 `((?j . ,(shell-quote-argument
17375 (expand-file-name org-latex-to-mathml-jar-file)))
17376 (?I . ,(shell-quote-argument tmp-in-file))
17377 (?o . ,(shell-quote-argument tmp-out-file)))))
17378 mathml shell-command-output)
17379 (when (org-called-interactively-p 'any)
17380 (unless (org-format-latex-mathml-available-p)
17381 (error "LaTeX to MathML converter not configured")))
17382 (message "Running %s" cmd)
17383 (setq shell-command-output (shell-command-to-string cmd))
17384 (setq mathml
17385 (when (file-readable-p tmp-out-file)
17386 (with-current-buffer (find-file-noselect tmp-out-file t)
17387 (goto-char (point-min))
17388 (when (re-search-forward
17389 (concat
17390 (regexp-quote
17391 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17392 "\\(.\\|\n\\)*"
17393 (regexp-quote "</math>")) nil t)
17394 (prog1 (match-string 0) (kill-buffer))))))
17395 (cond
17396 (mathml
17397 (setq mathml
17398 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17399 (when mathml-file
17400 (write-region mathml nil mathml-file))
17401 (when (org-called-interactively-p 'any)
17402 (message mathml)))
17403 ((message "LaTeX to MathML conversion failed")
17404 (message shell-command-output)))
17405 (delete-file tmp-in-file)
17406 (when (file-exists-p tmp-out-file)
17407 (delete-file tmp-out-file))
17408 mathml))
17410 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17411 prefix &optional dir)
17412 "Use `org-create-math-formula' but check local cache first."
17413 (let* ((absprefix (expand-file-name prefix dir))
17414 (print-length nil) (print-level nil)
17415 (formula-id (concat
17416 "formula-"
17417 (sha1
17418 (prin1-to-string
17419 (list latex-frag
17420 org-latex-to-mathml-convert-command)))))
17421 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17422 (formula-cache-dir (file-name-directory formula-cache)))
17424 (unless (file-directory-p formula-cache-dir)
17425 (make-directory formula-cache-dir t))
17427 (unless (file-exists-p formula-cache)
17428 (org-create-math-formula latex-frag formula-cache))
17430 (if (file-exists-p formula-cache)
17431 ;; Successful conversion. Return the link to MathML file.
17432 (org-add-props
17433 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17434 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17435 'org-latex-src-embed-type (if latex-frag-type
17436 'paragraph 'character)))
17437 ;; Failed conversion. Return the LaTeX fragment verbatim
17438 (add-text-properties
17439 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17440 latex-frag)))
17442 ;; This function borrows from Ganesh Swami's latex2png.el
17443 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17444 "This calls dvipng."
17445 (require 'org-latex)
17446 (let* ((tmpdir (if (featurep 'xemacs)
17447 (temp-directory)
17448 temporary-file-directory))
17449 (texfilebase (make-temp-name
17450 (expand-file-name "orgtex" tmpdir)))
17451 (texfile (concat texfilebase ".tex"))
17452 (dvifile (concat texfilebase ".dvi"))
17453 (pngfile (concat texfilebase ".png"))
17454 (fnh (if (featurep 'xemacs)
17455 (font-height (face-font 'default))
17456 (face-attribute 'default :height nil)))
17457 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17458 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17459 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17460 "Black"))
17461 (bg (or (plist-get options (if buffer :background :html-background))
17462 "Transparent")))
17463 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17464 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17465 (with-temp-file texfile
17466 (insert (org-splice-latex-header
17467 org-format-latex-header
17468 org-export-latex-default-packages-alist
17469 org-export-latex-packages-alist t
17470 org-format-latex-header-extra))
17471 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17472 (require 'org-latex)
17473 (org-export-latex-fix-inputenc))
17474 (let ((dir default-directory))
17475 (condition-case nil
17476 (progn
17477 (cd tmpdir)
17478 (call-process "latex" nil nil nil texfile))
17479 (error nil))
17480 (cd dir))
17481 (if (not (file-exists-p dvifile))
17482 (progn (message "Failed to create dvi file from %s" texfile) nil)
17483 (condition-case nil
17484 (if (featurep 'xemacs)
17485 (call-process "dvipng" nil nil nil
17486 "-fg" fg "-bg" bg
17487 "-T" "tight"
17488 "-o" pngfile
17489 dvifile)
17490 (call-process "dvipng" nil nil nil
17491 "-fg" fg "-bg" bg
17492 "-D" dpi
17493 ;;"-x" scale "-y" scale
17494 "-T" "tight"
17495 "-o" pngfile
17496 dvifile))
17497 (error nil))
17498 (if (not (file-exists-p pngfile))
17499 (if org-format-latex-signal-error
17500 (error "Failed to create png file from %s" texfile)
17501 (message "Failed to create png file from %s" texfile)
17502 nil)
17503 ;; Use the requested file name and clean up
17504 (copy-file pngfile tofile 'replace)
17505 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17506 (if (file-exists-p (concat texfilebase e))
17507 (delete-file (concat texfilebase e))))
17508 pngfile))))
17510 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17511 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17512 "This calls convert, which is included into imagemagick."
17513 (require 'org-latex)
17514 (let* ((tmpdir (if (featurep 'xemacs)
17515 (temp-directory)
17516 temporary-file-directory))
17517 (texfilebase (make-temp-name
17518 (expand-file-name "orgtex" tmpdir)))
17519 (texfile (concat texfilebase ".tex"))
17520 (pdffile (concat texfilebase ".pdf"))
17521 (pngfile (concat texfilebase ".png"))
17522 (fnh (if (featurep 'xemacs)
17523 (font-height (face-font 'default))
17524 (face-attribute 'default :height nil)))
17525 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17526 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17527 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17528 "black"))
17529 (bg (or (plist-get options (if buffer :background :html-background))
17530 "white")))
17531 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17532 (setq fg (org-latex-color-format fg)))
17533 (if (eq bg 'default) (setq bg (org-latex-color :background))
17534 (setq bg (org-latex-color-format
17535 (if (string= bg "Transparent")(setq bg "white")))))
17536 (with-temp-file texfile
17537 (insert (org-splice-latex-header
17538 org-format-latex-header
17539 org-export-latex-default-packages-alist
17540 org-export-latex-packages-alist t
17541 org-format-latex-header-extra))
17542 (insert "\n\\begin{document}\n"
17543 "\\definecolor{fg}{rgb}{" fg "}\n"
17544 "\\definecolor{bg}{rgb}{" bg "}\n"
17545 "\n\\pagecolor{bg}\n"
17546 "\n{\\color{fg}\n"
17547 string
17548 "\n}\n"
17549 "\n\\end{document}\n" )
17550 (require 'org-latex)
17551 (org-export-latex-fix-inputenc))
17552 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17553 (condition-case nil
17554 (progn
17555 (cd tmpdir)
17556 (setq cmds org-latex-to-pdf-process)
17557 (while cmds
17558 (setq latex-frags-cmds (pop cmds))
17559 (if (listp latex-frags-cmds)
17560 (setq cmds nil)
17561 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17562 (while latex-frags-cmds
17563 (setq cmd (pop latex-frags-cmds))
17564 (while (string-match "%b" cmd)
17565 (setq cmd (replace-match
17566 (save-match-data
17567 (shell-quote-argument texfile))
17568 t t cmd)))
17569 (while (string-match "%f" cmd)
17570 (setq cmd (replace-match
17571 (save-match-data
17572 (shell-quote-argument (file-name-nondirectory texfile)))
17573 t t cmd)))
17574 (while (string-match "%o" cmd)
17575 (setq cmd (replace-match
17576 (save-match-data
17577 (shell-quote-argument (file-name-directory texfile)))
17578 t t cmd)))
17579 (setq cmd (split-string cmd))
17580 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17581 (error nil))
17582 (cd dir))
17583 (if (not (file-exists-p pdffile))
17584 (progn (message "Failed to create pdf file from %s" texfile) nil)
17585 (condition-case nil
17586 (if (featurep 'xemacs)
17587 (call-process "convert" nil nil nil
17588 "-density" "96"
17589 "-trim"
17590 "-antialias"
17591 pdffile
17592 "-quality" "100"
17593 ;; "-sharpen" "0x1.0"
17594 pngfile)
17595 (call-process "convert" nil nil nil
17596 "-density" dpi
17597 "-trim"
17598 "-antialias"
17599 pdffile
17600 "-quality" "100"
17601 ; "-sharpen" "0x1.0"
17602 pngfile))
17603 (error nil))
17604 (if (not (file-exists-p pngfile))
17605 (if org-format-latex-signal-error
17606 (error "Failed to create png file from %s" texfile)
17607 (message "Failed to create png file from %s" texfile)
17608 nil)
17609 ;; Use the requested file name and clean up
17610 (copy-file pngfile tofile 'replace)
17611 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17612 (if (file-exists-p (concat texfilebase e))
17613 (delete-file (concat texfilebase e))))
17614 pngfile))))
17616 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17617 "Fill a LaTeX header template TPL.
17618 In the template, the following place holders will be recognized:
17620 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17621 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17622 [PACKAGES] \\usepackage statements for PKG
17623 [NO-PACKAGES] do not include PKG
17624 [EXTRA] the string EXTRA
17625 [NO-EXTRA] do not include EXTRA
17627 For backward compatibility, if both the positive and the negative place
17628 holder is missing, the positive one (without the \"NO-\") will be
17629 assumed to be present at the end of the template.
17630 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17631 EXTRA is a string.
17632 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17633 (let (rpl (end ""))
17634 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17635 (setq rpl (if (or (match-end 1) (not def-pkg))
17636 "" (org-latex-packages-to-string def-pkg snippets-p t))
17637 tpl (replace-match rpl t t tpl))
17638 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17640 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17641 (setq rpl (if (or (match-end 1) (not pkg))
17642 "" (org-latex-packages-to-string pkg snippets-p t))
17643 tpl (replace-match rpl t t tpl))
17644 (if pkg (setq end
17645 (concat end "\n"
17646 (org-latex-packages-to-string pkg snippets-p)))))
17648 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17649 (setq rpl (if (or (match-end 1) (not extra))
17650 "" (concat extra "\n"))
17651 tpl (replace-match rpl t t tpl))
17652 (if (and extra (string-match "\\S-" extra))
17653 (setq end (concat end "\n" extra))))
17655 (if (string-match "\\S-" end)
17656 (concat tpl "\n" end)
17657 tpl)))
17659 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17660 "Turn an alist of packages into a string with the \\usepackage macros."
17661 (setq pkg (mapconcat (lambda(p)
17662 (cond
17663 ((stringp p) p)
17664 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17665 (format "%% Package %s omitted" (cadr p)))
17666 ((equal "" (car p))
17667 (format "\\usepackage{%s}" (cadr p)))
17669 (format "\\usepackage[%s]{%s}"
17670 (car p) (cadr p)))))
17672 "\n"))
17673 (if newline (concat pkg "\n") pkg))
17675 (defun org-dvipng-color (attr)
17676 "Return a RGB color specification for dvipng."
17677 (apply 'format "rgb %s %s %s"
17678 (mapcar 'org-normalize-color
17679 (if (featurep 'xemacs)
17680 (color-rgb-components
17681 (face-property 'default
17682 (cond ((eq attr :foreground) 'foreground)
17683 ((eq attr :background) 'background))))
17684 (color-values (face-attribute 'default attr nil))))))
17686 (defun org-latex-color (attr)
17687 "Return a RGB color for the LaTeX color package."
17688 (apply 'format "%s,%s,%s"
17689 (mapcar 'org-normalize-color
17690 (if (featurep 'xemacs)
17691 (color-rgb-components
17692 (face-property 'default
17693 (cond ((eq attr :foreground) 'foreground)
17694 ((eq attr :background) 'background))))
17695 (color-values (face-attribute 'default attr nil))))))
17697 (defun org-latex-color-format (color-name)
17698 "Convert COLOR-NAME to a RGB color value."
17699 (apply 'format "%s,%s,%s"
17700 (mapcar 'org-normalize-color
17701 (color-values color-name))))
17703 (defun org-normalize-color (value)
17704 "Return string to be used as color value for an RGB component."
17705 (format "%g" (/ value 65535.0)))
17707 ;; Image display
17710 (defvar org-inline-image-overlays nil)
17711 (make-variable-buffer-local 'org-inline-image-overlays)
17713 (defun org-toggle-inline-images (&optional include-linked)
17714 "Toggle the display of inline images.
17715 INCLUDE-LINKED is passed to `org-display-inline-images'."
17716 (interactive "P")
17717 (if org-inline-image-overlays
17718 (progn
17719 (org-remove-inline-images)
17720 (message "Inline image display turned off"))
17721 (org-display-inline-images include-linked)
17722 (if org-inline-image-overlays
17723 (message "%d images displayed inline"
17724 (length org-inline-image-overlays))
17725 (message "No images to display inline"))))
17727 (defun org-redisplay-inline-images ()
17728 "Refresh the display of inline images."
17729 (interactive)
17730 (if (not org-inline-image-overlays)
17731 (org-toggle-inline-images)
17732 (org-toggle-inline-images)
17733 (org-toggle-inline-images)))
17735 (defun org-display-inline-images (&optional include-linked refresh beg end)
17736 "Display inline images.
17737 Normally only links without a description part are inlined, because this
17738 is how it will work for export. When INCLUDE-LINKED is set, also links
17739 with a description part will be inlined. This can be nice for a quick
17740 look at those images, but it does not reflect what exported files will look
17741 like.
17742 When REFRESH is set, refresh existing images between BEG and END.
17743 This will create new image displays only if necessary.
17744 BEG and END default to the buffer boundaries."
17745 (interactive "P")
17746 (unless refresh
17747 (org-remove-inline-images)
17748 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17749 (save-excursion
17750 (save-restriction
17751 (widen)
17752 (setq beg (or beg (point-min)) end (or end (point-max)))
17753 (goto-char beg)
17754 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17755 (substring (org-image-file-name-regexp) 0 -2)
17756 "\\)\\]" (if include-linked "" "\\]")))
17757 old file ov img)
17758 (while (re-search-forward re end t)
17759 (setq old (get-char-property-and-overlay (match-beginning 1)
17760 'org-image-overlay))
17761 (setq file (expand-file-name
17762 (concat (or (match-string 3) "") (match-string 4))))
17763 (when (file-exists-p file)
17764 (if (and (car-safe old) refresh)
17765 (image-refresh (overlay-get (cdr old) 'display))
17766 (setq img (save-match-data (create-image file)))
17767 (when img
17768 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17769 (overlay-put ov 'display img)
17770 (overlay-put ov 'face 'default)
17771 (overlay-put ov 'org-image-overlay t)
17772 (overlay-put ov 'modification-hooks
17773 (list 'org-display-inline-remove-overlay))
17774 (push ov org-inline-image-overlays)))))))))
17776 (define-obsolete-function-alias
17777 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17779 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17780 "Remove inline-display overlay if a corresponding region is modified."
17781 (let ((inhibit-modification-hooks t))
17782 (when (and ov after)
17783 (delete ov org-inline-image-overlays)
17784 (delete-overlay ov))))
17786 (defun org-remove-inline-images ()
17787 "Remove inline display of images."
17788 (interactive)
17789 (mapc 'delete-overlay org-inline-image-overlays)
17790 (setq org-inline-image-overlays nil))
17792 ;;;; Key bindings
17794 ;; Outline functions from `outline-mode-prefix-map'
17795 ;; that can be remapped in Org:
17796 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17797 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17798 (define-key org-mode-map [remap outline-forward-same-level]
17799 'org-forward-heading-same-level)
17800 (define-key org-mode-map [remap outline-backward-same-level]
17801 'org-backward-heading-same-level)
17802 (define-key org-mode-map [remap show-branches]
17803 'org-kill-note-or-show-branches)
17804 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17805 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17806 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17808 ;; Outline functions from `outline-mode-prefix-map' that can not
17809 ;; be remapped in Org:
17811 ;; - the column "key binding" shows whether the Outline function is still
17812 ;; available in Org mode on the same key that it has been bound to in
17813 ;; Outline mode:
17814 ;; - "overridden": key used for a different functionality in Org mode
17815 ;; - else: key still bound to the same Outline function in Org mode
17817 ;; | Outline function | key binding | Org replacement |
17818 ;; |------------------------------------+-------------+-----------------------|
17819 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17820 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17821 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17822 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17823 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17824 ;; | `show-entry' | overridden | no replacement |
17825 ;; | `show-children' | `C-c C-i' | visibility cycling |
17826 ;; | `show-branches' | `C-c C-k' | still same function |
17827 ;; | `show-subtree' | overridden | visibility cycling |
17828 ;; | `show-all' | overridden | no replacement |
17829 ;; | `hide-subtree' | overridden | visibility cycling |
17830 ;; | `hide-body' | overridden | no replacement |
17831 ;; | `hide-entry' | overridden | visibility cycling |
17832 ;; | `hide-leaves' | overridden | no replacement |
17833 ;; | `hide-sublevels' | overridden | no replacement |
17834 ;; | `hide-other' | overridden | no replacement |
17836 ;; Make `C-c C-x' a prefix key
17837 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17839 ;; TAB key with modifiers
17840 (org-defkey org-mode-map "\C-i" 'org-cycle)
17841 (org-defkey org-mode-map [(tab)] 'org-cycle)
17842 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17843 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17844 ;; The following line is necessary under Suse GNU/Linux
17845 (unless (featurep 'xemacs)
17846 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17847 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17848 (define-key org-mode-map [backtab] 'org-shifttab)
17850 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17851 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17852 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17854 ;; Cursor keys with modifiers
17855 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17856 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17857 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17858 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17860 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17861 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17862 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17863 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17865 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17866 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17867 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17868 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17870 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17871 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17872 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17873 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17875 ;; Babel keys
17876 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17877 (mapc (lambda (pair)
17878 (define-key org-babel-map (car pair) (cdr pair)))
17879 org-babel-key-bindings)
17881 ;;; Extra keys for tty access.
17882 ;; We only set them when really needed because otherwise the
17883 ;; menus don't show the simple keys
17885 (when (or org-use-extra-keys
17886 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17887 (not window-system))
17888 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17889 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17890 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17891 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17892 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17893 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17894 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17895 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17896 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17897 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17898 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17899 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17900 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17901 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17902 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17903 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17904 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17905 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17906 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17907 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17908 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17909 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17910 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17911 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17912 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17913 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17914 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17915 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17917 ;; All the other keys
17919 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17920 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17921 (if (boundp 'narrow-map)
17922 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17923 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17924 (if (boundp 'narrow-map)
17925 (org-defkey narrow-map "b" 'org-narrow-to-block)
17926 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17927 (if (boundp 'narrow-map)
17928 (org-defkey narrow-map "e" 'org-narrow-to-element)
17929 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
17930 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
17931 (org-defkey org-mode-map "\M-}" 'org-forward-element)
17932 (org-defkey org-mode-map "\M-{" 'org-backward-element)
17933 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
17934 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
17935 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
17936 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
17937 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17938 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17939 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17940 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
17941 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17942 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17943 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17944 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17945 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17946 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17947 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17948 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17949 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17950 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17951 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17952 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17953 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17954 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17955 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17956 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17957 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17958 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17959 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17960 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17961 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17962 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
17963 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17964 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17965 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17966 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17967 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17968 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17969 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17970 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17971 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17972 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17973 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17974 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17975 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17976 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17977 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17978 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17979 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17980 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17981 (org-defkey org-mode-map "\C-c^" 'org-sort)
17982 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17983 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17984 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17985 (org-defkey org-mode-map "\C-m" 'org-return)
17986 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17987 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17988 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17989 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17990 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17991 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17992 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17993 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17994 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17995 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17996 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17997 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17998 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17999 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18000 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18001 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18002 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18003 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18004 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18005 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18006 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18007 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18008 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18010 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18011 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18012 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18014 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18015 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18016 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18017 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18018 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18019 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18020 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18021 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18022 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18023 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18024 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18025 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18026 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18027 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18028 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18029 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18030 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18031 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18032 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18033 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18034 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18035 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18037 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18038 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18039 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18040 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18041 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18043 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18045 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18047 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18048 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18050 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18053 (when (featurep 'xemacs)
18054 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18057 (defconst org-speed-commands-default
18059 ("Outline Navigation")
18060 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18061 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18062 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18063 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18064 ("u" . (org-speed-move-safe 'outline-up-heading))
18065 ("j" . org-goto)
18066 ("g" . (org-refile t))
18067 ("Outline Visibility")
18068 ("c" . org-cycle)
18069 ("C" . org-shifttab)
18070 (" " . org-display-outline-path)
18071 (":" . org-columns)
18072 ("Outline Structure Editing")
18073 ("U" . org-shiftmetaup)
18074 ("D" . org-shiftmetadown)
18075 ("r" . org-metaright)
18076 ("l" . org-metaleft)
18077 ("R" . org-shiftmetaright)
18078 ("L" . org-shiftmetaleft)
18079 ("i" . (progn (forward-char 1) (call-interactively
18080 'org-insert-heading-respect-content)))
18081 ("^" . org-sort)
18082 ("w" . org-refile)
18083 ("a" . org-archive-subtree-default-with-confirmation)
18084 ("." . org-mark-subtree)
18085 ("#" . org-toggle-comment)
18086 ("Clock Commands")
18087 ("I" . org-clock-in)
18088 ("O" . org-clock-out)
18089 ("Meta Data Editing")
18090 ("t" . org-todo)
18091 ("," . (org-priority))
18092 ("0" . (org-priority ?\ ))
18093 ("1" . (org-priority ?A))
18094 ("2" . (org-priority ?B))
18095 ("3" . (org-priority ?C))
18096 (";" . org-set-tags-command)
18097 ("e" . org-set-effort)
18098 ("E" . org-inc-effort)
18099 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18100 (org-entry-put (point) "APPT_WARNTIME" m)))
18101 ("Agenda Views etc")
18102 ("v" . org-agenda)
18103 ("/" . org-sparse-tree)
18104 ("Misc")
18105 ("o" . org-open-at-point)
18106 ("?" . org-speed-command-help)
18107 ("<" . (org-agenda-set-restriction-lock 'subtree))
18108 (">" . (org-agenda-remove-restriction-lock))
18110 "The default speed commands.")
18112 (defun org-print-speed-command (e)
18113 (if (> (length (car e)) 1)
18114 (progn
18115 (princ "\n")
18116 (princ (car e))
18117 (princ "\n")
18118 (princ (make-string (length (car e)) ?-))
18119 (princ "\n"))
18120 (princ (car e))
18121 (princ " ")
18122 (if (symbolp (cdr e))
18123 (princ (symbol-name (cdr e)))
18124 (prin1 (cdr e)))
18125 (princ "\n")))
18127 (defun org-speed-command-help ()
18128 "Show the available speed commands."
18129 (interactive)
18130 (if (not org-use-speed-commands)
18131 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18132 (with-output-to-temp-buffer "*Help*"
18133 (princ "User-defined Speed commands\n===========================\n")
18134 (mapc 'org-print-speed-command org-speed-commands-user)
18135 (princ "\n")
18136 (princ "Built-in Speed commands\n=======================\n")
18137 (mapc 'org-print-speed-command org-speed-commands-default))
18138 (with-current-buffer "*Help*"
18139 (setq truncate-lines t))))
18141 (defun org-speed-move-safe (cmd)
18142 "Execute CMD, but make sure that the cursor always ends up in a headline.
18143 If not, return to the original position and throw an error."
18144 (interactive)
18145 (let ((pos (point)))
18146 (call-interactively cmd)
18147 (unless (and (bolp) (org-at-heading-p))
18148 (goto-char pos)
18149 (error "Boundary reached while executing %s" cmd))))
18151 (defvar org-self-insert-command-undo-counter 0)
18153 (defvar org-table-auto-blank-field) ; defined in org-table.el
18154 (defvar org-speed-command nil)
18156 (define-obsolete-function-alias
18157 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18159 (defun org-speed-command-activate (keys)
18160 "Hook for activating single-letter speed commands.
18161 `org-speed-commands-default' specifies a minimal command set.
18162 Use `org-speed-commands-user' for further customization."
18163 (when (or (and (bolp) (looking-at org-outline-regexp))
18164 (and (functionp org-use-speed-commands)
18165 (funcall org-use-speed-commands)))
18166 (cdr (assoc keys (append org-speed-commands-user
18167 org-speed-commands-default)))))
18169 (define-obsolete-function-alias
18170 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18172 (defun org-babel-speed-command-activate (keys)
18173 "Hook for activating single-letter code block commands."
18174 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18175 (cdr (assoc keys org-babel-key-bindings))))
18177 (defcustom org-speed-command-hook
18178 '(org-speed-command-default-hook org-babel-speed-command-hook)
18179 "Hook for activating speed commands at strategic locations.
18180 Hook functions are called in sequence until a valid handler is
18181 found.
18183 Each hook takes a single argument, a user-pressed command key
18184 which is also a `self-insert-command' from the global map.
18186 Within the hook, examine the cursor position and the command key
18187 and return nil or a valid handler as appropriate. Handler could
18188 be one of an interactive command, a function, or a form.
18190 Set `org-use-speed-commands' to non-nil value to enable this
18191 hook. The default setting is `org-speed-command-activate'."
18192 :group 'org-structure
18193 :version "24.1"
18194 :type 'hook)
18196 (defun org-self-insert-command (N)
18197 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18198 If the cursor is in a table looking at whitespace, the whitespace is
18199 overwritten, and the table is not marked as requiring realignment."
18200 (interactive "p")
18201 (org-check-before-invisible-edit 'insert)
18202 (cond
18203 ((and org-use-speed-commands
18204 (setq org-speed-command
18205 (run-hook-with-args-until-success
18206 'org-speed-command-hook (this-command-keys))))
18207 (cond
18208 ((commandp org-speed-command)
18209 (setq this-command org-speed-command)
18210 (call-interactively org-speed-command))
18211 ((functionp org-speed-command)
18212 (funcall org-speed-command))
18213 ((and org-speed-command (listp org-speed-command))
18214 (eval org-speed-command))
18215 (t (let (org-use-speed-commands)
18216 (call-interactively 'org-self-insert-command)))))
18217 ((and
18218 (org-table-p)
18219 (progn
18220 ;; check if we blank the field, and if that triggers align
18221 (and (featurep 'org-table) org-table-auto-blank-field
18222 (member last-command
18223 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18224 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18225 ;; got extra space, this field does not determine column width
18226 (let (org-table-may-need-update) (org-table-blank-field))
18227 ;; no extra space, this field may determine column width
18228 (org-table-blank-field)))
18230 (eq N 1)
18231 (looking-at "[^|\n]* |"))
18232 (let (org-table-may-need-update)
18233 (goto-char (1- (match-end 0)))
18234 (backward-delete-char 1)
18235 (goto-char (match-beginning 0))
18236 (self-insert-command N)))
18238 (setq org-table-may-need-update t)
18239 (self-insert-command N)
18240 (org-fix-tags-on-the-fly)
18241 (if org-self-insert-cluster-for-undo
18242 (if (not (eq last-command 'org-self-insert-command))
18243 (setq org-self-insert-command-undo-counter 1)
18244 (if (>= org-self-insert-command-undo-counter 20)
18245 (setq org-self-insert-command-undo-counter 1)
18246 (and (> org-self-insert-command-undo-counter 0)
18247 buffer-undo-list (listp buffer-undo-list)
18248 (not (cadr buffer-undo-list)) ; remove nil entry
18249 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18250 (setq org-self-insert-command-undo-counter
18251 (1+ org-self-insert-command-undo-counter))))))))
18253 (defun org-check-before-invisible-edit (kind)
18254 "Check is editing if kind KIND would be dangerous with invisible text around.
18255 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18256 ;; First, try to get out of here as quickly as possible, to reduce overhead
18257 (if (and org-catch-invisible-edits
18258 (or (not (boundp 'visible-mode)) (not visible-mode))
18259 (or (get-char-property (point) 'invisible)
18260 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18261 ;; OK, we need to take a closer look
18262 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18263 (invisible-before-point (if (bobp) nil (get-char-property
18264 (1- (point)) 'invisible)))
18265 (border-and-ok-direction
18267 ;; Check if we are acting predictably before invisible text
18268 (and invisible-at-point (not invisible-before-point)
18269 (memq kind '(insert delete-backward)))
18270 ;; Check if we are acting predictably after invisible text
18271 ;; This works not well, and I have turned it off. It seems
18272 ;; better to always show and stop after invisible text.
18273 ;; (and (not invisible-at-point) invisible-before-point
18274 ;; (memq kind '(insert delete)))
18276 (when (or (memq invisible-at-point '(outline org-hide-block t))
18277 (memq invisible-before-point '(outline org-hide-block t)))
18278 (if (eq org-catch-invisible-edits 'error)
18279 (error "Editing in invisible areas is prohibited - make visible first"))
18280 (if (and org-custom-properties-overlays
18281 (y-or-n-p "Display invisible properties in this buffer? "))
18282 (org-toggle-custom-properties-visibility)
18283 ;; Make the area visible
18284 (save-excursion
18285 (if invisible-before-point
18286 (goto-char (previous-single-char-property-change
18287 (point) 'invisible)))
18288 (org-cycle))
18289 (cond
18290 ((eq org-catch-invisible-edits 'show)
18291 ;; That's it, we do the edit after showing
18292 (message
18293 "Unfolding invisible region around point before editing")
18294 (sit-for 1))
18295 ((and (eq org-catch-invisible-edits 'smart)
18296 border-and-ok-direction)
18297 (message "Unfolding invisible region around point before editing"))
18299 ;; Don't do the edit, make the user repeat it in full visibility
18300 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18302 (defun org-fix-tags-on-the-fly ()
18303 (when (and (equal (char-after (point-at-bol)) ?*)
18304 (org-at-heading-p))
18305 (org-align-tags-here org-tags-column)))
18307 (defun org-delete-backward-char (N)
18308 "Like `delete-backward-char', insert whitespace at field end in tables.
18309 When deleting backwards, in tables this function will insert whitespace in
18310 front of the next \"|\" separator, to keep the table aligned. The table will
18311 still be marked for re-alignment if the field did fill the entire column,
18312 because, in this case the deletion might narrow the column."
18313 (interactive "p")
18314 (save-match-data
18315 (org-check-before-invisible-edit 'delete-backward)
18316 (if (and (org-table-p)
18317 (eq N 1)
18318 (string-match "|" (buffer-substring (point-at-bol) (point)))
18319 (looking-at ".*?|"))
18320 (let ((pos (point))
18321 (noalign (looking-at "[^|\n\r]* |"))
18322 (c org-table-may-need-update))
18323 (backward-delete-char N)
18324 (if (not overwrite-mode)
18325 (progn
18326 (skip-chars-forward "^|")
18327 (insert " ")
18328 (goto-char (1- pos))))
18329 ;; noalign: if there were two spaces at the end, this field
18330 ;; does not determine the width of the column.
18331 (if noalign (setq org-table-may-need-update c)))
18332 (backward-delete-char N)
18333 (org-fix-tags-on-the-fly))))
18335 (defun org-delete-char (N)
18336 "Like `delete-char', but insert whitespace at field end in tables.
18337 When deleting characters, in tables this function will insert whitespace in
18338 front of the next \"|\" separator, to keep the table aligned. The table will
18339 still be marked for re-alignment if the field did fill the entire column,
18340 because, in this case the deletion might narrow the column."
18341 (interactive "p")
18342 (save-match-data
18343 (org-check-before-invisible-edit 'delete)
18344 (if (and (org-table-p)
18345 (not (bolp))
18346 (not (= (char-after) ?|))
18347 (eq N 1))
18348 (if (looking-at ".*?|")
18349 (let ((pos (point))
18350 (noalign (looking-at "[^|\n\r]* |"))
18351 (c org-table-may-need-update))
18352 (replace-match (concat
18353 (substring (match-string 0) 1 -1)
18354 " |"))
18355 (goto-char pos)
18356 ;; noalign: if there were two spaces at the end, this field
18357 ;; does not determine the width of the column.
18358 (if noalign (setq org-table-may-need-update c)))
18359 (delete-char N))
18360 (delete-char N)
18361 (org-fix-tags-on-the-fly))))
18363 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18364 (put 'org-self-insert-command 'delete-selection t)
18365 (put 'orgtbl-self-insert-command 'delete-selection t)
18366 (put 'org-delete-char 'delete-selection 'supersede)
18367 (put 'org-delete-backward-char 'delete-selection 'supersede)
18368 (put 'org-yank 'delete-selection 'yank)
18370 ;; Make `flyspell-mode' delay after some commands
18371 (put 'org-self-insert-command 'flyspell-delayed t)
18372 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18373 (put 'org-delete-char 'flyspell-delayed t)
18374 (put 'org-delete-backward-char 'flyspell-delayed t)
18376 ;; Make pabbrev-mode expand after org-mode commands
18377 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18378 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18380 ;; How to do this: Measure non-white length of current string
18381 ;; If equal to column width, we should realign.
18383 (defun org-remap (map &rest commands)
18384 "In MAP, remap the functions given in COMMANDS.
18385 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18386 (let (new old)
18387 (while commands
18388 (setq old (pop commands) new (pop commands))
18389 (if (fboundp 'command-remapping)
18390 (org-defkey map (vector 'remap old) new)
18391 (substitute-key-definition old new map global-map)))))
18393 (when (eq org-enable-table-editor 'optimized)
18394 ;; If the user wants maximum table support, we need to hijack
18395 ;; some standard editing functions
18396 (org-remap org-mode-map
18397 'self-insert-command 'org-self-insert-command
18398 'delete-char 'org-delete-char
18399 'delete-backward-char 'org-delete-backward-char)
18400 (org-defkey org-mode-map "|" 'org-force-self-insert))
18402 (defvar org-ctrl-c-ctrl-c-hook nil
18403 "Hook for functions attaching themselves to `C-c C-c'.
18405 This can be used to add additional functionality to the C-c C-c
18406 key which executes context-dependent commands. This hook is run
18407 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18408 run after the last test.
18410 Each function will be called with no arguments. The function
18411 must check if the context is appropriate for it to act. If yes,
18412 it should do its thing and then return a non-nil value. If the
18413 context is wrong, just do nothing and return nil.")
18415 (defvar org-ctrl-c-ctrl-c-final-hook nil
18416 "Hook for functions attaching themselves to `C-c C-c'.
18418 This can be used to add additional functionality to the C-c C-c
18419 key which executes context-dependent commands. This hook is run
18420 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18421 before the first test.
18423 Each function will be called with no arguments. The function
18424 must check if the context is appropriate for it to act. If yes,
18425 it should do its thing and then return a non-nil value. If the
18426 context is wrong, just do nothing and return nil.")
18428 (defvar org-tab-first-hook nil
18429 "Hook for functions to attach themselves to TAB.
18430 See `org-ctrl-c-ctrl-c-hook' for more information.
18431 This hook runs as the first action when TAB is pressed, even before
18432 `org-cycle' messes around with the `outline-regexp' to cater for
18433 inline tasks and plain list item folding.
18434 If any function in this hook returns t, any other actions that
18435 would have been caused by TAB (such as table field motion or visibility
18436 cycling) will not occur.")
18438 (defvar org-tab-after-check-for-table-hook nil
18439 "Hook for functions to attach themselves to TAB.
18440 See `org-ctrl-c-ctrl-c-hook' for more information.
18441 This hook runs after it has been established that the cursor is not in a
18442 table, but before checking if the cursor is in a headline or if global cycling
18443 should be done.
18444 If any function in this hook returns t, not other actions like visibility
18445 cycling will be done.")
18447 (defvar org-tab-after-check-for-cycling-hook nil
18448 "Hook for functions to attach themselves to TAB.
18449 See `org-ctrl-c-ctrl-c-hook' for more information.
18450 This hook runs after it has been established that not table field motion and
18451 not visibility should be done because of current context. This is probably
18452 the place where a package like yasnippets can hook in.")
18454 (defvar org-tab-before-tab-emulation-hook nil
18455 "Hook for functions to attach themselves to TAB.
18456 See `org-ctrl-c-ctrl-c-hook' for more information.
18457 This hook runs after every other options for TAB have been exhausted, but
18458 before indentation and \t insertion takes place.")
18460 (defvar org-metaleft-hook nil
18461 "Hook for functions attaching themselves to `M-left'.
18462 See `org-ctrl-c-ctrl-c-hook' for more information.")
18463 (defvar org-metaright-hook nil
18464 "Hook for functions attaching themselves to `M-right'.
18465 See `org-ctrl-c-ctrl-c-hook' for more information.")
18466 (defvar org-metaup-hook nil
18467 "Hook for functions attaching themselves to `M-up'.
18468 See `org-ctrl-c-ctrl-c-hook' for more information.")
18469 (defvar org-metadown-hook nil
18470 "Hook for functions attaching themselves to `M-down'.
18471 See `org-ctrl-c-ctrl-c-hook' for more information.")
18472 (defvar org-shiftmetaleft-hook nil
18473 "Hook for functions attaching themselves to `M-S-left'.
18474 See `org-ctrl-c-ctrl-c-hook' for more information.")
18475 (defvar org-shiftmetaright-hook nil
18476 "Hook for functions attaching themselves to `M-S-right'.
18477 See `org-ctrl-c-ctrl-c-hook' for more information.")
18478 (defvar org-shiftmetaup-hook nil
18479 "Hook for functions attaching themselves to `M-S-up'.
18480 See `org-ctrl-c-ctrl-c-hook' for more information.")
18481 (defvar org-shiftmetadown-hook nil
18482 "Hook for functions attaching themselves to `M-S-down'.
18483 See `org-ctrl-c-ctrl-c-hook' for more information.")
18484 (defvar org-metareturn-hook nil
18485 "Hook for functions attaching themselves to `M-RET'.
18486 See `org-ctrl-c-ctrl-c-hook' for more information.")
18487 (defvar org-shiftup-hook nil
18488 "Hook for functions attaching themselves to `S-up'.
18489 See `org-ctrl-c-ctrl-c-hook' for more information.")
18490 (defvar org-shiftup-final-hook nil
18491 "Hook for functions attaching themselves to `S-up'.
18492 This one runs after all other options except shift-select have been excluded.
18493 See `org-ctrl-c-ctrl-c-hook' for more information.")
18494 (defvar org-shiftdown-hook nil
18495 "Hook for functions attaching themselves to `S-down'.
18496 See `org-ctrl-c-ctrl-c-hook' for more information.")
18497 (defvar org-shiftdown-final-hook nil
18498 "Hook for functions attaching themselves to `S-down'.
18499 This one runs after all other options except shift-select have been excluded.
18500 See `org-ctrl-c-ctrl-c-hook' for more information.")
18501 (defvar org-shiftleft-hook nil
18502 "Hook for functions attaching themselves to `S-left'.
18503 See `org-ctrl-c-ctrl-c-hook' for more information.")
18504 (defvar org-shiftleft-final-hook nil
18505 "Hook for functions attaching themselves to `S-left'.
18506 This one runs after all other options except shift-select have been excluded.
18507 See `org-ctrl-c-ctrl-c-hook' for more information.")
18508 (defvar org-shiftright-hook nil
18509 "Hook for functions attaching themselves to `S-right'.
18510 See `org-ctrl-c-ctrl-c-hook' for more information.")
18511 (defvar org-shiftright-final-hook nil
18512 "Hook for functions attaching themselves to `S-right'.
18513 This one runs after all other options except shift-select have been excluded.
18514 See `org-ctrl-c-ctrl-c-hook' for more information.")
18516 (defun org-modifier-cursor-error ()
18517 "Throw an error, a modified cursor command was applied in wrong context."
18518 (error "This command is active in special context like tables, headlines or items"))
18520 (defun org-shiftselect-error ()
18521 "Throw an error because Shift-Cursor command was applied in wrong context."
18522 (if (and (boundp 'shift-select-mode) shift-select-mode)
18523 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18524 (error "This command works only in special context like headlines or timestamps")))
18526 (defun org-call-for-shift-select (cmd)
18527 (let ((this-command-keys-shift-translated t))
18528 (call-interactively cmd)))
18530 (defun org-shifttab (&optional arg)
18531 "Global visibility cycling or move to previous table field.
18532 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18533 on context.
18534 See the individual commands for more information."
18535 (interactive "P")
18536 (cond
18537 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18538 ((integerp arg)
18539 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18540 (message "Content view to level: %d" arg)
18541 (org-content (prefix-numeric-value arg2))
18542 (setq org-cycle-global-status 'overview)))
18543 (t (call-interactively 'org-global-cycle))))
18545 (defun org-shiftmetaleft ()
18546 "Promote subtree or delete table column.
18547 Calls `org-promote-subtree', `org-outdent-item-tree', or
18548 `org-table-delete-column', depending on context. See the
18549 individual commands for more information."
18550 (interactive)
18551 (cond
18552 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18553 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18554 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18555 ((if (not (org-region-active-p)) (org-at-item-p)
18556 (save-excursion (goto-char (region-beginning))
18557 (org-at-item-p)))
18558 (call-interactively 'org-outdent-item-tree))
18559 (t (org-modifier-cursor-error))))
18561 (defun org-shiftmetaright ()
18562 "Demote subtree or insert table column.
18563 Calls `org-demote-subtree', `org-indent-item-tree', or
18564 `org-table-insert-column', depending on context. See the
18565 individual commands for more information."
18566 (interactive)
18567 (cond
18568 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18569 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18570 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18571 ((if (not (org-region-active-p)) (org-at-item-p)
18572 (save-excursion (goto-char (region-beginning))
18573 (org-at-item-p)))
18574 (call-interactively 'org-indent-item-tree))
18575 (t (org-modifier-cursor-error))))
18577 (defun org-shiftmetaup (&optional arg)
18578 "Move subtree up or kill table row.
18579 Calls `org-move-subtree-up' or `org-table-kill-row' or
18580 `org-move-item-up' or `org-timestamp-up', depending on context.
18581 See the individual commands for more information."
18582 (interactive "P")
18583 (cond
18584 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18585 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18586 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18587 ((org-at-item-p) (call-interactively 'org-move-item-up))
18588 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18589 (call-interactively 'org-timestamp-up)))
18590 (t (org-modifier-cursor-error))))
18592 (defun org-shiftmetadown (&optional arg)
18593 "Move subtree down or insert table row.
18594 Calls `org-move-subtree-down' or `org-table-insert-row' or
18595 `org-move-item-down' or `org-timestamp-up', depending on context.
18596 See the individual commands for more information."
18597 (interactive "P")
18598 (cond
18599 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18600 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18601 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18602 ((org-at-item-p) (call-interactively 'org-move-item-down))
18603 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18604 (call-interactively 'org-timestamp-down)))
18605 (t (org-modifier-cursor-error))))
18607 (defsubst org-hidden-tree-error ()
18608 (error
18609 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18611 (defun org-metaleft (&optional arg)
18612 "Promote heading or move table column to left.
18613 Calls `org-do-promote' or `org-table-move-column', depending on context.
18614 With no specific context, calls the Emacs default `backward-word'.
18615 See the individual commands for more information."
18616 (interactive "P")
18617 (cond
18618 ((run-hook-with-args-until-success 'org-metaleft-hook))
18619 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18620 ((org-with-limited-levels
18621 (or (org-at-heading-p)
18622 (and (org-region-active-p)
18623 (save-excursion
18624 (goto-char (region-beginning))
18625 (org-at-heading-p)))))
18626 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18627 (call-interactively 'org-do-promote))
18628 ;; At an inline task.
18629 ((org-at-heading-p)
18630 (call-interactively 'org-inlinetask-promote))
18631 ((or (org-at-item-p)
18632 (and (org-region-active-p)
18633 (save-excursion
18634 (goto-char (region-beginning))
18635 (org-at-item-p))))
18636 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18637 (call-interactively 'org-outdent-item))
18638 (t (call-interactively 'backward-word))))
18640 (defun org-metaright (&optional arg)
18641 "Demote a subtree, a list item or move table column to right.
18642 In front of a drawer or a block keyword, indent it correctly.
18643 With no specific context, calls the Emacs default `forward-word'.
18644 See the individual commands for more information."
18645 (interactive "P")
18646 (cond
18647 ((run-hook-with-args-until-success 'org-metaright-hook))
18648 ((org-at-table-p) (call-interactively 'org-table-move-column))
18649 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18650 ((org-at-block-p) (call-interactively 'org-indent-block))
18651 ((org-with-limited-levels
18652 (or (org-at-heading-p)
18653 (and (org-region-active-p)
18654 (save-excursion
18655 (goto-char (region-beginning))
18656 (org-at-heading-p)))))
18657 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18658 (call-interactively 'org-do-demote))
18659 ;; At an inline task.
18660 ((org-at-heading-p)
18661 (call-interactively 'org-inlinetask-demote))
18662 ((or (org-at-item-p)
18663 (and (org-region-active-p)
18664 (save-excursion
18665 (goto-char (region-beginning))
18666 (org-at-item-p))))
18667 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18668 (call-interactively 'org-indent-item))
18669 (t (call-interactively 'forward-word))))
18671 (defun org-check-for-hidden (what)
18672 "Check if there are hidden headlines/items in the current visual line.
18673 WHAT can be either `headlines' or `items'. If the current line is
18674 an outline or item heading and it has a folded subtree below it,
18675 this function returns t, nil otherwise."
18676 (let ((re (cond
18677 ((eq what 'headlines) org-outline-regexp-bol)
18678 ((eq what 'items) (org-item-beginning-re))
18679 (t (error "This should not happen"))))
18680 beg end)
18681 (save-excursion
18682 (catch 'exit
18683 (unless (org-region-active-p)
18684 (setq beg (point-at-bol))
18685 (beginning-of-line 2)
18686 (while (and (not (eobp)) ;; this is like `next-line'
18687 (get-char-property (1- (point)) 'invisible))
18688 (beginning-of-line 2))
18689 (setq end (point))
18690 (goto-char beg)
18691 (goto-char (point-at-eol))
18692 (setq end (max end (point)))
18693 (while (re-search-forward re end t)
18694 (if (get-char-property (match-beginning 0) 'invisible)
18695 (throw 'exit t))))
18696 nil))))
18698 (autoload 'org-element-at-point "org-element")
18699 (autoload 'org-element-type "org-element")
18701 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18702 (declare-function org-element-type "org-element" (element))
18703 (declare-function org-element-contents "org-element" (element))
18704 (declare-function org-element-property "org-element" (property element))
18705 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18706 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18707 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18708 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18709 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18711 (defun org-metaup (&optional arg)
18712 "Move subtree up or move table row up.
18713 Calls `org-move-subtree-up' or `org-table-move-row' or
18714 `org-move-item-up', depending on context. See the individual commands
18715 for more information."
18716 (interactive "P")
18717 (cond
18718 ((run-hook-with-args-until-success 'org-metaup-hook))
18719 ((org-region-active-p)
18720 (let* ((a (min (region-beginning) (region-end)))
18721 (b (1- (max (region-beginning) (region-end))))
18722 (c (save-excursion (goto-char a)
18723 (move-beginning-of-line 0)))
18724 (d (save-excursion (goto-char a)
18725 (move-end-of-line 0) (point))))
18726 (transpose-regions a b c d)
18727 (goto-char c)))
18728 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18729 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18730 ((org-at-item-p) (call-interactively 'org-move-item-up))
18731 (t (org-drag-element-backward))))
18733 (defun org-metadown (&optional arg)
18734 "Move subtree down or move table row down.
18735 Calls `org-move-subtree-down' or `org-table-move-row' or
18736 `org-move-item-down', depending on context. See the individual
18737 commands for more information."
18738 (interactive "P")
18739 (cond
18740 ((run-hook-with-args-until-success 'org-metadown-hook))
18741 ((org-region-active-p)
18742 (let* ((a (min (region-beginning) (region-end)))
18743 (b (max (region-beginning) (region-end)))
18744 (c (save-excursion (goto-char b)
18745 (move-beginning-of-line 1)))
18746 (d (save-excursion (goto-char b)
18747 (move-end-of-line 1) (1+ (point)))))
18748 (transpose-regions a b c d)
18749 (goto-char d)))
18750 ((org-at-table-p) (call-interactively 'org-table-move-row))
18751 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18752 ((org-at-item-p) (call-interactively 'org-move-item-down))
18753 (t (org-drag-element-forward))))
18755 (defun org-shiftup (&optional arg)
18756 "Increase item in timestamp or increase priority of current headline.
18757 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18758 depending on context. See the individual commands for more information."
18759 (interactive "P")
18760 (cond
18761 ((run-hook-with-args-until-success 'org-shiftup-hook))
18762 ((and org-support-shift-select (org-region-active-p))
18763 (org-call-for-shift-select 'previous-line))
18764 ((org-at-timestamp-p t)
18765 (call-interactively (if org-edit-timestamp-down-means-later
18766 'org-timestamp-down 'org-timestamp-up)))
18767 ((and (not (eq org-support-shift-select 'always))
18768 org-enable-priority-commands
18769 (org-at-heading-p))
18770 (call-interactively 'org-priority-up))
18771 ((and (not org-support-shift-select) (org-at-item-p))
18772 (call-interactively 'org-previous-item))
18773 ((org-clocktable-try-shift 'up arg))
18774 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18775 (org-support-shift-select
18776 (org-call-for-shift-select 'previous-line))
18777 (t (org-shiftselect-error))))
18779 (defun org-shiftdown (&optional arg)
18780 "Decrease item in timestamp or decrease priority of current headline.
18781 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18782 depending on context. See the individual commands for more information."
18783 (interactive "P")
18784 (cond
18785 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18786 ((and org-support-shift-select (org-region-active-p))
18787 (org-call-for-shift-select 'next-line))
18788 ((org-at-timestamp-p t)
18789 (call-interactively (if org-edit-timestamp-down-means-later
18790 'org-timestamp-up 'org-timestamp-down)))
18791 ((and (not (eq org-support-shift-select 'always))
18792 org-enable-priority-commands
18793 (org-at-heading-p))
18794 (call-interactively 'org-priority-down))
18795 ((and (not org-support-shift-select) (org-at-item-p))
18796 (call-interactively 'org-next-item))
18797 ((org-clocktable-try-shift 'down arg))
18798 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18799 (org-support-shift-select
18800 (org-call-for-shift-select 'next-line))
18801 (t (org-shiftselect-error))))
18803 (defun org-shiftright (&optional arg)
18804 "Cycle the thing at point or in the current line, depending on context.
18805 Depending on context, this does one of the following:
18807 - switch a timestamp at point one day into the future
18808 - on a headline, switch to the next TODO keyword.
18809 - on an item, switch entire list to the next bullet type
18810 - on a property line, switch to the next allowed value
18811 - on a clocktable definition line, move time block into the future"
18812 (interactive "P")
18813 (cond
18814 ((run-hook-with-args-until-success 'org-shiftright-hook))
18815 ((and org-support-shift-select (org-region-active-p))
18816 (org-call-for-shift-select 'forward-char))
18817 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18818 ((and (not (eq org-support-shift-select 'always))
18819 (org-at-heading-p))
18820 (let ((org-inhibit-logging
18821 (not org-treat-S-cursor-todo-selection-as-state-change))
18822 (org-inhibit-blocking
18823 (not org-treat-S-cursor-todo-selection-as-state-change)))
18824 (org-call-with-arg 'org-todo 'right)))
18825 ((or (and org-support-shift-select
18826 (not (eq org-support-shift-select 'always))
18827 (org-at-item-bullet-p))
18828 (and (not org-support-shift-select) (org-at-item-p)))
18829 (org-call-with-arg 'org-cycle-list-bullet nil))
18830 ((and (not (eq org-support-shift-select 'always))
18831 (org-at-property-p))
18832 (call-interactively 'org-property-next-allowed-value))
18833 ((org-clocktable-try-shift 'right arg))
18834 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18835 (org-support-shift-select
18836 (org-call-for-shift-select 'forward-char))
18837 (t (org-shiftselect-error))))
18839 (defun org-shiftleft (&optional arg)
18840 "Cycle the thing at point or in the current line, depending on context.
18841 Depending on context, this does one of the following:
18843 - switch a timestamp at point one day into the past
18844 - on a headline, switch to the previous TODO keyword.
18845 - on an item, switch entire list to the previous bullet type
18846 - on a property line, switch to the previous allowed value
18847 - on a clocktable definition line, move time block into the past"
18848 (interactive "P")
18849 (cond
18850 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18851 ((and org-support-shift-select (org-region-active-p))
18852 (org-call-for-shift-select 'backward-char))
18853 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18854 ((and (not (eq org-support-shift-select 'always))
18855 (org-at-heading-p))
18856 (let ((org-inhibit-logging
18857 (not org-treat-S-cursor-todo-selection-as-state-change))
18858 (org-inhibit-blocking
18859 (not org-treat-S-cursor-todo-selection-as-state-change)))
18860 (org-call-with-arg 'org-todo 'left)))
18861 ((or (and org-support-shift-select
18862 (not (eq org-support-shift-select 'always))
18863 (org-at-item-bullet-p))
18864 (and (not org-support-shift-select) (org-at-item-p)))
18865 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18866 ((and (not (eq org-support-shift-select 'always))
18867 (org-at-property-p))
18868 (call-interactively 'org-property-previous-allowed-value))
18869 ((org-clocktable-try-shift 'left arg))
18870 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18871 (org-support-shift-select
18872 (org-call-for-shift-select 'backward-char))
18873 (t (org-shiftselect-error))))
18875 (defun org-shiftcontrolright ()
18876 "Switch to next TODO set."
18877 (interactive)
18878 (cond
18879 ((and org-support-shift-select (org-region-active-p))
18880 (org-call-for-shift-select 'forward-word))
18881 ((and (not (eq org-support-shift-select 'always))
18882 (org-at-heading-p))
18883 (org-call-with-arg 'org-todo 'nextset))
18884 (org-support-shift-select
18885 (org-call-for-shift-select 'forward-word))
18886 (t (org-shiftselect-error))))
18888 (defun org-shiftcontrolleft ()
18889 "Switch to previous TODO set."
18890 (interactive)
18891 (cond
18892 ((and org-support-shift-select (org-region-active-p))
18893 (org-call-for-shift-select 'backward-word))
18894 ((and (not (eq org-support-shift-select 'always))
18895 (org-at-heading-p))
18896 (org-call-with-arg 'org-todo 'previousset))
18897 (org-support-shift-select
18898 (org-call-for-shift-select 'backward-word))
18899 (t (org-shiftselect-error))))
18901 (defun org-shiftcontrolup ()
18902 "Change timestamps synchronously up in CLOCK log lines."
18903 (interactive)
18904 (cond ((and (not org-support-shift-select)
18905 (org-at-clock-log-p)
18906 (org-at-timestamp-p t))
18907 (org-clock-timestamps-up))
18908 (t (org-shiftselect-error))))
18910 (defun org-shiftcontroldown ()
18911 "Change timestamps synchronously down in CLOCK log lines."
18912 (interactive)
18913 (cond ((and (not org-support-shift-select)
18914 (org-at-clock-log-p)
18915 (org-at-timestamp-p t))
18916 (org-clock-timestamps-down))
18917 (t (org-shiftselect-error))))
18919 (defun org-ctrl-c-ret ()
18920 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18921 (interactive)
18922 (cond
18923 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18924 (t (call-interactively 'org-insert-heading))))
18926 (defun org-find-visible ()
18927 (let ((s (point)))
18928 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18929 (get-char-property s 'invisible)))
18931 (defun org-find-invisible ()
18932 (let ((s (point)))
18933 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18934 (not (get-char-property s 'invisible))))
18937 (defun org-copy-visible (beg end)
18938 "Copy the visible parts of the region."
18939 (interactive "r")
18940 (let (snippets s)
18941 (save-excursion
18942 (save-restriction
18943 (narrow-to-region beg end)
18944 (setq s (goto-char (point-min)))
18945 (while (not (= (point) (point-max)))
18946 (goto-char (org-find-invisible))
18947 (push (buffer-substring s (point)) snippets)
18948 (setq s (goto-char (org-find-visible))))))
18949 (kill-new (apply 'concat (nreverse snippets)))))
18951 (defun org-copy-special ()
18952 "Copy region in table or copy current subtree.
18953 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18954 See the individual commands for more information."
18955 (interactive)
18956 (call-interactively
18957 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18959 (defun org-cut-special ()
18960 "Cut region in table or cut current subtree.
18961 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18962 See the individual commands for more information."
18963 (interactive)
18964 (call-interactively
18965 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18967 (defun org-paste-special (arg)
18968 "Paste rectangular region into table, or past subtree relative to level.
18969 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18970 See the individual commands for more information."
18971 (interactive "P")
18972 (if (org-at-table-p)
18973 (org-table-paste-rectangle)
18974 (org-paste-subtree arg)))
18976 (defsubst org-in-fixed-width-region-p ()
18977 "Is point in a fixed-width region?"
18978 (save-match-data
18979 (eq 'fixed-width (org-element-type (org-element-at-point)))))
18981 (defun org-edit-special (&optional arg)
18982 "Call a special editor for the stuff at point.
18983 When at a table, call the formula editor with `org-table-edit-formulas'.
18984 When in a source code block, call `org-edit-src-code'.
18985 When in a fixed-width region, call `org-edit-fixed-width-region'.
18986 When in an #+include line, visit the included file.
18987 On a link, call `ffap' to visit the link at point.
18988 Otherwise, return a user error."
18989 (interactive)
18990 ;; possibly prep session before editing source
18991 (when (and (org-in-src-block-p) arg)
18992 (let* ((info (org-babel-get-src-block-info))
18993 (lang (nth 0 info))
18994 (params (nth 2 info))
18995 (session (cdr (assoc :session params))))
18996 (when (and info session) ;; we are in a source-code block with a session
18997 (funcall
18998 (intern (concat "org-babel-prep-session:" lang)) session params))))
18999 (cond ;; proceed with `org-edit-special'
19000 ((save-excursion
19001 (beginning-of-line 1)
19002 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19003 (find-file (org-trim (match-string 1))))
19004 ((or (org-at-table-p)
19005 (save-excursion
19006 (beginning-of-line 1)
19007 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19008 (call-interactively 'org-table-edit-formulas))
19009 ((or (org-in-block-p '("src" "example" "latex" "html"))
19010 (org-at-table.el-p))
19011 (org-edit-src-code))
19012 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19013 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19014 (t (user-error "No special environment to edit here"))))
19016 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19017 (defun org-ctrl-c-ctrl-c (&optional arg)
19018 "Set tags in headline, or update according to changed information at point.
19020 This command does many different things, depending on context:
19022 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19023 this is what we do.
19025 - If the cursor is on a statistics cookie, update it.
19027 - If the cursor is in a headline, prompt for tags and insert them
19028 into the current line, aligned to `org-tags-column'. When called
19029 with prefix arg, realign all tags in the current buffer.
19031 - If the cursor is in one of the special #+KEYWORD lines, this
19032 triggers scanning the buffer for these lines and updating the
19033 information.
19035 - If the cursor is inside a table, realign the table. This command
19036 works even if the automatic table editor has been turned off.
19038 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19039 the entire table.
19041 - If the cursor is at a footnote reference or definition, jump to
19042 the corresponding definition or references, respectively.
19044 - If the cursor is a the beginning of a dynamic block, update it.
19046 - If the current buffer is a capture buffer, close note and file it.
19048 - If the cursor is on a <<<target>>>, update radio targets and
19049 corresponding links in this buffer.
19051 - If the cursor is on a numbered item in a plain list, renumber the
19052 ordered list.
19054 - If the cursor is on a checkbox, toggle it.
19056 - If the cursor is on a code block, evaluate it. The variable
19057 `org-confirm-babel-evaluate' can be used to control prompting
19058 before code block evaluation, by default every code block
19059 evaluation requires confirmation. Code block evaluation can be
19060 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19061 (interactive "P")
19062 (let ((org-enable-table-editor t))
19063 (cond
19064 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19065 org-occur-highlights
19066 org-latex-fragment-image-overlays)
19067 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19068 (org-remove-occur-highlights)
19069 (org-remove-latex-fragment-image-overlays)
19070 (message "Temporary highlights/overlays removed from current buffer"))
19071 ((and (local-variable-p 'org-finish-function (current-buffer))
19072 (fboundp org-finish-function))
19073 (funcall org-finish-function))
19074 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19075 ((org-in-regexp org-ts-regexp-both)
19076 (org-timestamp-change 0 'day))
19077 ((or (looking-at org-property-start-re)
19078 (org-at-property-p))
19079 (call-interactively 'org-property-action))
19080 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19081 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19082 (or (org-at-heading-p) (org-at-item-p)))
19083 (call-interactively 'org-update-statistics-cookies))
19084 ((org-at-heading-p) (call-interactively 'org-set-tags))
19085 ((org-at-table.el-p)
19086 (message "Use C-c ' to edit table.el tables"))
19087 ((org-at-table-p)
19088 (org-table-maybe-eval-formula)
19089 (if arg
19090 (call-interactively 'org-table-recalculate)
19091 (org-table-maybe-recalculate-line))
19092 (call-interactively 'org-table-align)
19093 (orgtbl-send-table 'maybe))
19094 ((or (org-footnote-at-reference-p)
19095 (org-footnote-at-definition-p))
19096 (call-interactively 'org-footnote-action))
19097 ((org-at-item-checkbox-p)
19098 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19099 ;; list only if at top item.
19100 (let* ((cbox (match-string 1))
19101 (struct (org-list-struct))
19102 (old-struct (copy-tree struct))
19103 (parents (org-list-parents-alist struct))
19104 (orderedp (org-entry-get nil "ORDERED"))
19105 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19106 block-item)
19107 ;; Use a light version of `org-toggle-checkbox' to avoid
19108 ;; computing list structure twice.
19109 (let ((new-box (cond
19110 ((equal arg '(16)) "[-]")
19111 ((equal arg '(4)) nil)
19112 ((equal "[X]" cbox) "[ ]")
19113 (t "[X]"))))
19114 (if (and firstp arg)
19115 ;; If at first item of sub-list, remove check-box from
19116 ;; every item at the same level.
19117 (mapc
19118 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19119 (org-list-get-all-items
19120 (point-at-bol) struct (org-list-prevs-alist struct)))
19121 (org-list-set-checkbox (point-at-bol) struct new-box)))
19122 ;; Replicate `org-list-write-struct', while grabbing a return
19123 ;; value from `org-list-struct-fix-box'.
19124 (org-list-struct-fix-ind struct parents 2)
19125 (org-list-struct-fix-item-end struct)
19126 (let ((prevs (org-list-prevs-alist struct)))
19127 (org-list-struct-fix-bul struct prevs)
19128 (org-list-struct-fix-ind struct parents)
19129 (setq block-item
19130 (org-list-struct-fix-box struct parents prevs orderedp)))
19131 (if (equal struct old-struct)
19132 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19133 (org-list-struct-apply-struct struct old-struct)
19134 (org-update-checkbox-count-maybe))
19135 (when block-item
19136 (message
19137 "Checkboxes were removed due to unchecked box at line %d"
19138 (org-current-line block-item)))
19139 (when firstp (org-list-send-list 'maybe))))
19140 ((org-at-item-p)
19141 ;; Cursor at an item: repair list. Do checkbox related actions
19142 ;; only if function was called with an argument. Send list only
19143 ;; if at top item.
19144 (let* ((struct (org-list-struct))
19145 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19146 old-struct)
19147 (when arg
19148 (setq old-struct (copy-tree struct))
19149 (if firstp
19150 ;; If at first item of sub-list, add check-box to every
19151 ;; item at the same level.
19152 (mapc
19153 (lambda (pos)
19154 (unless (org-list-get-checkbox pos struct)
19155 (org-list-set-checkbox pos struct "[ ]")))
19156 (org-list-get-all-items
19157 (point-at-bol) struct (org-list-prevs-alist struct)))
19158 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19159 (org-list-write-struct
19160 struct (org-list-parents-alist struct) old-struct)
19161 (when arg (org-update-checkbox-count-maybe))
19162 (when firstp (org-list-send-list 'maybe))))
19163 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19164 ;; Dynamic block
19165 (beginning-of-line 1)
19166 (save-excursion (org-update-dblock)))
19167 ((save-excursion
19168 (let ((case-fold-search t))
19169 (beginning-of-line 1)
19170 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19171 (cond
19172 ((or (equal (match-string 1) "TBLFM")
19173 (equal (match-string 1) "tblfm"))
19174 ;; Recalculate the table before this line
19175 (save-excursion
19176 (beginning-of-line 1)
19177 (skip-chars-backward " \r\n\t")
19178 (if (org-at-table-p)
19179 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19181 (let ((org-inhibit-startup-visibility-stuff t)
19182 (org-startup-align-all-tables nil))
19183 (when (boundp 'org-table-coordinate-overlays)
19184 (mapc 'delete-overlay org-table-coordinate-overlays)
19185 (setq org-table-coordinate-overlays nil))
19186 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19187 (message "Local setup has been refreshed"))))
19188 ((org-clock-update-time-maybe))
19190 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19191 (error "C-c C-c can do nothing useful at this location"))))))
19193 (defun org-mode-restart ()
19194 "Restart Org-mode, to scan again for special lines.
19195 Also updates the keyword regular expressions."
19196 (interactive)
19197 (org-mode)
19198 (message "Org-mode restarted"))
19200 (defun org-kill-note-or-show-branches ()
19201 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19202 (interactive)
19203 (if (not org-finish-function)
19204 (progn
19205 (hide-subtree)
19206 (call-interactively 'show-branches))
19207 (let ((org-note-abort t))
19208 (funcall org-finish-function))))
19210 (defun org-return (&optional indent)
19211 "Goto next table row or insert a newline.
19212 Calls `org-table-next-row' or `newline', depending on context.
19213 See the individual commands for more information."
19214 (interactive)
19215 (let (org-ts-what)
19216 (cond
19217 ((or (bobp) (org-in-src-block-p))
19218 (if indent (newline-and-indent) (newline)))
19219 ((org-at-table-p)
19220 (org-table-justify-field-maybe)
19221 (call-interactively 'org-table-next-row))
19222 ;; when `newline-and-indent' is called within a list, make sure
19223 ;; text moved stays inside the item.
19224 ((and (org-in-item-p) indent)
19225 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19226 (progn
19227 (save-match-data (newline))
19228 (org-indent-line-to (length (match-string 0))))
19229 (let ((ind (org-get-indentation)))
19230 (newline)
19231 (if (org-looking-back org-list-end-re)
19232 (org-indent-line)
19233 (org-indent-line-to ind)))))
19234 ((and org-return-follows-link
19235 (org-at-timestamp-p t)
19236 (not (eq org-ts-what 'after)))
19237 (org-follow-timestamp-link))
19238 ((and org-return-follows-link
19239 (let ((tprop (get-text-property (point) 'face)))
19240 (or (eq tprop 'org-link)
19241 (and (listp tprop) (memq 'org-link tprop)))))
19242 (call-interactively 'org-open-at-point))
19243 ((and (org-at-heading-p)
19244 (looking-at
19245 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19246 (org-show-entry)
19247 (end-of-line 1)
19248 (newline))
19249 (t (if indent (newline-and-indent) (newline))))))
19251 (defun org-return-indent ()
19252 "Goto next table row or insert a newline and indent.
19253 Calls `org-table-next-row' or `newline-and-indent', depending on
19254 context. See the individual commands for more information."
19255 (interactive)
19256 (org-return t))
19258 (defun org-ctrl-c-star ()
19259 "Compute table, or change heading status of lines.
19260 Calls `org-table-recalculate' or `org-toggle-heading',
19261 depending on context."
19262 (interactive)
19263 (cond
19264 ((org-at-table-p)
19265 (call-interactively 'org-table-recalculate))
19267 ;; Convert all lines in region to list items
19268 (call-interactively 'org-toggle-heading))))
19270 (defun org-ctrl-c-minus ()
19271 "Insert separator line in table or modify bullet status of line.
19272 Also turns a plain line or a region of lines into list items.
19273 Calls `org-table-insert-hline', `org-toggle-item', or
19274 `org-cycle-list-bullet', depending on context."
19275 (interactive)
19276 (cond
19277 ((org-at-table-p)
19278 (call-interactively 'org-table-insert-hline))
19279 ((org-region-active-p)
19280 (call-interactively 'org-toggle-item))
19281 ((org-in-item-p)
19282 (call-interactively 'org-cycle-list-bullet))
19284 (call-interactively 'org-toggle-item))))
19286 (defun org-toggle-item (arg)
19287 "Convert headings or normal lines to items, items to normal lines.
19288 If there is no active region, only the current line is considered.
19290 If the first non blank line in the region is an headline, convert
19291 all headlines to items, shifting text accordingly.
19293 If it is an item, convert all items to normal lines.
19295 If it is normal text, change region into an item. With a prefix
19296 argument ARG, change each line in region into an item."
19297 (interactive "P")
19298 (let ((shift-text
19299 (function
19300 ;; Shift text in current section to IND, from point to END.
19301 ;; The function leaves point to END line.
19302 (lambda (ind end)
19303 (let ((min-i 1000) (end (copy-marker end)))
19304 ;; First determine the minimum indentation (MIN-I) of
19305 ;; the text.
19306 (save-excursion
19307 (catch 'exit
19308 (while (< (point) end)
19309 (let ((i (org-get-indentation)))
19310 (cond
19311 ;; Skip blank lines and inline tasks.
19312 ((looking-at "^[ \t]*$"))
19313 ((looking-at org-outline-regexp-bol))
19314 ;; We can't find less than 0 indentation.
19315 ((zerop i) (throw 'exit (setq min-i 0)))
19316 ((< i min-i) (setq min-i i))))
19317 (forward-line))))
19318 ;; Then indent each line so that a line indented to
19319 ;; MIN-I becomes indented to IND. Ignore blank lines
19320 ;; and inline tasks in the process.
19321 (let ((delta (- ind min-i)))
19322 (while (< (point) end)
19323 (unless (or (looking-at "^[ \t]*$")
19324 (looking-at org-outline-regexp-bol))
19325 (org-indent-line-to (+ (org-get-indentation) delta)))
19326 (forward-line)))))))
19327 (skip-blanks
19328 (function
19329 ;; Return beginning of first non-blank line, starting from
19330 ;; line at POS.
19331 (lambda (pos)
19332 (save-excursion
19333 (goto-char pos)
19334 (skip-chars-forward " \r\t\n")
19335 (point-at-bol)))))
19336 beg end)
19337 ;; Determine boundaries of changes.
19338 (if (org-region-active-p)
19339 (setq beg (funcall skip-blanks (region-beginning))
19340 end (copy-marker (region-end)))
19341 (setq beg (funcall skip-blanks (point-at-bol))
19342 end (copy-marker (point-at-eol))))
19343 ;; Depending on the starting line, choose an action on the text
19344 ;; between BEG and END.
19345 (org-with-limited-levels
19346 (save-excursion
19347 (goto-char beg)
19348 (cond
19349 ;; Case 1. Start at an item: de-itemize. Note that it only
19350 ;; happens when a region is active: `org-ctrl-c-minus'
19351 ;; would call `org-cycle-list-bullet' otherwise.
19352 ((org-at-item-p)
19353 (while (< (point) end)
19354 (when (org-at-item-p)
19355 (skip-chars-forward " \t")
19356 (delete-region (point) (match-end 0)))
19357 (forward-line)))
19358 ;; Case 2. Start at an heading: convert to items.
19359 ((org-at-heading-p)
19360 (let* ((bul (org-list-bullet-string "-"))
19361 (bul-len (length bul))
19362 ;; Indentation of the first heading. It should be
19363 ;; relative to the indentation of its parent, if any.
19364 (start-ind (save-excursion
19365 (cond
19366 ((not org-adapt-indentation) 0)
19367 ((not (outline-previous-heading)) 0)
19368 (t (length (match-string 0))))))
19369 ;; Level of first heading. Further headings will be
19370 ;; compared to it to determine hierarchy in the list.
19371 (ref-level (org-reduced-level (org-outline-level))))
19372 (while (< (point) end)
19373 (let* ((level (org-reduced-level (org-outline-level)))
19374 (delta (max 0 (- level ref-level))))
19375 ;; If current headline is less indented than the first
19376 ;; one, set it as reference, in order to preserve
19377 ;; subtrees.
19378 (when (< level ref-level) (setq ref-level level))
19379 (replace-match bul t t)
19380 (org-indent-line-to (+ start-ind (* delta bul-len)))
19381 ;; Ensure all text down to END (or SECTION-END) belongs
19382 ;; to the newly created item.
19383 (let ((section-end (save-excursion
19384 (or (outline-next-heading) (point)))))
19385 (forward-line)
19386 (funcall shift-text
19387 (+ start-ind (* (1+ delta) bul-len))
19388 (min end section-end)))))))
19389 ;; Case 3. Normal line with ARG: turn each non-item line into
19390 ;; an item.
19391 (arg
19392 (while (< (point) end)
19393 (unless (or (org-at-heading-p) (org-at-item-p))
19394 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19395 (replace-match
19396 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19397 (forward-line)))
19398 ;; Case 4. Normal line without ARG: make the first line of
19399 ;; region an item, and shift indentation of others
19400 ;; lines to set them as item's body.
19401 (t (let* ((bul (org-list-bullet-string "-"))
19402 (bul-len (length bul))
19403 (ref-ind (org-get-indentation)))
19404 (skip-chars-forward " \t")
19405 (insert bul)
19406 (forward-line)
19407 (while (< (point) end)
19408 ;; Ensure that lines less indented than first one
19409 ;; still get included in item body.
19410 (funcall shift-text
19411 (+ ref-ind bul-len)
19412 (min end (save-excursion (or (outline-next-heading)
19413 (point)))))
19414 (forward-line)))))))))
19416 (defun org-toggle-heading (&optional nstars)
19417 "Convert headings to normal text, or items or text to headings.
19418 If there is no active region, only the current line is considered.
19420 With a \\[universal-argument] prefix, convert the whole list at
19421 point into heading.
19423 In a region:
19425 - If the first non blank line is an headline, remove the stars
19426 from all headlines in the region.
19428 - If it is a normal line turn each and every normal line (i.e. not an
19429 heading or an item) in the region into a heading.
19431 - If it is a plain list item, turn all plain list items into headings.
19433 When converting a line into a heading, the number of stars is chosen
19434 such that the lines become children of the current entry. However,
19435 when a prefix argument is given, its value determines the number of
19436 stars to add."
19437 (interactive "P")
19438 (let ((skip-blanks
19439 (function
19440 ;; Return beginning of first non-blank line, starting from
19441 ;; line at POS.
19442 (lambda (pos)
19443 (save-excursion
19444 (goto-char pos)
19445 (while (org-at-comment-p) (forward-line))
19446 (skip-chars-forward " \r\t\n")
19447 (point-at-bol)))))
19448 beg end toggled)
19449 ;; Determine boundaries of changes. If a universal prefix has
19450 ;; been given, put the list in a region. If region ends at a bol,
19451 ;; do not consider the last line to be in the region.
19453 (when (and current-prefix-arg (org-at-item-p))
19454 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19455 (org-mark-element))
19457 (if (org-region-active-p)
19458 (setq beg (funcall skip-blanks (region-beginning))
19459 end (copy-marker (save-excursion
19460 (goto-char (region-end))
19461 (if (bolp) (point) (point-at-eol)))))
19462 (setq beg (funcall skip-blanks (point-at-bol))
19463 end (copy-marker (point-at-eol))))
19464 ;; Ensure inline tasks don't count as headings.
19465 (org-with-limited-levels
19466 (save-excursion
19467 (goto-char beg)
19468 (cond
19469 ;; Case 1. Started at an heading: de-star headings.
19470 ((org-at-heading-p)
19471 (while (< (point) end)
19472 (when (org-at-heading-p t)
19473 (looking-at org-outline-regexp) (replace-match "")
19474 (setq toggled t))
19475 (forward-line)))
19476 ;; Case 2. Started at an item: change items into headlines.
19477 ;; One star will be added by `org-list-to-subtree'.
19478 ((org-at-item-p)
19479 (let* ((stars (make-string
19480 (if nstars
19481 ;; subtract the star that will be added again by
19482 ;; `org-list-to-subtree'
19483 (1- (prefix-numeric-value current-prefix-arg))
19484 (or (org-current-level) 0))
19485 ?*))
19486 (add-stars
19487 (cond (nstars "") ; stars from prefix only
19488 ((equal stars "") "") ; before first heading
19489 (org-odd-levels-only "*") ; inside heading, odd
19490 (t "")))) ; inside heading, oddeven
19491 (while (< (point) end)
19492 (when (org-at-item-p)
19493 ;; Pay attention to cases when region ends before list.
19494 (let* ((struct (org-list-struct))
19495 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19496 (save-restriction
19497 (narrow-to-region (point) list-end)
19498 (insert
19499 (org-list-to-subtree
19500 (org-list-parse-list t)
19501 '(:istart (concat stars add-stars (funcall get-stars depth))
19502 :icount (concat stars add-stars (funcall get-stars depth)))))))
19503 (setq toggled t))
19504 (forward-line))))
19505 ;; Case 3. Started at normal text: make every line an heading,
19506 ;; skipping headlines and items.
19507 (t (let* ((stars (make-string
19508 (if nstars
19509 (prefix-numeric-value current-prefix-arg)
19510 (or (org-current-level) 0))
19511 ?*))
19512 (add-stars
19513 (cond (nstars "") ; stars from prefix only
19514 ((equal stars "") "*") ; before first heading
19515 (org-odd-levels-only "**") ; inside heading, odd
19516 (t "*"))) ; inside heading, oddeven
19517 (rpl (concat stars add-stars " ")))
19518 (while (< (point) end)
19519 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19520 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19521 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19522 (forward-line)))))))
19523 (unless toggled (message "Cannot toggle heading from here"))))
19525 (defun org-meta-return (&optional arg)
19526 "Insert a new heading or wrap a region in a table.
19527 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19528 See the individual commands for more information."
19529 (interactive "P")
19530 (cond
19531 ((run-hook-with-args-until-success 'org-metareturn-hook))
19532 ((or (org-at-drawer-p) (org-at-property-p))
19533 (newline-and-indent))
19534 ((org-at-table-p)
19535 (call-interactively 'org-table-wrap-region))
19536 (t (call-interactively 'org-insert-heading))))
19538 ;;; Menu entries
19540 (defsubst org-in-subtree-not-table-p ()
19541 "Are we in a subtree and not in a table?"
19542 (and (not (org-before-first-heading-p))
19543 (not (org-at-table-p))))
19545 ;; Define the Org-mode menus
19546 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19547 '("Tbl"
19548 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19549 ["Next Field" org-cycle (org-at-table-p)]
19550 ["Previous Field" org-shifttab (org-at-table-p)]
19551 ["Next Row" org-return (org-at-table-p)]
19552 "--"
19553 ["Blank Field" org-table-blank-field (org-at-table-p)]
19554 ["Edit Field" org-table-edit-field (org-at-table-p)]
19555 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19556 "--"
19557 ("Column"
19558 ["Move Column Left" org-metaleft (org-at-table-p)]
19559 ["Move Column Right" org-metaright (org-at-table-p)]
19560 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19561 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19562 ("Row"
19563 ["Move Row Up" org-metaup (org-at-table-p)]
19564 ["Move Row Down" org-metadown (org-at-table-p)]
19565 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19566 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19567 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19568 "--"
19569 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19570 ("Rectangle"
19571 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19572 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19573 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19574 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19575 "--"
19576 ("Calculate"
19577 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19578 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19579 ["Edit Formulas" org-edit-special (org-at-table-p)]
19580 "--"
19581 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19582 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19583 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19584 "--"
19585 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19586 "--"
19587 ["Sum Column/Rectangle" org-table-sum
19588 (or (org-at-table-p) (org-region-active-p))]
19589 ["Which Column?" org-table-current-column (org-at-table-p)])
19590 ["Debug Formulas"
19591 org-table-toggle-formula-debugger
19592 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19593 ["Show Col/Row Numbers"
19594 org-table-toggle-coordinate-overlays
19595 :style toggle
19596 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19597 "--"
19598 ["Create" org-table-create (and (not (org-at-table-p))
19599 org-enable-table-editor)]
19600 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19601 ["Import from File" org-table-import (not (org-at-table-p))]
19602 ["Export to File" org-table-export (org-at-table-p)]
19603 "--"
19604 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19606 (easy-menu-define org-org-menu org-mode-map "Org menu"
19607 '("Org"
19608 ("Show/Hide"
19609 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19610 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19611 ["Sparse Tree..." org-sparse-tree t]
19612 ["Reveal Context" org-reveal t]
19613 ["Show All" show-all t]
19614 "--"
19615 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19616 "--"
19617 ["New Heading" org-insert-heading t]
19618 ("Navigate Headings"
19619 ["Up" outline-up-heading t]
19620 ["Next" outline-next-visible-heading t]
19621 ["Previous" outline-previous-visible-heading t]
19622 ["Next Same Level" outline-forward-same-level t]
19623 ["Previous Same Level" outline-backward-same-level t]
19624 "--"
19625 ["Jump" org-goto t])
19626 ("Edit Structure"
19627 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19628 "--"
19629 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19630 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19631 "--"
19632 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19633 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19634 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19635 "--"
19636 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19637 "--"
19638 ["Copy visible text" org-copy-visible t]
19639 "--"
19640 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19641 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19642 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19643 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19644 "--"
19645 ["Sort Region/Children" org-sort t]
19646 "--"
19647 ["Convert to odd levels" org-convert-to-odd-levels t]
19648 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19649 ("Editing"
19650 ["Emphasis..." org-emphasize t]
19651 ["Edit Source Example" org-edit-special t]
19652 "--"
19653 ["Footnote new/jump" org-footnote-action t]
19654 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19655 ("Archive"
19656 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19657 "--"
19658 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19659 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19660 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19662 "--"
19663 ("Hyperlinks"
19664 ["Store Link (Global)" org-store-link t]
19665 ["Find existing link to here" org-occur-link-in-agenda-files t]
19666 ["Insert Link" org-insert-link t]
19667 ["Follow Link" org-open-at-point t]
19668 "--"
19669 ["Next link" org-next-link t]
19670 ["Previous link" org-previous-link t]
19671 "--"
19672 ["Descriptive Links"
19673 org-toggle-link-display
19674 :style radio
19675 :selected org-descriptive-links
19677 ["Literal Links"
19678 org-toggle-link-display
19679 :style radio
19680 :selected (not org-descriptive-links)])
19681 "--"
19682 ("TODO Lists"
19683 ["TODO/DONE/-" org-todo t]
19684 ("Select keyword"
19685 ["Next keyword" org-shiftright (org-at-heading-p)]
19686 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19687 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19688 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19689 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19690 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19691 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19692 "--"
19693 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19694 :selected org-enforce-todo-dependencies :style toggle :active t]
19695 "Settings for tree at point"
19696 ["Do Children sequentially" org-toggle-ordered-property :style radio
19697 :selected (org-entry-get nil "ORDERED")
19698 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19699 ["Do Children parallel" org-toggle-ordered-property :style radio
19700 :selected (not (org-entry-get nil "ORDERED"))
19701 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19702 "--"
19703 ["Set Priority" org-priority t]
19704 ["Priority Up" org-shiftup t]
19705 ["Priority Down" org-shiftdown t]
19706 "--"
19707 ["Get news from all feeds" org-feed-update-all t]
19708 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19709 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19710 ("TAGS and Properties"
19711 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19712 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19713 "--"
19714 ["Set property" org-set-property (not (org-before-first-heading-p))]
19715 ["Column view of properties" org-columns t]
19716 ["Insert Column View DBlock" org-insert-columns-dblock t])
19717 ("Dates and Scheduling"
19718 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19719 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19720 ("Change Date"
19721 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19722 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19723 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19724 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19725 ["Compute Time Range" org-evaluate-time-range t]
19726 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19727 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19728 "--"
19729 ["Custom time format" org-toggle-time-stamp-overlays
19730 :style radio :selected org-display-custom-times]
19731 "--"
19732 ["Goto Calendar" org-goto-calendar t]
19733 ["Date from Calendar" org-date-from-calendar t]
19734 "--"
19735 ["Start/Restart Timer" org-timer-start t]
19736 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19737 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19738 ["Insert Timer String" org-timer t]
19739 ["Insert Timer Item" org-timer-item t])
19740 ("Logging work"
19741 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19742 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19743 ["Clock out" org-clock-out t]
19744 ["Clock cancel" org-clock-cancel t]
19745 "--"
19746 ["Mark as default task" org-clock-mark-default-task t]
19747 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19748 ["Goto running clock" org-clock-goto t]
19749 "--"
19750 ["Display times" org-clock-display t]
19751 ["Create clock table" org-clock-report t]
19752 "--"
19753 ["Record DONE time"
19754 (progn (setq org-log-done (not org-log-done))
19755 (message "Switching to %s will %s record a timestamp"
19756 (car org-done-keywords)
19757 (if org-log-done "automatically" "not")))
19758 :style toggle :selected org-log-done])
19759 "--"
19760 ["Agenda Command..." org-agenda t]
19761 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19762 ("File List for Agenda")
19763 ("Special views current file"
19764 ["TODO Tree" org-show-todo-tree t]
19765 ["Check Deadlines" org-check-deadlines t]
19766 ["Timeline" org-timeline t]
19767 ["Tags/Property tree" org-match-sparse-tree t])
19768 "--"
19769 ["Export/Publish..." org-export t]
19770 ("LaTeX"
19771 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19772 :selected org-cdlatex-mode]
19773 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19774 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19775 ["Modify math symbol" org-cdlatex-math-modify
19776 (org-inside-LaTeX-fragment-p)]
19777 ["Insert citation" org-reftex-citation t]
19778 "--"
19779 ["Template for BEAMER" (progn (require 'org-beamer)
19780 (org-insert-beamer-options-template)) t])
19781 "--"
19782 ("MobileOrg"
19783 ["Push Files and Views" org-mobile-push t]
19784 ["Get Captured and Flagged" org-mobile-pull t]
19785 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19786 "--"
19787 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19788 "--"
19789 ("Documentation"
19790 ["Show Version" org-version t]
19791 ["Info Documentation" org-info t])
19792 ("Customize"
19793 ["Browse Org Group" org-customize t]
19794 "--"
19795 ["Expand This Menu" org-create-customize-menu
19796 (fboundp 'customize-menu-create)])
19797 ["Send bug report" org-submit-bug-report t]
19798 "--"
19799 ("Refresh/Reload"
19800 ["Refresh setup current buffer" org-mode-restart t]
19801 ["Reload Org (after update)" org-reload t]
19802 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19805 (defun org-info (&optional node)
19806 "Read documentation for Org-mode in the info system.
19807 With optional NODE, go directly to that node."
19808 (interactive)
19809 (info (format "(org)%s" (or node ""))))
19811 ;;;###autoload
19812 (defun org-submit-bug-report ()
19813 "Submit a bug report on Org-mode via mail.
19815 Don't hesitate to report any problems or inaccurate documentation.
19817 If you don't have setup sending mail from (X)Emacs, please copy the
19818 output buffer into your mail program, as it gives us important
19819 information about your Org-mode version and configuration."
19820 (interactive)
19821 (require 'reporter)
19822 (org-load-modules-maybe)
19823 (org-require-autoloaded-modules)
19824 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19825 (reporter-submit-bug-report
19826 "emacs-orgmode@gnu.org"
19827 (org-version nil 'full)
19828 (let (list)
19829 (save-window-excursion
19830 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19831 (delete-other-windows)
19832 (erase-buffer)
19833 (insert "You are about to submit a bug report to the Org-mode mailing list.
19835 We would like to add your full Org-mode and Outline configuration to the
19836 bug report. This greatly simplifies the work of the maintainer and
19837 other experts on the mailing list.
19839 HOWEVER, some variables you have customized may contain private
19840 information. The names of customers, colleagues, or friends, might
19841 appear in the form of file names, tags, todo states, or search strings.
19842 If you answer yes to the prompt, you might want to check and remove
19843 such private information before sending the email.")
19844 (add-text-properties (point-min) (point-max) '(face org-warning))
19845 (when (yes-or-no-p "Include your Org-mode configuration ")
19846 (mapatoms
19847 (lambda (v)
19848 (and (boundp v)
19849 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19850 (or (and (symbol-value v)
19851 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19852 (and
19853 (get v 'custom-type) (get v 'standard-value)
19854 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19855 (push v list)))))
19856 (kill-buffer (get-buffer "*Warn about privacy*"))
19857 list))
19858 nil nil
19859 "Remember to cover the basics, that is, what you expected to happen and
19860 what in fact did happen. You don't know how to make a good report? See
19862 http://orgmode.org/manual/Feedback.html#Feedback
19864 Your bug report will be posted to the Org-mode mailing list.
19865 ------------------------------------------------------------------------")
19866 (save-excursion
19867 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19868 (replace-match "\\1Bug: \\3 [\\2]")))))
19871 (defun org-install-agenda-files-menu ()
19872 (let ((bl (buffer-list)))
19873 (save-excursion
19874 (while bl
19875 (set-buffer (pop bl))
19876 (if (derived-mode-p 'org-mode) (setq bl nil)))
19877 (when (derived-mode-p 'org-mode)
19878 (easy-menu-change
19879 '("Org") "File List for Agenda"
19880 (append
19881 (list
19882 ["Edit File List" (org-edit-agenda-file-list) t]
19883 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19884 ["Remove Current File from List" org-remove-file t]
19885 ["Cycle through agenda files" org-cycle-agenda-files t]
19886 ["Occur in all agenda files" org-occur-in-agenda-files t]
19887 "--")
19888 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19890 ;;;; Documentation
19892 (defun org-require-autoloaded-modules ()
19893 (interactive)
19894 (mapc 'require
19895 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19896 org-docbook org-exp org-html org-icalendar
19897 org-id org-latex
19898 org-publish org-remember org-table
19899 org-timer org-xoxo)))
19901 ;;;###autoload
19902 (defun org-reload (&optional uncompiled)
19903 "Reload all org lisp files.
19904 With prefix arg UNCOMPILED, load the uncompiled versions."
19905 (interactive "P")
19906 (require 'find-func)
19907 (let* ((file-re "^org\\(-.*\\)?\\.el")
19908 (dir-org (file-name-directory (org-find-library-dir "org")))
19909 (dir-org-contrib (ignore-errors
19910 (file-name-directory
19911 (org-find-library-dir "org-contribdir"))))
19912 (babel-files
19913 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19914 (append (list nil "comint" "eval" "exp" "keys"
19915 "lob" "ref" "table" "tangle")
19916 (delq nil
19917 (mapcar
19918 (lambda (lang)
19919 (when (cdr lang) (symbol-name (car lang))))
19920 org-babel-load-languages)))))
19921 (files
19922 (append babel-files
19923 (and dir-org-contrib
19924 (directory-files dir-org-contrib t file-re))
19925 (directory-files dir-org t file-re)))
19926 (remove-re (concat (if (featurep 'xemacs)
19927 "org-colview" "org-colview-xemacs")
19928 "\\'")))
19929 (setq files (mapcar 'file-name-sans-extension files))
19930 (setq files (mapcar
19931 (lambda (x) (if (string-match remove-re x) nil x))
19932 files))
19933 (setq files (delq nil files))
19934 (mapc
19935 (lambda (f)
19936 (when (featurep (intern (file-name-nondirectory f)))
19937 (if (and (not uncompiled)
19938 (file-exists-p (concat f ".elc")))
19939 (load (concat f ".elc") nil nil 'nosuffix)
19940 (load (concat f ".el") nil nil 'nosuffix))))
19941 files)
19942 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
19943 (org-version nil 'full 'message))
19945 ;;;###autoload
19946 (defun org-customize ()
19947 "Call the customize function with org as argument."
19948 (interactive)
19949 (org-load-modules-maybe)
19950 (org-require-autoloaded-modules)
19951 (customize-browse 'org))
19953 (defun org-create-customize-menu ()
19954 "Create a full customization menu for Org-mode, insert it into the menu."
19955 (interactive)
19956 (org-load-modules-maybe)
19957 (org-require-autoloaded-modules)
19958 (if (fboundp 'customize-menu-create)
19959 (progn
19960 (easy-menu-change
19961 '("Org") "Customize"
19962 `(["Browse Org group" org-customize t]
19963 "--"
19964 ,(customize-menu-create 'org)
19965 ["Set" Custom-set t]
19966 ["Save" Custom-save t]
19967 ["Reset to Current" Custom-reset-current t]
19968 ["Reset to Saved" Custom-reset-saved t]
19969 ["Reset to Standard Settings" Custom-reset-standard t]))
19970 (message "\"Org\"-menu now contains full customization menu"))
19971 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19973 ;;;; Miscellaneous stuff
19975 ;;; Generally useful functions
19977 (defun org-get-at-bol (property)
19978 "Get text property PROPERTY at beginning of line."
19979 (get-text-property (point-at-bol) property))
19981 (defun org-find-text-property-in-string (prop s)
19982 "Return the first non-nil value of property PROP in string S."
19983 (or (get-text-property 0 prop s)
19984 (get-text-property (or (next-single-property-change 0 prop s) 0)
19985 prop s)))
19987 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19988 "Display the given MESSAGE as a warning."
19989 (if (fboundp 'display-warning)
19990 (display-warning 'org message
19991 (if (featurep 'xemacs) 'warning :warning))
19992 (let ((buf (get-buffer-create "*Org warnings*")))
19993 (with-current-buffer buf
19994 (goto-char (point-max))
19995 (insert "Warning (Org): " message)
19996 (unless (bolp)
19997 (newline)))
19998 (display-buffer buf)
19999 (sit-for 0))))
20001 (defun org-eval (form)
20002 "Eval FORM and return result."
20003 (condition-case error
20004 (eval form)
20005 (error (format "%%![Error: %s]" error))))
20007 (defun org-in-clocktable-p ()
20008 "Check if the cursor is in a clocktable."
20009 (let ((pos (point)) start)
20010 (save-excursion
20011 (end-of-line 1)
20012 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20013 (setq start (match-beginning 0))
20014 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20015 (>= (match-end 0) pos)
20016 start))))
20018 (defun org-in-commented-line ()
20019 "Is point in a line starting with `#'?"
20020 (equal (char-after (point-at-bol)) ?#))
20022 (defun org-in-indented-comment-line ()
20023 "Is point in a line starting with `#' after some white space?"
20024 (save-excursion
20025 (save-match-data
20026 (goto-char (point-at-bol))
20027 (looking-at "[ \t]*#"))))
20029 (defun org-in-verbatim-emphasis ()
20030 (save-match-data
20031 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20033 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20034 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20035 (if (and marker (marker-buffer marker)
20036 (buffer-live-p (marker-buffer marker)))
20037 (progn
20038 (org-pop-to-buffer-same-window (marker-buffer marker))
20039 (if (or (> marker (point-max)) (< marker (point-min)))
20040 (widen))
20041 (goto-char marker)
20042 (org-show-context 'org-goto))
20043 (if bookmark
20044 (bookmark-jump bookmark)
20045 (error "Cannot find location"))))
20047 (defun org-quote-csv-field (s)
20048 "Quote field for inclusion in CSV material."
20049 (if (string-match "[\",]" s)
20050 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20053 (defun org-force-self-insert (N)
20054 "Needed to enforce self-insert under remapping."
20055 (interactive "p")
20056 (self-insert-command N))
20058 (defun org-string-width (s)
20059 "Compute width of string, ignoring invisible characters.
20060 This ignores character with invisibility property `org-link', and also
20061 characters with property `org-cwidth', because these will become invisible
20062 upon the next fontification round."
20063 (let (b l)
20064 (when (or (eq t buffer-invisibility-spec)
20065 (assq 'org-link buffer-invisibility-spec))
20066 (while (setq b (text-property-any 0 (length s)
20067 'invisible 'org-link s))
20068 (setq s (concat (substring s 0 b)
20069 (substring s (or (next-single-property-change
20070 b 'invisible s) (length s)))))))
20071 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20072 (setq s (concat (substring s 0 b)
20073 (substring s (or (next-single-property-change
20074 b 'org-cwidth s) (length s))))))
20075 (setq l (string-width s) b -1)
20076 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20077 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20080 (defun org-shorten-string (s maxlength)
20081 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20082 If the string is shorter or has length MAXLENGTH, just return the
20083 original string. If it is longer, the functions finds a space in the
20084 string, breaks this string off at that locations and adds three dots
20085 as ellipsis. Including the ellipsis, the string will not be longer
20086 than MAXLENGTH. If finding a good breaking point in the string does
20087 not work, the string is just chopped off in the middle of a word
20088 if necessary."
20089 (if (<= (length s) maxlength)
20091 (let* ((n (max (- maxlength 4) 1))
20092 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20093 (if (string-match re s)
20094 (concat (match-string 1 s) "...")
20095 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20097 (defun org-get-indentation (&optional line)
20098 "Get the indentation of the current line, interpreting tabs.
20099 When LINE is given, assume it represents a line and compute its indentation."
20100 (if line
20101 (if (string-match "^ *" (org-remove-tabs line))
20102 (match-end 0))
20103 (save-excursion
20104 (beginning-of-line 1)
20105 (skip-chars-forward " \t")
20106 (current-column))))
20108 (defun org-get-string-indentation (s)
20109 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20110 (let ((n -1) (i 0) (w tab-width) c)
20111 (catch 'exit
20112 (while (< (setq n (1+ n)) (length s))
20113 (setq c (aref s n))
20114 (cond ((= c ?\ ) (setq i (1+ i)))
20115 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20116 (t (throw 'exit t)))))
20119 (defun org-remove-tabs (s &optional width)
20120 "Replace tabulators in S with spaces.
20121 Assumes that s is a single line, starting in column 0."
20122 (setq width (or width tab-width))
20123 (while (string-match "\t" s)
20124 (setq s (replace-match
20125 (make-string
20126 (- (* width (/ (+ (match-beginning 0) width) width))
20127 (match-beginning 0)) ?\ )
20128 t t s)))
20131 (defun org-fix-indentation (line ind)
20132 "Fix indentation in LINE.
20133 IND is a cons cell with target and minimum indentation.
20134 If the current indentation in LINE is smaller than the minimum,
20135 leave it alone. If it is larger than ind, set it to the target."
20136 (let* ((l (org-remove-tabs line))
20137 (i (org-get-indentation l))
20138 (i1 (car ind)) (i2 (cdr ind)))
20139 (if (>= i i2) (setq l (substring line i2)))
20140 (if (> i1 0)
20141 (concat (make-string i1 ?\ ) l)
20142 l)))
20144 (defun org-remove-indentation (code &optional n)
20145 "Remove the maximum common indentation from the lines in CODE.
20146 N may optionally be the number of spaces to remove."
20147 (with-temp-buffer
20148 (insert code)
20149 (org-do-remove-indentation n)
20150 (buffer-string)))
20152 (defun org-do-remove-indentation (&optional n)
20153 "Remove the maximum common indentation from the buffer."
20154 (untabify (point-min) (point-max))
20155 (let ((min 10000) re)
20156 (if n
20157 (setq min n)
20158 (goto-char (point-min))
20159 (while (re-search-forward "^ *[^ \n]" nil t)
20160 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20161 (unless (or (= min 0) (= min 10000))
20162 (setq re (format "^ \\{%d\\}" min))
20163 (goto-char (point-min))
20164 (while (re-search-forward re nil t)
20165 (replace-match "")
20166 (end-of-line 1))
20167 min)))
20169 (defun org-fill-template (template alist)
20170 "Find each %key of ALIST in TEMPLATE and replace it."
20171 (let ((case-fold-search nil)
20172 entry key value)
20173 (setq alist (sort (copy-sequence alist)
20174 (lambda (a b) (< (length (car a)) (length (car b))))))
20175 (while (setq entry (pop alist))
20176 (setq template
20177 (replace-regexp-in-string
20178 (concat "%" (regexp-quote (car entry)))
20179 (or (cdr entry) "") template t t)))
20180 template))
20182 (defun org-base-buffer (buffer)
20183 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20184 (if (not buffer)
20185 buffer
20186 (or (buffer-base-buffer buffer)
20187 buffer)))
20189 (defun org-trim (s)
20190 "Remove whitespace at beginning and end of string."
20191 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20192 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20195 (defun org-wrap (string &optional width lines)
20196 "Wrap string to either a number of lines, or a width in characters.
20197 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20198 that costs. If there is a word longer than WIDTH, the text is actually
20199 wrapped to the length of that word.
20200 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20201 many lines, whatever width that takes.
20202 The return value is a list of lines, without newlines at the end."
20203 (let* ((words (org-split-string string "[ \t\n]+"))
20204 (maxword (apply 'max (mapcar 'org-string-width words)))
20205 w ll)
20206 (cond (width
20207 (org-do-wrap words (max maxword width)))
20208 (lines
20209 (setq w maxword)
20210 (setq ll (org-do-wrap words maxword))
20211 (if (<= (length ll) lines)
20213 (setq ll words)
20214 (while (> (length ll) lines)
20215 (setq w (1+ w))
20216 (setq ll (org-do-wrap words w)))
20217 ll))
20218 (t (error "Cannot wrap this")))))
20220 (defun org-do-wrap (words width)
20221 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20222 (let (lines line)
20223 (while words
20224 (setq line (pop words))
20225 (while (and words (< (+ (length line) (length (car words))) width))
20226 (setq line (concat line " " (pop words))))
20227 (setq lines (push line lines)))
20228 (nreverse lines)))
20230 (defun org-split-string (string &optional separators)
20231 "Splits STRING into substrings at SEPARATORS.
20232 No empty strings are returned if there are matches at the beginning
20233 and end of string."
20234 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20235 (start 0)
20236 notfirst
20237 (list nil))
20238 (while (and (string-match rexp string
20239 (if (and notfirst
20240 (= start (match-beginning 0))
20241 (< start (length string)))
20242 (1+ start) start))
20243 (< (match-beginning 0) (length string)))
20244 (setq notfirst t)
20245 (or (eq (match-beginning 0) 0)
20246 (and (eq (match-beginning 0) (match-end 0))
20247 (eq (match-beginning 0) start))
20248 (setq list
20249 (cons (substring string start (match-beginning 0))
20250 list)))
20251 (setq start (match-end 0)))
20252 (or (eq start (length string))
20253 (setq list
20254 (cons (substring string start)
20255 list)))
20256 (nreverse list)))
20258 (defun org-quote-vert (s)
20259 "Replace \"|\" with \"\\vert\"."
20260 (while (string-match "|" s)
20261 (setq s (replace-match "\\vert" t t s)))
20264 (defun org-uuidgen-p (s)
20265 "Is S an ID created by UUIDGEN?"
20266 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20268 (defun org-in-src-block-p (&optional inside)
20269 "Whether point is in a code source block.
20270 When INSIDE is non-nil, don't consider we are within a src block
20271 when point is at #+BEGIN_SRC or #+END_SRC."
20272 (let ((case-fold-search t) ov)
20273 (or (and (setq ov (overlays-at (point)))
20274 (memq 'org-block-background
20275 (overlay-properties (car ov))))
20276 (and (not inside)
20277 (save-match-data
20278 (save-excursion
20279 (beginning-of-line)
20280 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20282 (defun org-context ()
20283 "Return a list of contexts of the current cursor position.
20284 If several contexts apply, all are returned.
20285 Each context entry is a list with a symbol naming the context, and
20286 two positions indicating start and end of the context. Possible
20287 contexts are:
20289 :headline anywhere in a headline
20290 :headline-stars on the leading stars in a headline
20291 :todo-keyword on a TODO keyword (including DONE) in a headline
20292 :tags on the TAGS in a headline
20293 :priority on the priority cookie in a headline
20294 :item on the first line of a plain list item
20295 :item-bullet on the bullet/number of a plain list item
20296 :checkbox on the checkbox in a plain list item
20297 :table in an org-mode table
20298 :table-special on a special filed in a table
20299 :table-table in a table.el table
20300 :clocktable in a clocktable
20301 :src-block in a source block
20302 :link on a hyperlink
20303 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20304 :target on a <<target>>
20305 :radio-target on a <<<radio-target>>>
20306 :latex-fragment on a LaTeX fragment
20307 :latex-preview on a LaTeX fragment with overlaid preview image
20309 This function expects the position to be visible because it uses font-lock
20310 faces as a help to recognize the following contexts: :table-special, :link,
20311 and :keyword."
20312 (let* ((f (get-text-property (point) 'face))
20313 (faces (if (listp f) f (list f)))
20314 (case-fold-search t)
20315 (p (point)) clist o)
20316 ;; First the large context
20317 (cond
20318 ((org-at-heading-p t)
20319 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20320 (when (progn
20321 (beginning-of-line 1)
20322 (looking-at org-todo-line-tags-regexp))
20323 (push (org-point-in-group p 1 :headline-stars) clist)
20324 (push (org-point-in-group p 2 :todo-keyword) clist)
20325 (push (org-point-in-group p 4 :tags) clist))
20326 (goto-char p)
20327 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20328 (if (looking-at "\\[#[A-Z0-9]\\]")
20329 (push (org-point-in-group p 0 :priority) clist)))
20331 ((org-at-item-p)
20332 (push (org-point-in-group p 2 :item-bullet) clist)
20333 (push (list :item (point-at-bol)
20334 (save-excursion (org-end-of-item) (point)))
20335 clist)
20336 (and (org-at-item-checkbox-p)
20337 (push (org-point-in-group p 0 :checkbox) clist)))
20339 ((org-at-table-p)
20340 (push (list :table (org-table-begin) (org-table-end)) clist)
20341 (if (memq 'org-formula faces)
20342 (push (list :table-special
20343 (previous-single-property-change p 'face)
20344 (next-single-property-change p 'face)) clist)))
20345 ((org-at-table-p 'any)
20346 (push (list :table-table) clist)))
20347 (goto-char p)
20349 (let ((case-fold-search t))
20350 ;; New the "medium" contexts: clocktables, source blocks
20351 (cond ((org-in-clocktable-p)
20352 (push (list :clocktable
20353 (and (or (looking-at "#\\+BEGIN: clocktable")
20354 (search-backward "#+BEGIN: clocktable" nil t))
20355 (match-beginning 0))
20356 (and (re-search-forward "#\\+END:?" nil t)
20357 (match-end 0))) clist))
20358 ((org-in-src-block-p)
20359 (push (list :src-block
20360 (and (or (looking-at "#\\+BEGIN_SRC")
20361 (search-backward "#+BEGIN_SRC" nil t))
20362 (match-beginning 0))
20363 (and (search-forward "#+END_SRC" nil t)
20364 (match-beginning 0))) clist))))
20365 (goto-char p)
20367 ;; Now the small context
20368 (cond
20369 ((org-at-timestamp-p)
20370 (push (org-point-in-group p 0 :timestamp) clist))
20371 ((memq 'org-link faces)
20372 (push (list :link
20373 (previous-single-property-change p 'face)
20374 (next-single-property-change p 'face)) clist))
20375 ((memq 'org-special-keyword faces)
20376 (push (list :keyword
20377 (previous-single-property-change p 'face)
20378 (next-single-property-change p 'face)) clist))
20379 ((org-at-target-p)
20380 (push (org-point-in-group p 0 :target) clist)
20381 (goto-char (1- (match-beginning 0)))
20382 (if (looking-at org-radio-target-regexp)
20383 (push (org-point-in-group p 0 :radio-target) clist))
20384 (goto-char p))
20385 ((setq o (car (delq nil
20386 (mapcar
20387 (lambda (x)
20388 (if (memq x org-latex-fragment-image-overlays) x))
20389 (overlays-at (point))))))
20390 (push (list :latex-fragment
20391 (overlay-start o) (overlay-end o)) clist)
20392 (push (list :latex-preview
20393 (overlay-start o) (overlay-end o)) clist))
20394 ((org-inside-LaTeX-fragment-p)
20395 ;; FIXME: positions wrong.
20396 (push (list :latex-fragment (point) (point)) clist)))
20398 (setq clist (nreverse (delq nil clist)))
20399 clist))
20401 ;; FIXME: Compare with at-regexp-p Do we need both?
20402 (defun org-in-regexp (re &optional nlines visually)
20403 "Check if point is inside a match of regexp.
20404 Normally only the current line is checked, but you can include NLINES extra
20405 lines both before and after point into the search.
20406 If VISUALLY is set, require that the cursor is not after the match but
20407 really on, so that the block visually is on the match."
20408 (catch 'exit
20409 (let ((pos (point))
20410 (eol (point-at-eol (+ 1 (or nlines 0))))
20411 (inc (if visually 1 0)))
20412 (save-excursion
20413 (beginning-of-line (- 1 (or nlines 0)))
20414 (while (re-search-forward re eol t)
20415 (if (and (<= (match-beginning 0) pos)
20416 (>= (+ inc (match-end 0)) pos))
20417 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20419 (defun org-at-regexp-p (regexp)
20420 "Is point inside a match of REGEXP in the current line?"
20421 (catch 'exit
20422 (save-excursion
20423 (let ((pos (point)) (end (point-at-eol)))
20424 (beginning-of-line 1)
20425 (while (re-search-forward regexp end t)
20426 (if (and (<= (match-beginning 0) pos)
20427 (>= (match-end 0) pos))
20428 (throw 'exit t)))
20429 nil))))
20431 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20432 "Non-nil when point is between matches of START-RE and END-RE.
20434 Also return a non-nil value when point is on one of the matches.
20436 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20437 buffer positions. Default values are the positions of headlines
20438 surrounding the point.
20440 The functions returns a cons cell whose car (resp. cdr) is the
20441 position before START-RE (resp. after END-RE)."
20442 (save-match-data
20443 (let ((pos (point))
20444 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20445 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20446 beg end)
20447 (save-excursion
20448 ;; Point is on a block when on START-RE or if START-RE can be
20449 ;; found before it...
20450 (and (or (org-at-regexp-p start-re)
20451 (re-search-backward start-re limit-up t))
20452 (setq beg (match-beginning 0))
20453 ;; ... and END-RE after it...
20454 (goto-char (match-end 0))
20455 (re-search-forward end-re limit-down t)
20456 (> (setq end (match-end 0)) pos)
20457 ;; ... without another START-RE in-between.
20458 (goto-char (match-beginning 0))
20459 (not (re-search-backward start-re (1+ beg) t))
20460 ;; Return value.
20461 (cons beg end))))))
20463 (defun org-in-block-p (names)
20464 "Non-nil when point belongs to a block whose name belongs to NAMES.
20466 NAMES is a list of strings containing names of blocks.
20468 Return first block name matched, or nil. Beware that in case of
20469 nested blocks, the returned name may not belong to the closest
20470 block from point."
20471 (save-match-data
20472 (catch 'exit
20473 (let ((case-fold-search t)
20474 (lim-up (save-excursion (outline-previous-heading)))
20475 (lim-down (save-excursion (outline-next-heading))))
20476 (mapc (lambda (name)
20477 (let ((n (regexp-quote name)))
20478 (when (org-between-regexps-p
20479 (concat "^[ \t]*#\\+begin_" n)
20480 (concat "^[ \t]*#\\+end_" n)
20481 lim-up lim-down)
20482 (throw 'exit n))))
20483 names))
20484 nil)))
20486 (defun org-occur-in-agenda-files (regexp &optional nlines)
20487 "Call `multi-occur' with buffers for all agenda files."
20488 (interactive "sOrg-files matching: \np")
20489 (let* ((files (org-agenda-files))
20490 (tnames (mapcar 'file-truename files))
20491 (extra org-agenda-text-search-extra-files)
20493 (when (eq (car extra) 'agenda-archives)
20494 (setq extra (cdr extra))
20495 (setq files (org-add-archive-files files)))
20496 (while (setq f (pop extra))
20497 (unless (member (file-truename f) tnames)
20498 (add-to-list 'files f 'append)
20499 (add-to-list 'tnames (file-truename f) 'append)))
20500 (multi-occur
20501 (mapcar (lambda (x)
20502 (with-current-buffer
20503 (or (get-file-buffer x) (find-file-noselect x))
20504 (widen)
20505 (current-buffer)))
20506 files)
20507 regexp)))
20509 (if (boundp 'occur-mode-find-occurrence-hook)
20510 ;; Emacs 23
20511 (add-hook 'occur-mode-find-occurrence-hook
20512 (lambda ()
20513 (when (derived-mode-p 'org-mode)
20514 (org-reveal))))
20515 ;; Emacs 22
20516 (defadvice occur-mode-goto-occurrence
20517 (after org-occur-reveal activate)
20518 (and (derived-mode-p 'org-mode) (org-reveal)))
20519 (defadvice occur-mode-goto-occurrence-other-window
20520 (after org-occur-reveal activate)
20521 (and (derived-mode-p 'org-mode) (org-reveal)))
20522 (defadvice occur-mode-display-occurrence
20523 (after org-occur-reveal activate)
20524 (when (derived-mode-p 'org-mode)
20525 (let ((pos (occur-mode-find-occurrence)))
20526 (with-current-buffer (marker-buffer pos)
20527 (save-excursion
20528 (goto-char pos)
20529 (org-reveal)))))))
20531 (defun org-occur-link-in-agenda-files ()
20532 "Create a link and search for it in the agendas.
20533 The link is not stored in `org-stored-links', it is just created
20534 for the search purpose."
20535 (interactive)
20536 (let ((link (condition-case nil
20537 (org-store-link nil)
20538 (error "Unable to create a link to here"))))
20539 (org-occur-in-agenda-files (regexp-quote link))))
20541 (defun org-uniquify (list)
20542 "Remove duplicate elements from LIST."
20543 (let (res)
20544 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20545 res))
20547 (defun org-delete-all (elts list)
20548 "Remove all elements in ELTS from LIST."
20549 (while elts
20550 (setq list (delete (pop elts) list)))
20551 list)
20553 (defun org-count (cl-item cl-seq)
20554 "Count the number of occurrences of ITEM in SEQ.
20555 Taken from `count' in cl-seq.el with all keyword arguments removed."
20556 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20557 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20558 (while (< cl-start cl-end)
20559 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20560 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20561 (setq cl-start (1+ cl-start)))
20562 cl-count))
20564 (defun org-remove-if (predicate seq)
20565 "Remove everything from SEQ that fulfills PREDICATE."
20566 (let (res e)
20567 (while seq
20568 (setq e (pop seq))
20569 (if (not (funcall predicate e)) (push e res)))
20570 (nreverse res)))
20572 (defun org-remove-if-not (predicate seq)
20573 "Remove everything from SEQ that does not fulfill PREDICATE."
20574 (let (res e)
20575 (while seq
20576 (setq e (pop seq))
20577 (if (funcall predicate e) (push e res)))
20578 (nreverse res)))
20580 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20581 "Reduce two-argument FUNCTION across SEQ.
20582 Taken from `reduce' in cl-seq.el with all keyword arguments but
20583 \":initial-value\" removed."
20584 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20585 (cadr (memq :initial-value cl-keys)))
20586 (cl-seq (pop cl-seq))
20587 (t (funcall cl-func)))))
20588 (while cl-seq
20589 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20590 cl-accum))
20592 (defun org-back-over-empty-lines ()
20593 "Move backwards over whitespace, to the beginning of the first empty line.
20594 Returns the number of empty lines passed."
20595 (let ((pos (point)))
20596 (if (cdr (assoc 'heading org-blank-before-new-entry))
20597 (skip-chars-backward " \t\n\r")
20598 (unless (eobp)
20599 (forward-line -1)))
20600 (beginning-of-line 2)
20601 (goto-char (min (point) pos))
20602 (count-lines (point) pos)))
20604 (defun org-skip-whitespace ()
20605 (skip-chars-forward " \t\n\r"))
20607 (defun org-point-in-group (point group &optional context)
20608 "Check if POINT is in match-group GROUP.
20609 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20610 match. If the match group does not exist or point is not inside it,
20611 return nil."
20612 (and (match-beginning group)
20613 (>= point (match-beginning group))
20614 (<= point (match-end group))
20615 (if context
20616 (list context (match-beginning group) (match-end group))
20617 t)))
20619 (defun org-switch-to-buffer-other-window (&rest args)
20620 "Switch to buffer in a second window on the current frame.
20621 In particular, do not allow pop-up frames.
20622 Returns the newly created buffer."
20623 (org-no-popups
20624 (apply 'switch-to-buffer-other-window args)))
20626 (defun org-combine-plists (&rest plists)
20627 "Create a single property list from all plists in PLISTS.
20628 The process starts by copying the first list, and then setting properties
20629 from the other lists. Settings in the last list are the most significant
20630 ones and overrule settings in the other lists."
20631 (let ((rtn (copy-sequence (pop plists)))
20632 p v ls)
20633 (while plists
20634 (setq ls (pop plists))
20635 (while ls
20636 (setq p (pop ls) v (pop ls))
20637 (setq rtn (plist-put rtn p v))))
20638 rtn))
20640 (defun org-replace-escapes (string table)
20641 "Replace %-escapes in STRING with values in TABLE.
20642 TABLE is an association list with keys like \"%a\" and string values.
20643 The sequences in STRING may contain normal field width and padding information,
20644 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20645 so values can contain further %-escapes if they are define later in TABLE."
20646 (let ((tbl (copy-alist table))
20647 (case-fold-search nil)
20648 (pchg 0)
20649 e re rpl)
20650 (while (setq e (pop tbl))
20651 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20652 (when (and (cdr e) (string-match re (cdr e)))
20653 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20654 (safe "SREF"))
20655 (add-text-properties 0 3 (list 'sref sref) safe)
20656 (setcdr e (replace-match safe t t (cdr e)))))
20657 (while (string-match re string)
20658 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20659 (cdr e)))
20660 (setq string (replace-match rpl t t string))))
20661 (while (setq pchg (next-property-change pchg string))
20662 (let ((sref (get-text-property pchg 'sref string)))
20663 (when (and sref (string-match "SREF" string pchg))
20664 (setq string (replace-match sref t t string)))))
20665 string))
20667 (defun org-sublist (list start end)
20668 "Return a section of LIST, from START to END.
20669 Counting starts at 1."
20670 (let (rtn (c start))
20671 (setq list (nthcdr (1- start) list))
20672 (while (and list (<= c end))
20673 (push (pop list) rtn)
20674 (setq c (1+ c)))
20675 (nreverse rtn)))
20677 (defun org-find-base-buffer-visiting (file)
20678 "Like `find-buffer-visiting' but always return the base buffer and
20679 not an indirect buffer."
20680 (let ((buf (or (get-file-buffer file)
20681 (find-buffer-visiting file))))
20682 (if buf
20683 (or (buffer-base-buffer buf) buf)
20684 nil)))
20686 (defun org-image-file-name-regexp (&optional extensions)
20687 "Return regexp matching the file names of images.
20688 If EXTENSIONS is given, only match these."
20689 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20690 (image-file-name-regexp)
20691 (let ((image-file-name-extensions
20692 (or extensions
20693 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20694 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20695 (concat "\\."
20696 (regexp-opt (nconc (mapcar 'upcase
20697 image-file-name-extensions)
20698 image-file-name-extensions)
20700 "\\'"))))
20702 (defun org-file-image-p (file &optional extensions)
20703 "Return non-nil if FILE is an image."
20704 (save-match-data
20705 (string-match (org-image-file-name-regexp extensions) file)))
20707 (defun org-get-cursor-date ()
20708 "Return the date at cursor in as a time.
20709 This works in the calendar and in the agenda, anywhere else it just
20710 returns the current time."
20711 (let (date day defd)
20712 (cond
20713 ((eq major-mode 'calendar-mode)
20714 (setq date (calendar-cursor-to-date)
20715 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20716 ((eq major-mode 'org-agenda-mode)
20717 (setq day (get-text-property (point) 'day))
20718 (if day
20719 (setq date (calendar-gregorian-from-absolute day)
20720 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20721 (nth 2 date))))))
20722 (or defd (current-time))))
20724 (defun org-mark-subtree (&optional up)
20725 "Mark the current subtree.
20726 This puts point at the start of the current subtree, and mark at
20727 the end. If a numeric prefix UP is given, move up into the
20728 hierarchy of headlines by UP levels before marking the subtree."
20729 (interactive "P")
20730 (org-with-limited-levels
20731 (cond ((org-at-heading-p) (beginning-of-line))
20732 ((org-before-first-heading-p) (error "Not in a subtree"))
20733 (t (outline-previous-visible-heading 1))))
20734 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20735 (if (org-called-interactively-p 'any)
20736 (call-interactively 'org-mark-element)
20737 (org-mark-element)))
20739 ;;; Indentation
20741 (defun org-indent-line ()
20742 "Indent line depending on context."
20743 (interactive)
20744 (let* ((pos (point))
20745 (itemp (org-at-item-p))
20746 (case-fold-search t)
20747 (org-drawer-regexp (or org-drawer-regexp "\000"))
20748 (inline-task-p (and (featurep 'org-inlinetask)
20749 (org-inlinetask-in-task-p)))
20750 (inline-re (and inline-task-p
20751 (org-inlinetask-outline-regexp)))
20752 column)
20753 (if (and orgstruct-is-++ (eq pos (point)))
20754 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20755 (indent-according-to-mode))
20756 (beginning-of-line 1)
20757 (cond
20758 ;; Headings
20759 ((looking-at org-outline-regexp) (setq column 0))
20760 ;; Included files
20761 ((looking-at "#\\+include:") (setq column 0))
20762 ;; Footnote definition
20763 ((looking-at org-footnote-definition-re) (setq column 0))
20764 ;; Literal examples
20765 ((looking-at "[ \t]*:\\( \\|$\\)")
20766 (setq column (org-get-indentation))) ; do nothing
20767 ;; Lists
20768 ((ignore-errors (goto-char (org-in-item-p)))
20769 (setq column (if itemp
20770 (org-get-indentation)
20771 (org-list-item-body-column (point))))
20772 (goto-char pos))
20773 ;; Drawers
20774 ((and (looking-at "[ \t]*:END:")
20775 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20776 (save-excursion
20777 (goto-char (1- (match-beginning 1)))
20778 (setq column (current-column))))
20779 ;; Special blocks
20780 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20781 (save-excursion
20782 (re-search-backward
20783 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20784 (setq column (org-get-indentation (match-string 0))))
20785 ((and (not (looking-at "[ \t]*#\\+begin_"))
20786 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20787 (save-excursion
20788 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20789 (setq column
20790 (cond ((equal (downcase (match-string 1)) "src")
20791 ;; src blocks: let `org-edit-src-exit' handle them
20792 (org-get-indentation))
20793 ((equal (downcase (match-string 1)) "example")
20794 (max (org-get-indentation)
20795 (org-get-indentation (match-string 0))))
20797 (org-get-indentation (match-string 0))))))
20798 ;; This line has nothing special, look at the previous relevant
20799 ;; line to compute indentation
20801 (beginning-of-line 0)
20802 (while (and (not (bobp))
20803 (not (looking-at org-table-line-regexp))
20804 (not (looking-at org-drawer-regexp))
20805 ;; When point started in an inline task, do not move
20806 ;; above task starting line.
20807 (not (and inline-task-p (looking-at inline-re)))
20808 ;; Skip drawers, blocks, empty lines, verbatim,
20809 ;; comments, tables, footnotes definitions, lists,
20810 ;; inline tasks.
20811 (or (and (looking-at "[ \t]*:END:")
20812 (re-search-backward org-drawer-regexp nil t))
20813 (and (looking-at "[ \t]*#\\+end_")
20814 (re-search-backward "[ \t]*#\\+begin_"nil t))
20815 (looking-at "[ \t]*[\n:#|]")
20816 (looking-at org-footnote-definition-re)
20817 (and (ignore-errors (goto-char (org-in-item-p)))
20818 (goto-char
20819 (org-list-get-top-point (org-list-struct))))
20820 (and (not inline-task-p)
20821 (featurep 'org-inlinetask)
20822 (org-inlinetask-in-task-p)
20823 (or (org-inlinetask-goto-beginning) t))))
20824 (beginning-of-line 0))
20825 (cond
20826 ;; There was an heading above.
20827 ((looking-at "\\*+[ \t]+")
20828 (if (not org-adapt-indentation)
20829 (setq column 0)
20830 (goto-char (match-end 0))
20831 (setq column (current-column))))
20832 ;; A drawer had started and is unfinished
20833 ((looking-at org-drawer-regexp)
20834 (goto-char (1- (match-beginning 1)))
20835 (setq column (current-column)))
20836 ;; Else, nothing noticeable found: get indentation and go on.
20837 (t (setq column (org-get-indentation))))))
20838 ;; Now apply indentation and move cursor accordingly
20839 (goto-char pos)
20840 (if (<= (current-column) (current-indentation))
20841 (org-indent-line-to column)
20842 (save-excursion (org-indent-line-to column)))
20843 ;; Special polishing for properties, see `org-property-format'
20844 (setq column (current-column))
20845 (beginning-of-line 1)
20846 (if (looking-at
20847 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20848 (replace-match (concat (match-string 1)
20849 (format org-property-format
20850 (match-string 2) (match-string 3)))
20851 t t))
20852 (org-move-to-column column))))
20854 (defun org-indent-drawer ()
20855 "Indent the drawer at point."
20856 (interactive)
20857 (let ((p (point))
20858 (e (and (save-excursion (re-search-forward ":END:" nil t))
20859 (match-end 0)))
20860 (folded
20861 (save-excursion
20862 (end-of-line)
20863 (when (overlays-at (point))
20864 (member 'invisible (overlay-properties
20865 (car (overlays-at (point)))))))))
20866 (when folded (org-cycle))
20867 (indent-for-tab-command)
20868 (while (and (move-beginning-of-line 2) (< (point) e))
20869 (indent-for-tab-command))
20870 (goto-char p)
20871 (when folded (org-cycle)))
20872 (message "Drawer at point indented"))
20874 (defun org-indent-block ()
20875 "Indent the block at point."
20876 (interactive)
20877 (let ((p (point))
20878 (case-fold-search t)
20879 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20880 (match-end 0)))
20881 (folded
20882 (save-excursion
20883 (end-of-line)
20884 (when (overlays-at (point))
20885 (member 'invisible (overlay-properties
20886 (car (overlays-at (point)))))))))
20887 (when folded (org-cycle))
20888 (indent-for-tab-command)
20889 (while (and (move-beginning-of-line 2) (< (point) e))
20890 (indent-for-tab-command))
20891 (goto-char p)
20892 (when folded (org-cycle)))
20893 (message "Block at point indented"))
20895 (defun org-indent-region (start end)
20896 "Indent region."
20897 (interactive "r")
20898 (save-excursion
20899 (let ((line-end (org-current-line end)))
20900 (goto-char start)
20901 (while (< (org-current-line) line-end)
20902 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20903 (t (call-interactively 'org-indent-line)))
20904 (move-beginning-of-line 2)))))
20907 ;;; Filling
20909 ;; We use our own fill-paragraph and auto-fill functions.
20911 ;; `org-fill-paragraph' relies on adaptive filling and context
20912 ;; checking. Appropriate `fill-prefix' is computed with
20913 ;; `org-adaptive-fill-function'.
20915 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20916 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20917 ;; `org-adaptive-fill-function' value. Internally,
20918 ;; `org-comment-line-break-function' breaks the line.
20920 ;; `org-setup-filling' installs filling and auto-filling related
20921 ;; variables during `org-mode' initialization.
20923 (defun org-setup-filling ()
20924 (interactive)
20925 ;; Prevent auto-fill from inserting unwanted new items.
20926 (when (boundp 'fill-nobreak-predicate)
20927 (org-set-local
20928 'fill-nobreak-predicate
20929 (org-uniquify
20930 (append fill-nobreak-predicate
20931 '(org-fill-paragraph-separate-nobreak-p
20932 org-fill-line-break-nobreak-p)))))
20933 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20934 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
20935 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20936 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
20938 (defvar org-element-paragraph-separate) ; org-element.el
20939 (defun org-fill-paragraph-separate-nobreak-p ()
20940 "Non-nil when a line break at point would insert a new item."
20941 (looking-at (substring org-element-paragraph-separate 1)))
20943 (defun org-fill-line-break-nobreak-p ()
20944 "Non-nil when a line break at point would create an Org line break."
20945 (save-excursion
20946 (skip-chars-backward "[ \t]")
20947 (skip-chars-backward "\\\\")
20948 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
20950 (declare-function message-in-body-p "message" ())
20951 (defvar org-element--affiliated-re) ; From org-element.el
20952 (defun org-adaptive-fill-function ()
20953 "Compute a fill prefix for the current line.
20954 Return fill prefix, as a string, or nil if current line isn't
20955 meant to be filled."
20956 (org-with-wide-buffer
20957 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
20958 ;; FIXME: This is really the job of orgstruct++-mode
20959 (let* ((p (line-beginning-position))
20960 (element (save-excursion (beginning-of-line)
20961 (org-element-at-point)))
20962 (type (org-element-type element))
20963 (post-affiliated
20964 (save-excursion
20965 (goto-char (org-element-property :begin element))
20966 (while (looking-at org-element--affiliated-re) (forward-line))
20967 (point))))
20968 (unless (< p post-affiliated)
20969 (case type
20970 (comment (looking-at "[ \t]*# ?") (match-string 0))
20971 (footnote-definition "")
20972 ((item plain-list)
20973 (make-string (org-list-item-body-column post-affiliated) ? ))
20974 (paragraph
20975 ;; Fill prefix is usually the same as the current line,
20976 ;; except if the paragraph is at the beginning of an item.
20977 (let ((parent (org-element-property :parent element)))
20978 (cond ((eq (org-element-type parent) 'item)
20979 (make-string (org-list-item-body-column
20980 (org-element-property :begin parent))
20981 ? ))
20982 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20983 (match-string 0))
20984 (t ""))))
20985 (comment-block
20986 ;; Only fill contents if P is within block boundaries.
20987 (let* ((cbeg (save-excursion (goto-char post-affiliated)
20988 (forward-line)
20989 (point)))
20990 (cend (save-excursion
20991 (goto-char (org-element-property :end element))
20992 (skip-chars-backward " \r\t\n")
20993 (line-beginning-position))))
20994 (when (and (>= p cbeg) (< p cend))
20995 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
20996 (match-string 0)
20997 ""))))))))))
20999 (declare-function message-goto-body "message" ())
21000 (defvar message-cite-prefix-regexp) ; From message.el
21001 (defvar org-element-all-objects) ; From org-element.el
21002 (defun org-fill-paragraph (&optional justify)
21003 "Fill element at point, when applicable.
21005 This function only applies to comment blocks, comments, example
21006 blocks and paragraphs. Also, as a special case, re-align table
21007 when point is at one.
21009 If JUSTIFY is non-nil (interactively, with prefix argument),
21010 justify as well. If `sentence-end-double-space' is non-nil, then
21011 period followed by one space does not end a sentence, so don't
21012 break a line there. The variable `fill-column' controls the
21013 width for filling.
21015 For convenience, when point is at a plain list, an item or
21016 a footnote definition, try to fill the first paragraph within."
21017 (interactive)
21018 (if (and (derived-mode-p 'message-mode)
21019 (or (not (message-in-body-p))
21020 (save-excursion (move-beginning-of-line 1)
21021 (looking-at message-cite-prefix-regexp))))
21022 ;; First ensure filling is correct in message-mode.
21023 (let ((fill-paragraph-function
21024 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21025 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21026 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21027 (paragraph-separate
21028 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21029 (fill-paragraph nil))
21030 (save-excursion
21031 ;; Move to end of line in order to get the first paragraph
21032 ;; within a plain list or a footnote definition.
21033 (end-of-line)
21034 (let ((element (org-element-at-point)))
21035 ;; First check if point is in a blank line at the beginning of
21036 ;; the buffer. In that case, ignore filling.
21037 (if (< (point) (org-element-property :begin element)) t
21038 (case (org-element-type element)
21039 ;; Use major mode filling function is src blocks.
21040 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21041 ;; Align Org tables, leave table.el tables as-is.
21042 (table-row (org-table-align) t)
21043 (table
21044 (when (eq (org-element-property :type element) 'org)
21045 (org-table-align))
21047 (paragraph
21048 ;; Paragraphs may contain `line-break' type objects.
21049 (let ((beg (max (point-min)
21050 (org-element-property :contents-begin element)))
21051 (end (min (point-max)
21052 (org-element-property :contents-end element))))
21053 ;; Do nothing if point is at an affiliated keyword.
21054 (if (< (point) beg) t
21055 (when (derived-mode-p 'message-mode)
21056 ;; In `message-mode', do not fill following
21057 ;; citation in current paragraph nor text before
21058 ;; message body.
21059 (let ((body-start (save-excursion (message-goto-body))))
21060 (when body-start (setq beg (max body-start beg))))
21061 (when (save-excursion
21062 (re-search-forward
21063 (concat "^" message-cite-prefix-regexp) end t))
21064 (setq end (match-beginning 0))))
21065 ;; Fill paragraph, taking line breaks into
21066 ;; consideration. For that, slice the paragraph
21067 ;; using line breaks as separators, and fill the
21068 ;; parts in reverse order to avoid messing with
21069 ;; markers.
21070 (save-excursion
21071 (goto-char end)
21072 (mapc
21073 (lambda (pos)
21074 (fill-region-as-paragraph pos (point) justify)
21075 (goto-char pos))
21076 ;; Find the list of ending positions for line
21077 ;; breaks in the current paragraph. Add paragraph
21078 ;; beginning to include first slice.
21079 (nreverse
21080 (cons
21082 (org-element-map
21083 (org-element--parse-objects
21084 beg end nil org-element-all-objects)
21085 'line-break
21086 (lambda (lb) (org-element-property :end lb)))))))
21087 t)))
21088 ;; Contents of `comment-block' type elements should be
21089 ;; filled as plain text, but only if point is within block
21090 ;; markers.
21091 (comment-block
21092 (let* ((case-fold-search t)
21093 (beg (save-excursion
21094 (goto-char (org-element-property :begin element))
21095 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21096 (forward-line)
21097 (point)))
21098 (end (save-excursion
21099 (goto-char (org-element-property :end element))
21100 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21101 (line-beginning-position))))
21102 (when (and (>= (point) beg) (< (point) end))
21103 (fill-region-as-paragraph
21104 (save-excursion
21105 (end-of-line)
21106 (re-search-backward "^[ \t]*$" beg 'move)
21107 (line-beginning-position))
21108 (save-excursion
21109 (beginning-of-line)
21110 (re-search-forward "^[ \t]*$" end 'move)
21111 (line-beginning-position))
21112 justify)))
21114 ;; Fill comments.
21115 (comment (fill-comment-paragraph justify))
21116 ;; Ignore every other element.
21117 (otherwise t)))))))
21119 (defun org-auto-fill-function ()
21120 "Auto-fill function."
21121 ;; Check if auto-filling is meaningful.
21122 (let ((fc (current-fill-column)))
21123 (when (and fc (> (current-column) fc))
21124 (let* ((fill-prefix (org-adaptive-fill-function))
21125 ;; Enforce empty fill prefix, if required. Otherwise, it
21126 ;; will be computed again.
21127 (adaptive-fill-mode (not (equal fill-prefix ""))))
21128 (when fill-prefix (do-auto-fill))))))
21130 (defun org-comment-line-break-function (&optional soft)
21131 "Break line at point and indent, continuing comment if within one.
21132 The inserted newline is marked hard if variable
21133 `use-hard-newlines' is true, unless optional argument SOFT is
21134 non-nil."
21135 (if soft (insert-and-inherit ?\n) (newline 1))
21136 (save-excursion (forward-char -1) (delete-horizontal-space))
21137 (delete-horizontal-space)
21138 (indent-to-left-margin)
21139 (insert-before-markers-and-inherit fill-prefix))
21142 ;;; Comments
21144 ;; Org comments syntax is quite complex. It requires the entire line
21145 ;; to be just a comment. Also, even with the right syntax at the
21146 ;; beginning of line, some some elements (i.e. verse-block or
21147 ;; example-block) don't accept comments. Usual Emacs comment commands
21148 ;; cannot cope with those requirements. Therefore, Org replaces them.
21150 ;; Org still relies on `comment-dwim', but cannot trust
21151 ;; `comment-only-p'. So, `comment-region-function' and
21152 ;; `uncomment-region-function' both point
21153 ;; to`org-comment-or-uncomment-region'. Eventually,
21154 ;; `org-insert-comment' takes care of insertion of comments at the
21155 ;; beginning of line.
21157 ;; `org-setup-comments-handling' install comments related variables
21158 ;; during `org-mode' initialization.
21160 (defun org-setup-comments-handling ()
21161 (interactive)
21162 (org-set-local 'comment-use-syntax nil)
21163 (org-set-local 'comment-start "# ")
21164 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21165 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21166 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21167 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21169 (defun org-insert-comment ()
21170 "Insert an empty comment above current line.
21171 If the line is empty, insert comment at its beginning."
21172 (beginning-of-line)
21173 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21174 (org-indent-line)
21175 (insert "# "))
21177 (defvar comment-empty-lines) ; From newcomment.el.
21178 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21179 "Comment or uncomment each non-blank line in the region.
21180 Uncomment each non-blank line between BEG and END if it only
21181 contains commented lines. Otherwise, comment them."
21182 (save-restriction
21183 ;; Restrict region
21184 (narrow-to-region (save-excursion (goto-char beg)
21185 (skip-chars-forward " \r\t\n" end)
21186 (line-beginning-position))
21187 (save-excursion (goto-char end)
21188 (skip-chars-backward " \r\t\n" beg)
21189 (line-end-position)))
21190 (let ((uncommentp
21191 ;; UNCOMMENTP is non-nil when every non blank line between
21192 ;; BEG and END is a comment.
21193 (save-excursion
21194 (goto-char (point-min))
21195 (while (and (not (eobp))
21196 (let ((element (org-element-at-point)))
21197 (and (eq (org-element-type element) 'comment)
21198 (goto-char (min (point-max)
21199 (org-element-property
21200 :end element)))))))
21201 (eobp))))
21202 (if uncommentp
21203 ;; Only blank lines and comments in region: uncomment it.
21204 (save-excursion
21205 (goto-char (point-min))
21206 (while (not (eobp))
21207 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21208 (replace-match "" nil nil nil 1))
21209 (forward-line)))
21210 ;; Comment each line in region.
21211 (let ((min-indent (point-max)))
21212 ;; First find the minimum indentation across all lines.
21213 (save-excursion
21214 (goto-char (point-min))
21215 (while (and (not (eobp)) (not (zerop min-indent)))
21216 (unless (looking-at "[ \t]*$")
21217 (setq min-indent (min min-indent (current-indentation))))
21218 (forward-line)))
21219 ;; Then loop over all lines.
21220 (save-excursion
21221 (goto-char (point-min))
21222 (while (not (eobp))
21223 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21224 (org-move-to-column min-indent t)
21225 (insert comment-start))
21226 (forward-line))))))))
21229 ;;; Other stuff.
21231 (defun org-toggle-fixed-width-section (arg)
21232 "Toggle the fixed-width export.
21233 If there is no active region, the QUOTE keyword at the current headline is
21234 inserted or removed. When present, it causes the text between this headline
21235 and the next to be exported as fixed-width text, and unmodified.
21236 If there is an active region, this command adds or removes a colon as the
21237 first character of this line. If the first character of a line is a colon,
21238 this line is also exported in fixed-width font."
21239 (interactive "P")
21240 (let* ((cc 0)
21241 (regionp (org-region-active-p))
21242 (beg (if regionp (region-beginning) (point)))
21243 (end (if regionp (region-end)))
21244 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21245 (case-fold-search nil)
21246 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21247 off)
21248 (if regionp
21249 (save-excursion
21250 (goto-char beg)
21251 (setq cc (current-column))
21252 (beginning-of-line 1)
21253 (setq off (looking-at re))
21254 (while (> nlines 0)
21255 (setq nlines (1- nlines))
21256 (beginning-of-line 1)
21257 (cond
21258 (arg
21259 (org-move-to-column cc t)
21260 (insert ": \n")
21261 (forward-line -1))
21262 ((and off (looking-at re))
21263 (replace-match "" t t nil 1))
21264 ((not off) (org-move-to-column cc t) (insert ": ")))
21265 (forward-line 1)))
21266 (save-excursion
21267 (org-back-to-heading)
21268 (cond
21269 ((looking-at (format org-heading-keyword-regexp-format
21270 org-quote-string))
21271 (goto-char (match-end 1))
21272 (looking-at (concat " +" org-quote-string))
21273 (replace-match "" t t)
21274 (when (eolp) (insert " ")))
21275 ((looking-at org-outline-regexp)
21276 (goto-char (match-end 0))
21277 (insert org-quote-string " ")))))))
21279 (defun org-reftex-citation ()
21280 "Use reftex-citation to insert a citation into the buffer.
21281 This looks for a line like
21283 #+BIBLIOGRAPHY: foo plain option:-d
21285 and derives from it that foo.bib is the bibliography file relevant
21286 for this document. It then installs the necessary environment for RefTeX
21287 to work in this buffer and calls `reftex-citation' to insert a citation
21288 into the buffer.
21290 Export of such citations to both LaTeX and HTML is handled by the contributed
21291 package org-exp-bibtex by Taru Karttunen."
21292 (interactive)
21293 (let ((reftex-docstruct-symbol 'rds)
21294 (reftex-cite-format "\\cite{%l}")
21295 rds bib)
21296 (save-excursion
21297 (save-restriction
21298 (widen)
21299 (let ((case-fold-search t)
21300 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21301 (if (not (save-excursion
21302 (or (re-search-forward re nil t)
21303 (re-search-backward re nil t))))
21304 (error "No bibliography defined in file")
21305 (setq bib (concat (match-string 1) ".bib")
21306 rds (list (list 'bib bib)))))))
21307 (call-interactively 'reftex-citation)))
21309 ;;;; Functions extending outline functionality
21311 (defun org-beginning-of-line (&optional arg)
21312 "Go to the beginning of the current line. If that is invisible, continue
21313 to a visible line beginning. This makes the function of C-a more intuitive.
21314 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21315 first attempt, and only move to after the tags when the cursor is already
21316 beyond the end of the headline."
21317 (interactive "P")
21318 (let ((pos (point))
21319 (special (if (consp org-special-ctrl-a/e)
21320 (car org-special-ctrl-a/e)
21321 org-special-ctrl-a/e))
21322 refpos)
21323 (if (org-bound-and-true-p visual-line-mode)
21324 (beginning-of-visual-line 1)
21325 (beginning-of-line 1))
21326 (if (and arg (fboundp 'move-beginning-of-line))
21327 (call-interactively 'move-beginning-of-line)
21328 (if (bobp)
21330 (backward-char 1)
21331 (if (org-truely-invisible-p)
21332 (while (and (not (bobp)) (org-truely-invisible-p))
21333 (backward-char 1)
21334 (beginning-of-line 1))
21335 (forward-char 1))))
21336 (when special
21337 (cond
21338 ((and (looking-at org-complex-heading-regexp)
21339 (= (char-after (match-end 1)) ?\ ))
21340 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21341 (point-at-eol)))
21342 (goto-char
21343 (if (eq special t)
21344 (cond ((> pos refpos) refpos)
21345 ((= pos (point)) refpos)
21346 (t (point)))
21347 (cond ((> pos (point)) (point))
21348 ((not (eq last-command this-command)) (point))
21349 (t refpos)))))
21350 ((org-at-item-p)
21351 ;; Being at an item and not looking at an the item means point
21352 ;; was previously moved to beginning of a visual line, which
21353 ;; doesn't contain the item. Therefore, do nothing special,
21354 ;; just stay here.
21355 (when (looking-at org-list-full-item-re)
21356 ;; Set special position at first white space character after
21357 ;; bullet, and check-box, if any.
21358 (let ((after-bullet
21359 (let ((box (match-end 3)))
21360 (if (not box) (match-end 1)
21361 (let ((after (char-after box)))
21362 (if (and after (= after ? )) (1+ box) box))))))
21363 ;; Special case: Move point to special position when
21364 ;; currently after it or at beginning of line.
21365 (if (eq special t)
21366 (when (or (> pos after-bullet) (= (point) pos))
21367 (goto-char after-bullet))
21368 ;; Reversed case: Move point to special position when
21369 ;; point was already at beginning of line and command is
21370 ;; repeated.
21371 (when (and (= (point) pos) (eq last-command this-command))
21372 (goto-char after-bullet))))))))
21373 (org-no-warnings
21374 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21376 (defun org-end-of-line (&optional arg)
21377 "Go to the end of the line.
21378 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21379 tags on the first attempt, and only move to after the tags when
21380 the cursor is already beyond the end of the headline."
21381 (interactive "P")
21382 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21383 org-special-ctrl-a/e))
21384 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21385 'end-of-visual-line)
21386 ((fboundp 'move-end-of-line) 'move-end-of-line)
21387 (t 'end-of-line))))
21388 (if (or (not special) arg) (call-interactively move-fun)
21389 (let* ((element (save-excursion (beginning-of-line)
21390 (org-element-at-point)))
21391 (type (org-element-type element)))
21392 (cond
21393 ((memq type '(headline inlinetask))
21394 (let ((pos (point)))
21395 (beginning-of-line 1)
21396 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21397 (if (eq special t)
21398 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21399 (goto-char (match-beginning 1))
21400 (goto-char (match-end 0)))
21401 (if (or (< pos (match-end 0))
21402 (not (eq this-command last-command)))
21403 (goto-char (match-end 0))
21404 (goto-char (match-beginning 1))))
21405 (call-interactively move-fun))))
21406 ((org-element-property :hiddenp element)
21407 ;; If element is hidden, `move-end-of-line' would put point
21408 ;; after it. Use `end-of-line' to stay on current line.
21409 (call-interactively 'end-of-line))
21410 (t (call-interactively move-fun)))))
21411 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21413 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21414 (define-key org-mode-map "\C-e" 'org-end-of-line)
21416 (defun org-backward-sentence (&optional arg)
21417 "Go to beginning of sentence, or beginning of table field.
21418 This will call `backward-sentence' or `org-table-beginning-of-field',
21419 depending on context."
21420 (interactive "P")
21421 (cond
21422 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21423 (t (call-interactively 'backward-sentence))))
21425 (defun org-forward-sentence (&optional arg)
21426 "Go to end of sentence, or end of table field.
21427 This will call `forward-sentence' or `org-table-end-of-field',
21428 depending on context."
21429 (interactive "P")
21430 (cond
21431 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21432 (t (call-interactively 'forward-sentence))))
21434 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21435 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21437 (defun org-kill-line (&optional arg)
21438 "Kill line, to tags or end of line."
21439 (interactive "P")
21440 (cond
21441 ((or (not org-special-ctrl-k)
21442 (bolp)
21443 (not (org-at-heading-p)))
21444 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21445 org-ctrl-k-protect-subtree)
21446 (if (or (eq org-ctrl-k-protect-subtree 'error)
21447 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21448 (error "C-k aborted - would kill hidden subtree")))
21449 (call-interactively
21450 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21451 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21452 (kill-region (point) (match-beginning 1))
21453 (org-set-tags nil t))
21454 (t (kill-region (point) (point-at-eol)))))
21456 (define-key org-mode-map "\C-k" 'org-kill-line)
21458 (defun org-yank (&optional arg)
21459 "Yank. If the kill is a subtree, treat it specially.
21460 This command will look at the current kill and check if is a single
21461 subtree, or a series of subtrees[1]. If it passes the test, and if the
21462 cursor is at the beginning of a line or after the stars of a currently
21463 empty headline, then the yank is handled specially. How exactly depends
21464 on the value of the following variables, both set by default.
21466 org-yank-folded-subtrees
21467 When set, the subtree(s) will be folded after insertion, but only
21468 if doing so would now swallow text after the yanked text.
21470 org-yank-adjusted-subtrees
21471 When set, the subtree will be promoted or demoted in order to
21472 fit into the local outline tree structure, which means that the level
21473 will be adjusted so that it becomes the smaller one of the two
21474 *visible* surrounding headings.
21476 Any prefix to this command will cause `yank' to be called directly with
21477 no special treatment. In particular, a simple \\[universal-argument] prefix \
21478 will just
21479 plainly yank the text as it is.
21481 \[1] The test checks if the first non-white line is a heading
21482 and if there are no other headings with fewer stars."
21483 (interactive "P")
21484 (org-yank-generic 'yank arg))
21486 (defun org-yank-generic (command arg)
21487 "Perform some yank-like command.
21489 This function implements the behavior described in the `org-yank'
21490 documentation. However, it has been generalized to work for any
21491 interactive command with similar behavior."
21493 ;; pretend to be command COMMAND
21494 (setq this-command command)
21496 (if arg
21497 (call-interactively command)
21499 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21500 (and (org-kill-is-subtree-p)
21501 (or (bolp)
21502 (and (looking-at "[ \t]*$")
21503 (string-match
21504 "\\`\\*+\\'"
21505 (buffer-substring (point-at-bol) (point)))))))
21506 swallowp)
21507 (cond
21508 ((and subtreep org-yank-folded-subtrees)
21509 (let ((beg (point))
21510 end)
21511 (if (and subtreep org-yank-adjusted-subtrees)
21512 (org-paste-subtree nil nil 'for-yank)
21513 (call-interactively command))
21515 (setq end (point))
21516 (goto-char beg)
21517 (when (and (bolp) subtreep
21518 (not (setq swallowp
21519 (org-yank-folding-would-swallow-text beg end))))
21520 (org-with-limited-levels
21521 (or (looking-at org-outline-regexp)
21522 (re-search-forward org-outline-regexp-bol end t))
21523 (while (and (< (point) end) (looking-at org-outline-regexp))
21524 (hide-subtree)
21525 (org-cycle-show-empty-lines 'folded)
21526 (condition-case nil
21527 (outline-forward-same-level 1)
21528 (error (goto-char end))))))
21529 (when swallowp
21530 (message
21531 "Inserted text not folded because that would swallow text"))
21533 (goto-char end)
21534 (skip-chars-forward " \t\n\r")
21535 (beginning-of-line 1)
21536 (push-mark beg 'nomsg)))
21537 ((and subtreep org-yank-adjusted-subtrees)
21538 (let ((beg (point-at-bol)))
21539 (org-paste-subtree nil nil 'for-yank)
21540 (push-mark beg 'nomsg)))
21542 (call-interactively command))))))
21544 (defun org-yank-folding-would-swallow-text (beg end)
21545 "Would hide-subtree at BEG swallow any text after END?"
21546 (let (level)
21547 (org-with-limited-levels
21548 (save-excursion
21549 (goto-char beg)
21550 (when (or (looking-at org-outline-regexp)
21551 (re-search-forward org-outline-regexp-bol end t))
21552 (setq level (org-outline-level)))
21553 (goto-char end)
21554 (skip-chars-forward " \t\r\n\v\f")
21555 (if (or (eobp)
21556 (and (bolp) (looking-at org-outline-regexp)
21557 (<= (org-outline-level) level)))
21558 nil ; Nothing would be swallowed
21559 t))))) ; something would swallow
21561 (define-key org-mode-map "\C-y" 'org-yank)
21563 (defun org-truely-invisible-p ()
21564 "Check if point is at a character currently not visible.
21565 This version does not only check the character property, but also
21566 `visible-mode'."
21567 ;; Early versions of noutline don't have `outline-invisible-p'.
21568 (if (org-bound-and-true-p visible-mode)
21570 (outline-invisible-p)))
21572 (defun org-invisible-p2 ()
21573 "Check if point is at a character currently not visible."
21574 (save-excursion
21575 (if (and (eolp) (not (bobp))) (backward-char 1))
21576 ;; Early versions of noutline don't have `outline-invisible-p'.
21577 (outline-invisible-p)))
21579 (defun org-back-to-heading (&optional invisible-ok)
21580 "Call `outline-back-to-heading', but provide a better error message."
21581 (condition-case nil
21582 (outline-back-to-heading invisible-ok)
21583 (error (error "Before first headline at position %d in buffer %s"
21584 (point) (current-buffer)))))
21586 (defun org-before-first-heading-p ()
21587 "Before first heading?"
21588 (save-excursion
21589 (end-of-line)
21590 (null (re-search-backward org-outline-regexp-bol nil t))))
21592 (defun org-at-heading-p (&optional ignored)
21593 (outline-on-heading-p t))
21594 ;; Compatibility alias with Org versions < 7.8.03
21595 (defalias 'org-on-heading-p 'org-at-heading-p)
21597 (defun org-at-comment-p nil
21598 "Is cursor in a line starting with a # character?"
21599 (save-excursion
21600 (beginning-of-line)
21601 (looking-at "^#")))
21603 (defun org-at-drawer-p nil
21604 "Is cursor at a drawer keyword?"
21605 (save-excursion
21606 (move-beginning-of-line 1)
21607 (looking-at org-drawer-regexp)))
21609 (defun org-at-block-p nil
21610 "Is cursor at a block keyword?"
21611 (save-excursion
21612 (move-beginning-of-line 1)
21613 (looking-at org-block-regexp)))
21615 (defun org-point-at-end-of-empty-headline ()
21616 "If point is at the end of an empty headline, return t, else nil.
21617 If the heading only contains a TODO keyword, it is still still considered
21618 empty."
21619 (and (looking-at "[ \t]*$")
21620 (when org-todo-line-regexp
21621 (save-excursion
21622 (beginning-of-line 1)
21623 (let ((case-fold-search nil))
21624 (looking-at org-todo-line-regexp)
21625 (string= (match-string 3) ""))))))
21627 (defun org-at-heading-or-item-p ()
21628 (or (org-at-heading-p) (org-at-item-p)))
21630 (defun org-at-target-p ()
21631 (or (org-in-regexp org-radio-target-regexp)
21632 (org-in-regexp org-target-regexp)))
21633 ;; Compatibility alias with Org versions < 7.8.03
21634 (defalias 'org-on-target-p 'org-at-target-p)
21636 (defun org-up-heading-all (arg)
21637 "Move to the heading line of which the present line is a subheading.
21638 This function considers both visible and invisible heading lines.
21639 With argument, move up ARG levels."
21640 (if (fboundp 'outline-up-heading-all)
21641 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21642 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21644 (defun org-up-heading-safe ()
21645 "Move to the heading line of which the present line is a subheading.
21646 This version will not throw an error. It will return the level of the
21647 headline found, or nil if no higher level is found.
21649 Also, this function will be a lot faster than `outline-up-heading',
21650 because it relies on stars being the outline starters. This can really
21651 make a significant difference in outlines with very many siblings."
21652 (let (start-level re)
21653 (org-back-to-heading t)
21654 (setq start-level (funcall outline-level))
21655 (if (equal start-level 1)
21657 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21658 (if (re-search-backward re nil t)
21659 (funcall outline-level)))))
21661 (defun org-first-sibling-p ()
21662 "Is this heading the first child of its parents?"
21663 (interactive)
21664 (let ((re org-outline-regexp-bol)
21665 level l)
21666 (unless (org-at-heading-p t)
21667 (error "Not at a heading"))
21668 (setq level (funcall outline-level))
21669 (save-excursion
21670 (if (not (re-search-backward re nil t))
21672 (setq l (funcall outline-level))
21673 (< l level)))))
21675 (defun org-goto-sibling (&optional previous)
21676 "Goto the next sibling, even if it is invisible.
21677 When PREVIOUS is set, go to the previous sibling instead. Returns t
21678 when a sibling was found. When none is found, return nil and don't
21679 move point."
21680 (let ((fun (if previous 're-search-backward 're-search-forward))
21681 (pos (point))
21682 (re org-outline-regexp-bol)
21683 level l)
21684 (when (condition-case nil (org-back-to-heading t) (error nil))
21685 (setq level (funcall outline-level))
21686 (catch 'exit
21687 (or previous (forward-char 1))
21688 (while (funcall fun re nil t)
21689 (setq l (funcall outline-level))
21690 (when (< l level) (goto-char pos) (throw 'exit nil))
21691 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21692 (goto-char pos)
21693 nil))))
21695 (defun org-show-siblings ()
21696 "Show all siblings of the current headline."
21697 (save-excursion
21698 (while (org-goto-sibling) (org-flag-heading nil)))
21699 (save-excursion
21700 (while (org-goto-sibling 'previous)
21701 (org-flag-heading nil))))
21703 (defun org-goto-first-child ()
21704 "Goto the first child, even if it is invisible.
21705 Return t when a child was found. Otherwise don't move point and
21706 return nil."
21707 (let (level (pos (point)) (re org-outline-regexp-bol))
21708 (when (condition-case nil (org-back-to-heading t) (error nil))
21709 (setq level (outline-level))
21710 (forward-char 1)
21711 (if (and (re-search-forward re nil t) (> (outline-level) level))
21712 (progn (goto-char (match-beginning 0)) t)
21713 (goto-char pos) nil))))
21715 (defun org-show-hidden-entry ()
21716 "Show an entry where even the heading is hidden."
21717 (save-excursion
21718 (org-show-entry)))
21720 (defun org-flag-heading (flag &optional entry)
21721 "Flag the current heading. FLAG non-nil means make invisible.
21722 When ENTRY is non-nil, show the entire entry."
21723 (save-excursion
21724 (org-back-to-heading t)
21725 ;; Check if we should show the entire entry
21726 (if entry
21727 (progn
21728 (org-show-entry)
21729 (save-excursion
21730 (and (outline-next-heading)
21731 (org-flag-heading nil))))
21732 (outline-flag-region (max (point-min) (1- (point)))
21733 (save-excursion (outline-end-of-heading) (point))
21734 flag))))
21736 (defun org-get-next-sibling ()
21737 "Move to next heading of the same level, and return point.
21738 If there is no such heading, return nil.
21739 This is like outline-next-sibling, but invisible headings are ok."
21740 (let ((level (funcall outline-level)))
21741 (outline-next-heading)
21742 (while (and (not (eobp)) (> (funcall outline-level) level))
21743 (outline-next-heading))
21744 (if (or (eobp) (< (funcall outline-level) level))
21746 (point))))
21748 (defun org-get-last-sibling ()
21749 "Move to previous heading of the same level, and return point.
21750 If there is no such heading, return nil."
21751 (let ((opoint (point))
21752 (level (funcall outline-level)))
21753 (outline-previous-heading)
21754 (when (and (/= (point) opoint) (outline-on-heading-p t))
21755 (while (and (> (funcall outline-level) level)
21756 (not (bobp)))
21757 (outline-previous-heading))
21758 (if (< (funcall outline-level) level)
21760 (point)))))
21762 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21763 "Goto to the end of a subtree."
21764 ;; This contains an exact copy of the original function, but it uses
21765 ;; `org-back-to-heading', to make it work also in invisible
21766 ;; trees. And is uses an invisible-ok argument.
21767 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21768 ;; Furthermore, when used inside Org, finding the end of a large subtree
21769 ;; with many children and grandchildren etc, this can be much faster
21770 ;; than the outline version.
21771 (org-back-to-heading invisible-ok)
21772 (let ((first t)
21773 (level (funcall outline-level)))
21774 (if (and (derived-mode-p 'org-mode) (< level 1000))
21775 ;; A true heading (not a plain list item), in Org-mode
21776 ;; This means we can easily find the end by looking
21777 ;; only for the right number of stars. Using a regexp to do
21778 ;; this is so much faster than using a Lisp loop.
21779 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21780 (forward-char 1)
21781 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21782 ;; something else, do it the slow way
21783 (while (and (not (eobp))
21784 (or first (> (funcall outline-level) level)))
21785 (setq first nil)
21786 (outline-next-heading)))
21787 (unless to-heading
21788 (if (memq (preceding-char) '(?\n ?\^M))
21789 (progn
21790 ;; Go to end of line before heading
21791 (forward-char -1)
21792 (if (memq (preceding-char) '(?\n ?\^M))
21793 ;; leave blank line before heading
21794 (forward-char -1))))))
21795 (point))
21797 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21798 "Use Org version in org-mode, for dramatic speed-up."
21799 (if (derived-mode-p 'org-mode)
21800 (progn
21801 (org-end-of-subtree nil t)
21802 (unless (eobp) (backward-char 1)))
21803 ad-do-it))
21805 (defun org-end-of-meta-data-and-drawers ()
21806 "Jump to the first text after meta data and drawers in the current entry.
21807 This will move over empty lines, lines with planning time stamps,
21808 clocking lines, and drawers."
21809 (org-back-to-heading t)
21810 (let ((end (save-excursion (outline-next-heading) (point)))
21811 (re (concat "\\(" org-drawer-regexp "\\)"
21812 "\\|" "[ \t]*" org-keyword-time-regexp)))
21813 (forward-line 1)
21814 (while (re-search-forward re end t)
21815 (if (not (match-end 1))
21816 ;; empty or planning line
21817 (forward-line 1)
21818 ;; a drawer, find the end
21819 (re-search-forward "^[ \t]*:END:" end 'move)
21820 (forward-line 1)))
21821 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21822 (point)))
21824 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21825 "Move forward to the arg'th subheading at same level as this one.
21826 Stop at the first and last subheadings of a superior heading.
21827 Normally this only looks at visible headings, but when INVISIBLE-OK is
21828 non-nil it will also look at invisible ones."
21829 (interactive "p")
21830 (org-back-to-heading invisible-ok)
21831 (org-at-heading-p)
21832 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21833 (re (format "^\\*\\{1,%d\\} " level))
21835 (forward-char 1)
21836 (while (> arg 0)
21837 (while (and (re-search-forward re nil 'move)
21838 (setq l (- (match-end 0) (match-beginning 0) 1))
21839 (= l level)
21840 (not invisible-ok)
21841 (progn (backward-char 1) (outline-invisible-p)))
21842 (if (< l level) (setq arg 1)))
21843 (setq arg (1- arg)))
21844 (beginning-of-line 1)))
21846 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21847 "Move backward to the arg'th subheading at same level as this one.
21848 Stop at the first and last subheadings of a superior heading."
21849 (interactive "p")
21850 (org-back-to-heading)
21851 (org-at-heading-p)
21852 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21853 (re (format "^\\*\\{1,%d\\} " level))
21855 (while (> arg 0)
21856 (while (and (re-search-backward re nil 'move)
21857 (setq l (- (match-end 0) (match-beginning 0) 1))
21858 (= l level)
21859 (not invisible-ok)
21860 (outline-invisible-p))
21861 (if (< l level) (setq arg 1)))
21862 (setq arg (1- arg)))))
21864 (defun org-forward-element ()
21865 "Move forward by one element.
21866 Move to the next element at the same level, when possible."
21867 (interactive)
21868 (cond ((eobp) (error "Cannot move further down"))
21869 ((org-with-limited-levels (org-at-heading-p))
21870 (let ((origin (point)))
21871 (org-forward-heading-same-level 1)
21872 (unless (org-with-limited-levels (org-at-heading-p))
21873 (goto-char origin)
21874 (error "Cannot move further down"))))
21876 (let* ((elem (org-element-at-point))
21877 (end (org-element-property :end elem))
21878 (parent (org-element-property :parent elem)))
21879 (if (and parent (= (org-element-property :contents-end parent) end))
21880 (goto-char (org-element-property :end parent))
21881 (goto-char end))))))
21883 (defun org-backward-element ()
21884 "Move backward by one element.
21885 Move to the previous element at the same level, when possible."
21886 (interactive)
21887 (cond ((bobp) (error "Cannot move further up"))
21888 ((org-with-limited-levels (org-at-heading-p))
21889 ;; At an headline, move to the previous one, if any, or stay
21890 ;; here.
21891 (let ((origin (point)))
21892 (org-backward-heading-same-level 1)
21893 (unless (org-with-limited-levels (org-at-heading-p))
21894 (goto-char origin)
21895 (error "Cannot move further up"))))
21897 (let* ((trail (org-element-at-point 'keep-trail))
21898 (elem (car trail))
21899 (prev-elem (nth 1 trail))
21900 (beg (org-element-property :begin elem)))
21901 (cond
21902 ;; Move to beginning of current element if point isn't
21903 ;; there already.
21904 ((/= (point) beg) (goto-char beg))
21905 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21906 ((org-before-first-heading-p) (goto-char (point-min)))
21907 (t (org-back-to-heading)))))))
21909 (defun org-up-element ()
21910 "Move to upper element."
21911 (interactive)
21912 (if (org-with-limited-levels (org-at-heading-p))
21913 (unless (org-up-heading-safe) (error "No surrounding element"))
21914 (let* ((elem (org-element-at-point))
21915 (parent (org-element-property :parent elem)))
21916 (if parent (goto-char (org-element-property :begin parent))
21917 (if (org-with-limited-levels (org-before-first-heading-p))
21918 (error "No surrounding element")
21919 (org-with-limited-levels (org-back-to-heading)))))))
21921 (defvar org-element-greater-elements)
21922 (defun org-down-element ()
21923 "Move to inner element."
21924 (interactive)
21925 (let ((element (org-element-at-point)))
21926 (cond
21927 ((memq (org-element-type element) '(plain-list table))
21928 (goto-char (org-element-property :contents-begin element))
21929 (forward-char))
21930 ((memq (org-element-type element) org-element-greater-elements)
21931 ;; If contents are hidden, first disclose them.
21932 (when (org-element-property :hiddenp element) (org-cycle))
21933 (goto-char (or (org-element-property :contents-begin element)
21934 (error "No content for this element"))))
21935 (t (error "No inner element")))))
21937 (defun org-drag-element-backward ()
21938 "Move backward element at point."
21939 (interactive)
21940 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
21941 (let* ((trail (org-element-at-point 'keep-trail))
21942 (elem (car trail))
21943 (prev-elem (nth 1 trail)))
21944 ;; Error out if no previous element or previous element is
21945 ;; a parent of the current one.
21946 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
21947 (error "Cannot drag element backward")
21948 (let ((pos (point)))
21949 (org-element-swap-A-B prev-elem elem)
21950 (goto-char (+ (org-element-property :begin prev-elem)
21951 (- pos (org-element-property :begin elem)))))))))
21953 (defun org-drag-element-forward ()
21954 "Move forward element at point."
21955 (interactive)
21956 (let* ((pos (point))
21957 (elem (org-element-at-point)))
21958 (when (= (point-max) (org-element-property :end elem))
21959 (error "Cannot drag element forward"))
21960 (goto-char (org-element-property :end elem))
21961 (let ((next-elem (org-element-at-point)))
21962 (when (or (org-element-nested-p elem next-elem)
21963 (and (eq (org-element-type next-elem) 'headline)
21964 (not (eq (org-element-type elem) 'headline))))
21965 (goto-char pos)
21966 (error "Cannot drag element forward"))
21967 ;; Compute new position of point: it's shifted by NEXT-ELEM
21968 ;; body's length (without final blanks) and by the length of
21969 ;; blanks between ELEM and NEXT-ELEM.
21970 (let ((size-next (- (save-excursion
21971 (goto-char (org-element-property :end next-elem))
21972 (skip-chars-backward " \r\t\n")
21973 (forward-line)
21974 ;; Small correction if buffer doesn't end
21975 ;; with a newline character.
21976 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
21977 (org-element-property :begin next-elem)))
21978 (size-blank (- (org-element-property :end elem)
21979 (save-excursion
21980 (goto-char (org-element-property :end elem))
21981 (skip-chars-backward " \r\t\n")
21982 (forward-line)
21983 (point)))))
21984 (org-element-swap-A-B elem next-elem)
21985 (goto-char (+ pos size-next size-blank))))))
21987 (defun org-mark-element ()
21988 "Put point at beginning of this element, mark at end.
21990 Interactively, if this command is repeated or (in Transient Mark
21991 mode) if the mark is active, it marks the next element after the
21992 ones already marked."
21993 (interactive)
21994 (let (deactivate-mark)
21995 (if (and (org-called-interactively-p 'any)
21996 (or (and (eq last-command this-command) (mark t))
21997 (and transient-mark-mode mark-active)))
21998 (set-mark
21999 (save-excursion
22000 (goto-char (mark))
22001 (goto-char (org-element-property :end (org-element-at-point)))))
22002 (let ((element (org-element-at-point)))
22003 (end-of-line)
22004 (push-mark (org-element-property :end element) t t)
22005 (goto-char (org-element-property :begin element))))))
22007 (defun org-narrow-to-element ()
22008 "Narrow buffer to current element."
22009 (interactive)
22010 (let ((elem (org-element-at-point)))
22011 (cond
22012 ((eq (car elem) 'headline)
22013 (narrow-to-region
22014 (org-element-property :begin elem)
22015 (org-element-property :end elem)))
22016 ((memq (car elem) org-element-greater-elements)
22017 (narrow-to-region
22018 (org-element-property :contents-begin elem)
22019 (org-element-property :contents-end elem)))
22021 (narrow-to-region
22022 (org-element-property :begin elem)
22023 (org-element-property :end elem))))))
22025 (defun org-transpose-element ()
22026 "Transpose current and previous elements, keeping blank lines between.
22027 Point is moved after both elements."
22028 (interactive)
22029 (org-skip-whitespace)
22030 (let ((end (org-element-property :end (org-element-at-point))))
22031 (org-drag-element-backward)
22032 (goto-char end)))
22034 (defun org-unindent-buffer ()
22035 "Un-indent the visible part of the buffer.
22036 Relative indentation (between items, inside blocks, etc.) isn't
22037 modified."
22038 (interactive)
22039 (unless (eq major-mode 'org-mode)
22040 (error "Cannot un-indent a buffer not in Org mode"))
22041 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22042 unindent-tree ; For byte-compiler.
22043 (unindent-tree
22044 (function
22045 (lambda (contents)
22046 (mapc
22047 (lambda (element)
22048 (if (memq (org-element-type element) '(headline section))
22049 (funcall unindent-tree (org-element-contents element))
22050 (save-excursion
22051 (save-restriction
22052 (narrow-to-region
22053 (org-element-property :begin element)
22054 (org-element-property :end element))
22055 (org-do-remove-indentation)))))
22056 (reverse contents))))))
22057 (funcall unindent-tree (org-element-contents parse-tree))))
22059 (defun org-show-subtree ()
22060 "Show everything after this heading at deeper levels."
22061 (interactive)
22062 (outline-flag-region
22063 (point)
22064 (save-excursion
22065 (org-end-of-subtree t t))
22066 nil))
22068 (defun org-show-entry ()
22069 "Show the body directly following this heading.
22070 Show the heading too, if it is currently invisible."
22071 (interactive)
22072 (save-excursion
22073 (condition-case nil
22074 (progn
22075 (org-back-to-heading t)
22076 (outline-flag-region
22077 (max (point-min) (1- (point)))
22078 (save-excursion
22079 (if (re-search-forward
22080 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22081 (match-beginning 1)
22082 (point-max)))
22083 nil)
22084 (org-cycle-hide-drawers 'children))
22085 (error nil))))
22087 (defun org-make-options-regexp (kwds &optional extra)
22088 "Make a regular expression for keyword lines."
22089 (concat
22090 "^#\\+\\("
22091 (mapconcat 'regexp-quote kwds "\\|")
22092 (if extra (concat "\\|" extra))
22093 "\\):[ \t]*\\(.*\\)"))
22095 ;; Make isearch reveal the necessary context
22096 (defun org-isearch-end ()
22097 "Reveal context after isearch exits."
22098 (when isearch-success ; only if search was successful
22099 (if (featurep 'xemacs)
22100 ;; Under XEmacs, the hook is run in the correct place,
22101 ;; we directly show the context.
22102 (org-show-context 'isearch)
22103 ;; In Emacs the hook runs *before* restoring the overlays.
22104 ;; So we have to use a one-time post-command-hook to do this.
22105 ;; (Emacs 22 has a special variable, see function `org-mode')
22106 (unless (and (boundp 'isearch-mode-end-hook-quit)
22107 isearch-mode-end-hook-quit)
22108 ;; Only when the isearch was not quitted.
22109 (org-add-hook 'post-command-hook 'org-isearch-post-command
22110 'append 'local)))))
22112 (defun org-isearch-post-command ()
22113 "Remove self from hook, and show context."
22114 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22115 (org-show-context 'isearch))
22118 ;;;; Integration with and fixes for other packages
22120 ;;; Imenu support
22122 (defvar org-imenu-markers nil
22123 "All markers currently used by Imenu.")
22124 (make-variable-buffer-local 'org-imenu-markers)
22126 (defun org-imenu-new-marker (&optional pos)
22127 "Return a new marker for use by Imenu, and remember the marker."
22128 (let ((m (make-marker)))
22129 (move-marker m (or pos (point)))
22130 (push m org-imenu-markers)
22133 (defun org-imenu-get-tree ()
22134 "Produce the index for Imenu."
22135 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22136 (setq org-imenu-markers nil)
22137 (let* ((n org-imenu-depth)
22138 (re (concat "^" (org-get-limited-outline-regexp)))
22139 (subs (make-vector (1+ n) nil))
22140 (last-level 0)
22141 m level head)
22142 (save-excursion
22143 (save-restriction
22144 (widen)
22145 (goto-char (point-max))
22146 (while (re-search-backward re nil t)
22147 (setq level (org-reduced-level (funcall outline-level)))
22148 (when (and (<= level n)
22149 (looking-at org-complex-heading-regexp))
22150 (setq head (org-link-display-format
22151 (org-match-string-no-properties 4))
22152 m (org-imenu-new-marker))
22153 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22154 (if (>= level last-level)
22155 (push (cons head m) (aref subs level))
22156 (push (cons head (aref subs (1+ level))) (aref subs level))
22157 (loop for i from (1+ level) to n do (aset subs i nil)))
22158 (setq last-level level)))))
22159 (aref subs 1)))
22161 (eval-after-load "imenu"
22162 '(progn
22163 (add-hook 'imenu-after-jump-hook
22164 (lambda ()
22165 (if (derived-mode-p 'org-mode)
22166 (org-show-context 'org-goto))))))
22168 (defun org-link-display-format (link)
22169 "Replace a link with either the description, or the link target
22170 if no description is present"
22171 (save-match-data
22172 (if (string-match org-bracket-link-analytic-regexp link)
22173 (replace-match (if (match-end 5)
22174 (match-string 5 link)
22175 (concat (match-string 1 link)
22176 (match-string 3 link)))
22177 nil t link)
22178 link)))
22180 (defun org-toggle-link-display ()
22181 "Toggle the literal or descriptive display of links."
22182 (interactive)
22183 (if org-descriptive-links
22184 (progn (org-remove-from-invisibility-spec '(org-link))
22185 (org-restart-font-lock)
22186 (setq org-descriptive-links nil))
22187 (progn (add-to-invisibility-spec '(org-link))
22188 (org-restart-font-lock)
22189 (setq org-descriptive-links t))))
22191 ;; Speedbar support
22193 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22194 "Overlay marking the agenda restriction line in speedbar.")
22195 (overlay-put org-speedbar-restriction-lock-overlay
22196 'face 'org-agenda-restriction-lock)
22197 (overlay-put org-speedbar-restriction-lock-overlay
22198 'help-echo "Agendas are currently limited to this item.")
22199 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22201 (defun org-speedbar-set-agenda-restriction ()
22202 "Restrict future agenda commands to the location at point in speedbar.
22203 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22204 (interactive)
22205 (require 'org-agenda)
22206 (let (p m tp np dir txt)
22207 (cond
22208 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22209 'org-imenu t))
22210 (setq m (get-text-property p 'org-imenu-marker))
22211 (with-current-buffer (marker-buffer m)
22212 (goto-char m)
22213 (org-agenda-set-restriction-lock 'subtree)))
22214 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22215 'speedbar-function 'speedbar-find-file))
22216 (setq tp (previous-single-property-change
22217 (1+ p) 'speedbar-function)
22218 np (next-single-property-change
22219 tp 'speedbar-function)
22220 dir (speedbar-line-directory)
22221 txt (buffer-substring-no-properties (or tp (point-min))
22222 (or np (point-max))))
22223 (with-current-buffer (find-file-noselect
22224 (let ((default-directory dir))
22225 (expand-file-name txt)))
22226 (unless (derived-mode-p 'org-mode)
22227 (error "Cannot restrict to non-Org-mode file"))
22228 (org-agenda-set-restriction-lock 'file)))
22229 (t (error "Don't know how to restrict Org-mode's agenda")))
22230 (move-overlay org-speedbar-restriction-lock-overlay
22231 (point-at-bol) (point-at-eol))
22232 (setq current-prefix-arg nil)
22233 (org-agenda-maybe-redo)))
22235 (eval-after-load "speedbar"
22236 '(progn
22237 (speedbar-add-supported-extension ".org")
22238 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22239 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22240 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22241 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22242 (add-hook 'speedbar-visiting-tag-hook
22243 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22245 ;;; Fixes and Hacks for problems with other packages
22247 ;; Make flyspell not check words in links, to not mess up our keymap
22248 (defun org-mode-flyspell-verify ()
22249 "Don't let flyspell put overlays at active buttons, or on
22250 {todo,all-time,additional-option-like}-keywords."
22251 (let ((pos (max (1- (point)) (point-min)))
22252 (word (thing-at-point 'word)))
22253 (and (not (get-text-property pos 'keymap))
22254 (not (get-text-property pos 'org-no-flyspell))
22255 (not (member word org-todo-keywords-1))
22256 (not (member word org-all-time-keywords))
22257 (not (member word org-options-keywords))
22258 (not (member word (mapcar 'car org-startup-options)))
22259 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22261 (defun org-remove-flyspell-overlays-in (beg end)
22262 "Remove flyspell overlays in region."
22263 (and (org-bound-and-true-p flyspell-mode)
22264 (fboundp 'flyspell-delete-region-overlays)
22265 (flyspell-delete-region-overlays beg end))
22266 (add-text-properties beg end '(org-no-flyspell t)))
22268 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22269 (eval-after-load "bookmark"
22270 '(if (boundp 'bookmark-after-jump-hook)
22271 ;; We can use the hook
22272 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22273 ;; Hook not available, use advice
22274 (defadvice bookmark-jump (after org-make-visible activate)
22275 "Make the position visible."
22276 (org-bookmark-jump-unhide))))
22278 ;; Make sure saveplace shows the location if it was hidden
22279 (eval-after-load "saveplace"
22280 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22281 "Make the position visible."
22282 (org-bookmark-jump-unhide)))
22284 ;; Make sure ecb shows the location if it was hidden
22285 (eval-after-load "ecb"
22286 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22287 "Make hierarchy visible when jumping into location from ECB tree buffer."
22288 (if (derived-mode-p 'org-mode)
22289 (org-show-context))))
22291 (defun org-bookmark-jump-unhide ()
22292 "Unhide the current position, to show the bookmark location."
22293 (and (derived-mode-p 'org-mode)
22294 (or (outline-invisible-p)
22295 (save-excursion (goto-char (max (point-min) (1- (point))))
22296 (outline-invisible-p)))
22297 (org-show-context 'bookmark-jump)))
22299 ;; Make session.el ignore our circular variable
22300 (eval-after-load "session"
22301 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22303 ;;;; Experimental code
22305 (defun org-closed-in-range ()
22306 "Sparse tree of items closed in a certain time range.
22307 Still experimental, may disappear in the future."
22308 (interactive)
22309 ;; Get the time interval from the user.
22310 (let* ((time1 (org-float-time
22311 (org-read-date nil 'to-time nil "Starting date: ")))
22312 (time2 (org-float-time
22313 (org-read-date nil 'to-time nil "End date:")))
22314 ;; callback function
22315 (callback (lambda ()
22316 (let ((time
22317 (org-float-time
22318 (apply 'encode-time
22319 (org-parse-time-string
22320 (match-string 1))))))
22321 ;; check if time in interval
22322 (and (>= time time1) (<= time time2))))))
22323 ;; make tree, check each match with the callback
22324 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22326 ;;;; Finish up
22328 (provide 'org)
22330 (run-hooks 'org-load-hook)
22332 ;;; org.el ends here