org.el: Fall back in interactive prompt when `org-make-link-description-function...
[org-mode/org-tableheadings.git] / lisp / org.el
blob8c8741bce4b945832952bfc9499a26c6a1d88da7
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol "^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias)
102 (unless (boundp 'calendar-view-holidays-initially-flag)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially))
105 (unless (boundp 'calendar-view-diary-initially-flag)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially))
108 (unless (boundp 'diary-fancy-buffer)
109 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
111 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
115 (declare-function org-at-clock-log-p "org-clock" ())
116 (declare-function org-clock-timestamps-up "org-clock" ())
117 (declare-function org-clock-timestamps-down "org-clock" ())
118 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
120 ;; load languages based on value of `org-babel-load-languages'
121 (defvar org-babel-load-languages)
122 ;;;###autoload
123 (defun org-babel-do-load-languages (sym value)
124 "Load the languages defined in `org-babel-load-languages'."
125 (set-default sym value)
126 (mapc (lambda (pair)
127 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
128 (if active
129 (progn
130 (require (intern (concat "ob-" lang))))
131 (progn
132 (funcall 'fmakunbound
133 (intern (concat "org-babel-execute:" lang)))
134 (funcall 'fmakunbound
135 (intern (concat "org-babel-expand-body:" lang)))))))
136 org-babel-load-languages))
138 (defcustom org-babel-load-languages '((emacs-lisp . t))
139 "Languages which can be evaluated in Org-mode buffers.
140 This list can be used to load support for any of the languages
141 below, note that each language will depend on a different set of
142 system executables and/or Emacs modes. When a language is
143 \"loaded\", then code blocks in that language can be evaluated
144 with `org-babel-execute-src-block' bound by default to C-c
145 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
146 be set to remove code block evaluation from the C-c C-c
147 keybinding. By default only Emacs Lisp (which has no
148 requirements) is loaded."
149 :group 'org-babel
150 :set 'org-babel-do-load-languages
151 :version "24.1"
152 :type '(alist :tag "Babel Languages"
153 :key-type
154 (choice
155 (const :tag "Awk" awk)
156 (const :tag "C" C)
157 (const :tag "R" R)
158 (const :tag "Asymptote" asymptote)
159 (const :tag "Calc" calc)
160 (const :tag "Clojure" clojure)
161 (const :tag "CSS" css)
162 (const :tag "Ditaa" ditaa)
163 (const :tag "Dot" dot)
164 (const :tag "Emacs Lisp" emacs-lisp)
165 (const :tag "Fortran" fortran)
166 (const :tag "Gnuplot" gnuplot)
167 (const :tag "Haskell" haskell)
168 (const :tag "IO" io)
169 (const :tag "Java" java)
170 (const :tag "Javascript" js)
171 (const :tag "LaTeX" latex)
172 (const :tag "Ledger" ledger)
173 (const :tag "Lilypond" lilypond)
174 (const :tag "Lisp" lisp)
175 (const :tag "Maxima" maxima)
176 (const :tag "Matlab" matlab)
177 (const :tag "Mscgen" mscgen)
178 (const :tag "Ocaml" ocaml)
179 (const :tag "Octave" octave)
180 (const :tag "Org" org)
181 (const :tag "Perl" perl)
182 (const :tag "Pico Lisp" picolisp)
183 (const :tag "PlantUML" plantuml)
184 (const :tag "Python" python)
185 (const :tag "Ruby" ruby)
186 (const :tag "Sass" sass)
187 (const :tag "Scala" scala)
188 (const :tag "Scheme" scheme)
189 (const :tag "Screen" screen)
190 (const :tag "Shell Script" sh)
191 (const :tag "Shen" shen)
192 (const :tag "Sql" sql)
193 (const :tag "Sqlite" sqlite))
194 :value-type (boolean :tag "Activate" :value t)))
196 ;;;; Customization variables
197 (defcustom org-clone-delete-id nil
198 "Remove ID property of clones of a subtree.
199 When non-nil, clones of a subtree don't inherit the ID property.
200 Otherwise they inherit the ID property with a new unique
201 identifier."
202 :type 'boolean
203 :version "24.1"
204 :group 'org-id)
206 ;;; Version
207 (require 'org-compat)
208 (org-check-version)
209 ;;;###autoload
210 (defun org-version (&optional here full message)
211 "Show the org-mode version in the echo area.
212 With prefix argument HERE, insert it at point.
213 When FULL is non-nil, use a verbose version string.
214 When MESSAGE is non-nil, display a message with the version."
215 (interactive "P")
216 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
217 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
218 (org-trash (or
219 (and (fboundp 'org-release) (fboundp 'org-git-version))
220 (load (concat org-dir "org-version.el")
221 'noerror 'nomessage 'nosuffix)))
222 (org-version (org-release))
223 (git-version (org-git-version))
224 (version (format "Org-mode version %s (%s @ %s)"
225 org-version
226 git-version
227 (if org-install-dir
228 (if (string= org-dir org-install-dir)
229 org-install-dir
230 (concat "mixed installation! " org-install-dir " and " org-dir))
231 "org-install.el can not be found!")))
232 (_version (if full version org-version)))
233 (if (org-called-interactively-p 'interactive)
234 (if here
235 (insert version)
236 (message version))
237 (if message (message _version))
238 _version)))
240 (defconst org-version (org-version))
242 ;;; Compatibility constants
244 ;;; The custom variables
246 (defgroup org nil
247 "Outline-based notes management and organizer."
248 :tag "Org"
249 :group 'outlines
250 :group 'calendar)
252 (defcustom org-mode-hook nil
253 "Mode hook for Org-mode, run after the mode was turned on."
254 :group 'org
255 :type 'hook)
257 (defcustom org-load-hook nil
258 "Hook that is run after org.el has been loaded."
259 :group 'org
260 :type 'hook)
262 (defcustom org-log-buffer-setup-hook nil
263 "Hook that is run after an Org log buffer is created."
264 :group 'org
265 :version "24.1"
266 :type 'hook)
268 (defvar org-modules) ; defined below
269 (defvar org-modules-loaded nil
270 "Have the modules been loaded already?")
272 (defun org-load-modules-maybe (&optional force)
273 "Load all extensions listed in `org-modules'."
274 (when (or force (not org-modules-loaded))
275 (mapc (lambda (ext)
276 (condition-case nil (require ext)
277 (error (message "Problems while trying to load feature `%s'" ext))))
278 org-modules)
279 (setq org-modules-loaded t)))
281 (defun org-set-modules (var value)
282 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
283 (set var value)
284 (when (featurep 'org)
285 (org-load-modules-maybe 'force)))
287 (when (org-bound-and-true-p org-modules)
288 (let ((a (member 'org-infojs org-modules)))
289 (and a (setcar a 'org-jsinfo))))
291 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
292 "Modules that should always be loaded together with org.el.
293 If a description starts with <C>, the file is not part of Emacs
294 and loading it will require that you have downloaded and properly installed
295 the org-mode distribution.
297 You can also use this system to load external packages (i.e. neither Org
298 core modules, nor modules from the CONTRIB directory). Just add symbols
299 to the end of the list. If the package is called org-xyz.el, then you need
300 to add the symbol `xyz', and the package must have a call to
302 (provide 'org-xyz)"
303 :group 'org
304 :set 'org-set-modules
305 :type
306 '(set :greedy t
307 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
308 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
309 (const :tag " crypt: Encryption of subtrees" org-crypt)
310 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
311 (const :tag " docview: Links to doc-view buffers" org-docview)
312 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
313 (const :tag " id: Global IDs for identifying entries" org-id)
314 (const :tag " info: Links to Info nodes" org-info)
315 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
316 (const :tag " habit: Track your consistency with habits" org-habit)
317 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
318 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
319 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
320 (const :tag " mew Links to Mew folders/messages" org-mew)
321 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
322 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
323 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
324 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
325 (const :tag " vm: Links to VM folders/messages" org-vm)
326 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
327 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
328 (const :tag " mouse: Additional mouse support" org-mouse)
329 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
331 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
332 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
333 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
334 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
335 (const :tag "C collector: Collect properties into tables" org-collector)
336 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
337 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
338 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
339 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
340 (const :tag "C eval: Include command output as text" org-eval)
341 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
342 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
343 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
344 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
345 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
347 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
349 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
350 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
351 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
352 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
353 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
354 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
355 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
356 (const :tag "C mtags: Support for muse-like tags" org-mtags)
357 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
358 (const :tag "C registry: A registry for Org-mode links" org-registry)
359 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
360 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
361 (const :tag "C secretary: Team management with org-mode" org-secretary)
362 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
363 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
364 (const :tag "C track: Keep up with Org-mode development" org-track)
365 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
366 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
367 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
369 (defcustom org-support-shift-select nil
370 "Non-nil means make shift-cursor commands select text when possible.
372 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
373 start selecting a region, or enlarge regions started in this way.
374 In Org-mode, in special contexts, these same keys are used for
375 other purposes, important enough to compete with shift selection.
376 Org tries to balance these needs by supporting `shift-select-mode'
377 outside these special contexts, under control of this variable.
379 The default of this variable is nil, to avoid confusing behavior. Shifted
380 cursor keys will then execute Org commands in the following contexts:
381 - on a headline, changing TODO state (left/right) and priority (up/down)
382 - on a time stamp, changing the time
383 - in a plain list item, changing the bullet type
384 - in a property definition line, switching between allowed values
385 - in the BEGIN line of a clock table (changing the time block).
386 Outside these contexts, the commands will throw an error.
388 When this variable is t and the cursor is not in a special
389 context, Org-mode will support shift-selection for making and
390 enlarging regions. To make this more effective, the bullet
391 cycling will no longer happen anywhere in an item line, but only
392 if the cursor is exactly on the bullet.
394 If you set this variable to the symbol `always', then the keys
395 will not be special in headlines, property lines, and item lines,
396 to make shift selection work there as well. If this is what you
397 want, you can use the following alternative commands: `C-c C-t'
398 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
399 can be used to switch TODO sets, `C-c -' to cycle item bullet
400 types, and properties can be edited by hand or in column view.
402 However, when the cursor is on a timestamp, shift-cursor commands
403 will still edit the time stamp - this is just too good to give up.
405 XEmacs user should have this variable set to nil, because
406 `shift-select-mode' is in Emacs 23 or later only."
407 :group 'org
408 :type '(choice
409 (const :tag "Never" nil)
410 (const :tag "When outside special context" t)
411 (const :tag "Everywhere except timestamps" always)))
413 (defcustom org-loop-over-headlines-in-active-region nil
414 "Shall some commands act upon headlines in the active region?
416 When set to `t', some commands will be performed in all headlines
417 within the active region.
419 When set to `start-level', some commands will be performed in all
420 headlines within the active region, provided that these headlines
421 are of the same level than the first one.
423 When set to a string, those commands will be performed on the
424 matching headlines within the active region. Such string must be
425 a tags/property/todo match as it is used in the agenda tags view.
427 The list of commands is: `org-schedule', `org-deadline',
428 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
429 `org-archive-to-archive-sibling'. The archiving commands skip
430 already archived entries."
431 :type '(choice (const :tag "Don't loop" nil)
432 (const :tag "All headlines in active region" t)
433 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
434 (string :tag "Tags/Property/Todo matcher"))
435 :version "24.1"
436 :group 'org-todo
437 :group 'org-archive)
439 (defgroup org-startup nil
440 "Options concerning startup of Org-mode."
441 :tag "Org Startup"
442 :group 'org)
444 (defcustom org-startup-folded t
445 "Non-nil means entering Org-mode will switch to OVERVIEW.
446 This can also be configured on a per-file basis by adding one of
447 the following lines anywhere in the buffer:
449 #+STARTUP: fold (or `overview', this is equivalent)
450 #+STARTUP: nofold (or `showall', this is equivalent)
451 #+STARTUP: content
452 #+STARTUP: showeverything"
453 :group 'org-startup
454 :type '(choice
455 (const :tag "nofold: show all" nil)
456 (const :tag "fold: overview" t)
457 (const :tag "content: all headlines" content)
458 (const :tag "show everything, even drawers" showeverything)))
460 (defcustom org-startup-truncated t
461 "Non-nil means entering Org-mode will set `truncate-lines'.
462 This is useful since some lines containing links can be very long and
463 uninteresting. Also tables look terrible when wrapped."
464 :group 'org-startup
465 :type 'boolean)
467 (defcustom org-startup-indented nil
468 "Non-nil means turn on `org-indent-mode' on startup.
469 This can also be configured on a per-file basis by adding one of
470 the following lines anywhere in the buffer:
472 #+STARTUP: indent
473 #+STARTUP: noindent"
474 :group 'org-structure
475 :type '(choice
476 (const :tag "Not" nil)
477 (const :tag "Globally (slow on startup in large files)" t)))
479 (defcustom org-use-sub-superscripts t
480 "Non-nil means interpret \"_\" and \"^\" for export.
481 When this option is turned on, you can use TeX-like syntax for sub- and
482 superscripts. Several characters after \"_\" or \"^\" will be
483 considered as a single item - so grouping with {} is normally not
484 needed. For example, the following things will be parsed as single
485 sub- or superscripts.
487 10^24 or 10^tau several digits will be considered 1 item.
488 10^-12 or 10^-tau a leading sign with digits or a word
489 x^2-y^3 will be read as x^2 - y^3, because items are
490 terminated by almost any nonword/nondigit char.
491 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
493 Still, ambiguity is possible - so when in doubt use {} to enclose the
494 sub/superscript. If you set this variable to the symbol `{}',
495 the braces are *required* in order to trigger interpretations as
496 sub/superscript. This can be helpful in documents that need \"_\"
497 frequently in plain text.
499 Not all export backends support this, but HTML does.
501 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
502 :group 'org-startup
503 :group 'org-export-translation
504 :version "24.1"
505 :type '(choice
506 (const :tag "Always interpret" t)
507 (const :tag "Only with braces" {})
508 (const :tag "Never interpret" nil)))
510 (if (fboundp 'defvaralias)
511 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
514 (defcustom org-startup-with-beamer-mode nil
515 "Non-nil means turn on `org-beamer-mode' on startup.
516 This can also be configured on a per-file basis by adding one of
517 the following lines anywhere in the buffer:
519 #+STARTUP: beamer"
520 :group 'org-startup
521 :version "24.1"
522 :type 'boolean)
524 (defcustom org-startup-align-all-tables nil
525 "Non-nil means align all tables when visiting a file.
526 This is useful when the column width in tables is forced with <N> cookies
527 in table fields. Such tables will look correct only after the first re-align.
528 This can also be configured on a per-file basis by adding one of
529 the following lines anywhere in the buffer:
530 #+STARTUP: align
531 #+STARTUP: noalign"
532 :group 'org-startup
533 :type 'boolean)
535 (defcustom org-startup-with-inline-images nil
536 "Non-nil means show inline images when loading a new Org file.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
539 #+STARTUP: inlineimages
540 #+STARTUP: noinlineimages"
541 :group 'org-startup
542 :version "24.1"
543 :type 'boolean)
545 (defcustom org-insert-mode-line-in-empty-file nil
546 "Non-nil means insert the first line setting Org-mode in empty files.
547 When the function `org-mode' is called interactively in an empty file, this
548 normally means that the file name does not automatically trigger Org-mode.
549 To ensure that the file will always be in Org-mode in the future, a
550 line enforcing Org-mode will be inserted into the buffer, if this option
551 has been set."
552 :group 'org-startup
553 :type 'boolean)
555 (defcustom org-replace-disputed-keys nil
556 "Non-nil means use alternative key bindings for some keys.
557 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
558 These keys are also used by other packages like shift-selection-mode'
559 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
560 If you want to use Org-mode together with one of these other modes,
561 or more generally if you would like to move some Org-mode commands to
562 other keys, set this variable and configure the keys with the variable
563 `org-disputed-keys'.
565 This option is only relevant at load-time of Org-mode, and must be set
566 *before* org.el is loaded. Changing it requires a restart of Emacs to
567 become effective."
568 :group 'org-startup
569 :type 'boolean)
571 (defcustom org-use-extra-keys nil
572 "Non-nil means use extra key sequence definitions for certain commands.
573 This happens automatically if you run XEmacs or if `window-system'
574 is nil. This variable lets you do the same manually. You must
575 set it before loading org.
577 Example: on Carbon Emacs 22 running graphically, with an external
578 keyboard on a Powerbook, the default way of setting M-left might
579 not work for either Alt or ESC. Setting this variable will make
580 it work for ESC."
581 :group 'org-startup
582 :type 'boolean)
584 (if (fboundp 'defvaralias)
585 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
587 (defcustom org-disputed-keys
588 '(([(shift up)] . [(meta p)])
589 ([(shift down)] . [(meta n)])
590 ([(shift left)] . [(meta -)])
591 ([(shift right)] . [(meta +)])
592 ([(control shift right)] . [(meta shift +)])
593 ([(control shift left)] . [(meta shift -)]))
594 "Keys for which Org-mode and other modes compete.
595 This is an alist, cars are the default keys, second element specifies
596 the alternative to use when `org-replace-disputed-keys' is t.
598 Keys can be specified in any syntax supported by `define-key'.
599 The value of this option takes effect only at Org-mode's startup,
600 therefore you'll have to restart Emacs to apply it after changing."
601 :group 'org-startup
602 :type 'alist)
604 (defun org-key (key)
605 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
606 Or return the original if not disputed.
607 Also apply the translations defined in `org-xemacs-key-equivalents'."
608 (when org-replace-disputed-keys
609 (let* ((nkey (key-description key))
610 (x (org-find-if (lambda (x)
611 (equal (key-description (car x)) nkey))
612 org-disputed-keys)))
613 (setq key (if x (cdr x) key))))
614 (when (featurep 'xemacs)
615 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
616 key)
618 (defun org-find-if (predicate seq)
619 (catch 'exit
620 (while seq
621 (if (funcall predicate (car seq))
622 (throw 'exit (car seq))
623 (pop seq)))))
625 (defun org-defkey (keymap key def)
626 "Define a key, possibly translated, as returned by `org-key'."
627 (define-key keymap (org-key key) def))
629 (defcustom org-ellipsis nil
630 "The ellipsis to use in the Org-mode outline.
631 When nil, just use the standard three dots. When a string, use that instead,
632 When a face, use the standard 3 dots, but with the specified face.
633 The change affects only Org-mode (which will then use its own display table).
634 Changing this requires executing `M-x org-mode' in a buffer to become
635 effective."
636 :group 'org-startup
637 :type '(choice (const :tag "Default" nil)
638 (face :tag "Face" :value org-warning)
639 (string :tag "String" :value "...#")))
641 (defvar org-display-table nil
642 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
644 (defgroup org-keywords nil
645 "Keywords in Org-mode."
646 :tag "Org Keywords"
647 :group 'org)
649 (defcustom org-deadline-string "DEADLINE:"
650 "String to mark deadline entries.
651 A deadline is this string, followed by a time stamp. Should be a word,
652 terminated by a colon. You can insert a schedule keyword and
653 a timestamp with \\[org-deadline].
654 Changes become only effective after restarting Emacs."
655 :group 'org-keywords
656 :type 'string)
658 (defcustom org-scheduled-string "SCHEDULED:"
659 "String to mark scheduled TODO entries.
660 A schedule is this string, followed by a time stamp. Should be a word,
661 terminated by a colon. You can insert a schedule keyword and
662 a timestamp with \\[org-schedule].
663 Changes become only effective after restarting Emacs."
664 :group 'org-keywords
665 :type 'string)
667 (defcustom org-closed-string "CLOSED:"
668 "String used as the prefix for timestamps logging closing a TODO entry."
669 :group 'org-keywords
670 :type 'string)
672 (defcustom org-clock-string "CLOCK:"
673 "String used as prefix for timestamps clocking work hours on an item."
674 :group 'org-keywords
675 :type 'string)
677 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
678 org-scheduled-string "\\|"
679 org-deadline-string "\\|"
680 org-closed-string "\\|"
681 org-clock-string "\\)")
682 "Matches a line with planning or clock info.")
684 (defcustom org-comment-string "COMMENT"
685 "Entries starting with this keyword will never be exported.
686 An entry can be toggled between COMMENT and normal with
687 \\[org-toggle-comment].
688 Changes become only effective after restarting Emacs."
689 :group 'org-keywords
690 :type 'string)
692 (defcustom org-quote-string "QUOTE"
693 "Entries starting with this keyword will be exported in fixed-width font.
694 Quoting applies only to the text in the entry following the headline, and does
695 not extend beyond the next headline, even if that is lower level.
696 An entry can be toggled between QUOTE and normal with
697 \\[org-toggle-fixed-width-section]."
698 :group 'org-keywords
699 :type 'string)
701 (defconst org-repeat-re
702 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
703 "Regular expression for specifying repeated events.
704 After a match, group 1 contains the repeat expression.")
706 (defgroup org-structure nil
707 "Options concerning the general structure of Org-mode files."
708 :tag "Org Structure"
709 :group 'org)
711 (defgroup org-reveal-location nil
712 "Options about how to make context of a location visible."
713 :tag "Org Reveal Location"
714 :group 'org-structure)
716 (defconst org-context-choice
717 '(choice
718 (const :tag "Always" t)
719 (const :tag "Never" nil)
720 (repeat :greedy t :tag "Individual contexts"
721 (cons
722 (choice :tag "Context"
723 (const agenda)
724 (const org-goto)
725 (const occur-tree)
726 (const tags-tree)
727 (const link-search)
728 (const mark-goto)
729 (const bookmark-jump)
730 (const isearch)
731 (const default))
732 (boolean))))
733 "Contexts for the reveal options.")
735 (defcustom org-show-hierarchy-above '((default . t))
736 "Non-nil means show full hierarchy when revealing a location.
737 Org-mode often shows locations in an org-mode file which might have
738 been invisible before. When this is set, the hierarchy of headings
739 above the exposed location is shown.
740 Turning this off for example for sparse trees makes them very compact.
741 Instead of t, this can also be an alist specifying this option for different
742 contexts. Valid contexts are
743 agenda when exposing an entry from the agenda
744 org-goto when using the command `org-goto' on key C-c C-j
745 occur-tree when using the command `org-occur' on key C-c /
746 tags-tree when constructing a sparse tree based on tags matches
747 link-search when exposing search matches associated with a link
748 mark-goto when exposing the jump goal of a mark
749 bookmark-jump when exposing a bookmark location
750 isearch when exiting from an incremental search
751 default default for all contexts not set explicitly"
752 :group 'org-reveal-location
753 :type org-context-choice)
755 (defcustom org-show-following-heading '((default . nil))
756 "Non-nil means show following heading when revealing a location.
757 Org-mode often shows locations in an org-mode file which might have
758 been invisible before. When this is set, the heading following the
759 match is shown.
760 Turning this off for example for sparse trees makes them very compact,
761 but makes it harder to edit the location of the match. In such a case,
762 use the command \\[org-reveal] to show more context.
763 Instead of t, this can also be an alist specifying this option for different
764 contexts. See `org-show-hierarchy-above' for valid contexts."
765 :group 'org-reveal-location
766 :type org-context-choice)
768 (defcustom org-show-siblings '((default . nil) (isearch t))
769 "Non-nil means show all sibling heading when revealing a location.
770 Org-mode often shows locations in an org-mode file which might have
771 been invisible before. When this is set, the sibling of the current entry
772 heading are all made visible. If `org-show-hierarchy-above' is t,
773 the same happens on each level of the hierarchy above the current entry.
775 By default this is on for the isearch context, off for all other contexts.
776 Turning this off for example for sparse trees makes them very compact,
777 but makes it harder to edit the location of the match. In such a case,
778 use the command \\[org-reveal] to show more context.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. See `org-show-hierarchy-above' for valid contexts."
781 :group 'org-reveal-location
782 :type org-context-choice)
784 (defcustom org-show-entry-below '((default . nil))
785 "Non-nil means show the entry below a headline when revealing a location.
786 Org-mode often shows locations in an org-mode file which might have
787 been invisible before. When this is set, the text below the headline that is
788 exposed is also shown.
790 By default this is off for all contexts.
791 Instead of t, this can also be an alist specifying this option for different
792 contexts. See `org-show-hierarchy-above' for valid contexts."
793 :group 'org-reveal-location
794 :type org-context-choice)
796 (defcustom org-indirect-buffer-display 'other-window
797 "How should indirect tree buffers be displayed?
798 This applies to indirect buffers created with the commands
799 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
800 Valid values are:
801 current-window Display in the current window
802 other-window Just display in another window.
803 dedicated-frame Create one new frame, and re-use it each time.
804 new-frame Make a new frame each time. Note that in this case
805 previously-made indirect buffers are kept, and you need to
806 kill these buffers yourself."
807 :group 'org-structure
808 :group 'org-agenda-windows
809 :type '(choice
810 (const :tag "In current window" current-window)
811 (const :tag "In current frame, other window" other-window)
812 (const :tag "Each time a new frame" new-frame)
813 (const :tag "One dedicated frame" dedicated-frame)))
815 (defcustom org-use-speed-commands nil
816 "Non-nil means activate single letter commands at beginning of a headline.
817 This may also be a function to test for appropriate locations where speed
818 commands should be active."
819 :group 'org-structure
820 :type '(choice
821 (const :tag "Never" nil)
822 (const :tag "At beginning of headline stars" t)
823 (function)))
825 (defcustom org-speed-commands-user nil
826 "Alist of additional speed commands.
827 This list will be checked before `org-speed-commands-default'
828 when the variable `org-use-speed-commands' is non-nil
829 and when the cursor is at the beginning of a headline.
830 The car if each entry is a string with a single letter, which must
831 be assigned to `self-insert-command' in the global map.
832 The cdr is either a command to be called interactively, a function
833 to be called, or a form to be evaluated.
834 An entry that is just a list with a single string will be interpreted
835 as a descriptive headline that will be added when listing the speed
836 commands in the Help buffer using the `?' speed command."
837 :group 'org-structure
838 :type '(repeat :value ("k" . ignore)
839 (choice :value ("k" . ignore)
840 (list :tag "Descriptive Headline" (string :tag "Headline"))
841 (cons :tag "Letter and Command"
842 (string :tag "Command letter")
843 (choice
844 (function)
845 (sexp))))))
847 (defgroup org-cycle nil
848 "Options concerning visibility cycling in Org-mode."
849 :tag "Org Cycle"
850 :group 'org-structure)
852 (defcustom org-cycle-skip-children-state-if-no-children t
853 "Non-nil means skip CHILDREN state in entries that don't have any."
854 :group 'org-cycle
855 :type 'boolean)
857 (defcustom org-cycle-max-level nil
858 "Maximum level which should still be subject to visibility cycling.
859 Levels higher than this will, for cycling, be treated as text, not a headline.
860 When `org-odd-levels-only' is set, a value of N in this variable actually
861 means 2N-1 stars as the limiting headline.
862 When nil, cycle all levels.
863 Note that the limiting level of cycling is also influenced by
864 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
865 `org-inlinetask-min-level' is, cycling will be limited to levels one less
866 than its value."
867 :group 'org-cycle
868 :type '(choice
869 (const :tag "No limit" nil)
870 (integer :tag "Maximum level")))
872 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
873 "Names of drawers. Drawers are not opened by cycling on the headline above.
874 Drawers only open with a TAB on the drawer line itself. A drawer looks like
875 this:
876 :DRAWERNAME:
877 .....
878 :END:
879 The drawer \"PROPERTIES\" is special for capturing properties through
880 the property API.
882 Drawers can be defined on the per-file basis with a line like:
884 #+DRAWERS: HIDDEN STATE PROPERTIES"
885 :group 'org-structure
886 :group 'org-cycle
887 :type '(repeat (string :tag "Drawer Name")))
889 (defcustom org-hide-block-startup nil
890 "Non-nil means entering Org-mode will fold all blocks.
891 This can also be set in on a per-file basis with
893 #+STARTUP: hideblocks
894 #+STARTUP: showblocks"
895 :group 'org-startup
896 :group 'org-cycle
897 :type 'boolean)
899 (defcustom org-cycle-global-at-bob nil
900 "Cycle globally if cursor is at beginning of buffer and not at a headline.
901 This makes it possible to do global cycling without having to use S-TAB or
902 \\[universal-argument] TAB. For this special case to work, the first line
903 of the buffer must not be a headline -- it may be empty or some other text.
904 When used in this way, `org-cycle-hook' is disabled temporarily to make
905 sure the cursor stays at the beginning of the buffer. When this option is
906 nil, don't do anything special at the beginning of the buffer."
907 :group 'org-cycle
908 :type 'boolean)
910 (defcustom org-cycle-level-after-item/entry-creation t
911 "Non-nil means cycle entry level or item indentation in new empty entries.
913 When the cursor is at the end of an empty headline, i.e with only stars
914 and maybe a TODO keyword, TAB will then switch the entry to become a child,
915 and then all possible ancestor states, before returning to the original state.
916 This makes data entry extremely fast: M-RET to create a new headline,
917 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
919 When the cursor is at the end of an empty plain list item, one TAB will
920 make it a subitem, two or more tabs will back up to make this an item
921 higher up in the item hierarchy."
922 :group 'org-cycle
923 :type 'boolean)
925 (defcustom org-cycle-emulate-tab t
926 "Where should `org-cycle' emulate TAB.
927 nil Never
928 white Only in completely white lines
929 whitestart Only at the beginning of lines, before the first non-white char
930 t Everywhere except in headlines
931 exc-hl-bol Everywhere except at the start of a headline
932 If TAB is used in a place where it does not emulate TAB, the current subtree
933 visibility is cycled."
934 :group 'org-cycle
935 :type '(choice (const :tag "Never" nil)
936 (const :tag "Only in completely white lines" white)
937 (const :tag "Before first char in a line" whitestart)
938 (const :tag "Everywhere except in headlines" t)
939 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
942 (defcustom org-cycle-separator-lines 2
943 "Number of empty lines needed to keep an empty line between collapsed trees.
944 If you leave an empty line between the end of a subtree and the following
945 headline, this empty line is hidden when the subtree is folded.
946 Org-mode will leave (exactly) one empty line visible if the number of
947 empty lines is equal or larger to the number given in this variable.
948 So the default 2 means at least 2 empty lines after the end of a subtree
949 are needed to produce free space between a collapsed subtree and the
950 following headline.
952 If the number is negative, and the number of empty lines is at least -N,
953 all empty lines are shown.
955 Special case: when 0, never leave empty lines in collapsed view."
956 :group 'org-cycle
957 :type 'integer)
958 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
960 (defcustom org-pre-cycle-hook nil
961 "Hook that is run before visibility cycling is happening.
962 The function(s) in this hook must accept a single argument which indicates
963 the new state that will be set right after running this hook. The
964 argument is a symbol. Before a global state change, it can have the values
965 `overview', `content', or `all'. Before a local state change, it can have
966 the values `folded', `children', or `subtree'."
967 :group 'org-cycle
968 :type 'hook)
970 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
971 org-cycle-hide-drawers
972 org-cycle-show-empty-lines
973 org-optimize-window-after-visibility-change)
974 "Hook that is run after `org-cycle' has changed the buffer visibility.
975 The function(s) in this hook must accept a single argument which indicates
976 the new state that was set by the most recent `org-cycle' command. The
977 argument is a symbol. After a global state change, it can have the values
978 `overview', `contents', or `all'. After a local state change, it can have
979 the values `folded', `children', or `subtree'."
980 :group 'org-cycle
981 :type 'hook)
983 (defgroup org-edit-structure nil
984 "Options concerning structure editing in Org-mode."
985 :tag "Org Edit Structure"
986 :group 'org-structure)
988 (defcustom org-odd-levels-only nil
989 "Non-nil means skip even levels and only use odd levels for the outline.
990 This has the effect that two stars are being added/taken away in
991 promotion/demotion commands. It also influences how levels are
992 handled by the exporters.
993 Changing it requires restart of `font-lock-mode' to become effective
994 for fontification also in regions already fontified.
995 You may also set this on a per-file basis by adding one of the following
996 lines to the buffer:
998 #+STARTUP: odd
999 #+STARTUP: oddeven"
1000 :group 'org-edit-structure
1001 :group 'org-appearance
1002 :type 'boolean)
1004 (defcustom org-adapt-indentation t
1005 "Non-nil means adapt indentation to outline node level.
1007 When this variable is set, Org assumes that you write outlines by
1008 indenting text in each node to align with the headline (after the stars).
1009 The following issues are influenced by this variable:
1011 - When this is set and the *entire* text in an entry is indented, the
1012 indentation is increased by one space in a demotion command, and
1013 decreased by one in a promotion command. If any line in the entry
1014 body starts with text at column 0, indentation is not changed at all.
1016 - Property drawers and planning information is inserted indented when
1017 this variable s set. When nil, they will not be indented.
1019 - TAB indents a line relative to context. The lines below a headline
1020 will be indented when this variable is set.
1022 Note that this is all about true indentation, by adding and removing
1023 space characters. See also `org-indent.el' which does level-dependent
1024 indentation in a virtual way, i.e. at display time in Emacs."
1025 :group 'org-edit-structure
1026 :type 'boolean)
1028 (defcustom org-special-ctrl-a/e nil
1029 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1031 When t, `C-a' will bring back the cursor to the beginning of the
1032 headline text, i.e. after the stars and after a possible TODO
1033 keyword. In an item, this will be the position after bullet and
1034 check-box, if any. When the cursor is already at that position,
1035 another `C-a' will bring it to the beginning of the line.
1037 `C-e' will jump to the end of the headline, ignoring the presence
1038 of tags in the headline. A second `C-e' will then jump to the
1039 true end of the line, after any tags. This also means that, when
1040 this variable is non-nil, `C-e' also will never jump beyond the
1041 end of the heading of a folded section, i.e. not after the
1042 ellipses.
1044 When set to the symbol `reversed', the first `C-a' or `C-e' works
1045 normally, going to the true line boundary first. Only a directly
1046 following, identical keypress will bring the cursor to the
1047 special positions.
1049 This may also be a cons cell where the behavior for `C-a' and
1050 `C-e' is set separately."
1051 :group 'org-edit-structure
1052 :type '(choice
1053 (const :tag "off" nil)
1054 (const :tag "on: after stars/bullet and before tags first" t)
1055 (const :tag "reversed: true line boundary first" reversed)
1056 (cons :tag "Set C-a and C-e separately"
1057 (choice :tag "Special C-a"
1058 (const :tag "off" nil)
1059 (const :tag "on: after stars/bullet first" t)
1060 (const :tag "reversed: before stars/bullet first" reversed))
1061 (choice :tag "Special C-e"
1062 (const :tag "off" nil)
1063 (const :tag "on: before tags first" t)
1064 (const :tag "reversed: after tags first" reversed)))))
1065 (if (fboundp 'defvaralias)
1066 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1068 (defcustom org-special-ctrl-k nil
1069 "Non-nil means `C-k' will behave specially in headlines.
1070 When nil, `C-k' will call the default `kill-line' command.
1071 When t, the following will happen while the cursor is in the headline:
1073 - When the cursor is at the beginning of a headline, kill the entire
1074 line and possible the folded subtree below the line.
1075 - When in the middle of the headline text, kill the headline up to the tags.
1076 - When after the headline text, kill the tags."
1077 :group 'org-edit-structure
1078 :type 'boolean)
1080 (defcustom org-ctrl-k-protect-subtree nil
1081 "Non-nil means, do not delete a hidden subtree with C-k.
1082 When set to the symbol `error', simply throw an error when C-k is
1083 used to kill (part-of) a headline that has hidden text behind it.
1084 Any other non-nil value will result in a query to the user, if it is
1085 OK to kill that hidden subtree. When nil, kill without remorse."
1086 :group 'org-edit-structure
1087 :version "24.1"
1088 :type '(choice
1089 (const :tag "Do not protect hidden subtrees" nil)
1090 (const :tag "Protect hidden subtrees with a security query" t)
1091 (const :tag "Never kill a hidden subtree with C-k" error)))
1093 (defcustom org-catch-invisible-edits nil
1094 "Check if in invisible region before inserting or deleting a character.
1095 Valid values are:
1097 nil Do not check, so just do invisible edits.
1098 error Throw an error and do nothing.
1099 show Make point visible, and do the requested edit.
1100 show-and-error Make point visible, then throw an error and abort the edit.
1101 smart Make point visible, and do insertion/deletion if it is
1102 adjacent to visible text and the change feels predictable.
1103 Never delete a previously invisible character or add in the
1104 middle or right after an invisible region. Basically, this
1105 allows insertion and backward-delete right before ellipses.
1106 FIXME: maybe in this case we should not even show?"
1107 :group 'org-edit-structure
1108 :version "24.1"
1109 :type '(choice
1110 (const :tag "Do not check" nil)
1111 (const :tag "Throw error when trying to edit" error)
1112 (const :tag "Unhide, but do not do the edit" show-and-error)
1113 (const :tag "Show invisible part and do the edit" show)
1114 (const :tag "Be smart and do the right thing" smart)))
1116 (defcustom org-yank-folded-subtrees t
1117 "Non-nil means when yanking subtrees, fold them.
1118 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1119 it starts with a heading and all other headings in it are either children
1120 or siblings, then fold all the subtrees. However, do this only if no
1121 text after the yank would be swallowed into a folded tree by this action."
1122 :group 'org-edit-structure
1123 :type 'boolean)
1125 (defcustom org-yank-adjusted-subtrees nil
1126 "Non-nil means when yanking subtrees, adjust the level.
1127 With this setting, `org-paste-subtree' is used to insert the subtree, see
1128 this function for details."
1129 :group 'org-edit-structure
1130 :type 'boolean)
1132 (defcustom org-M-RET-may-split-line '((default . t))
1133 "Non-nil means M-RET will split the line at the cursor position.
1134 When nil, it will go to the end of the line before making a
1135 new line.
1136 You may also set this option in a different way for different
1137 contexts. Valid contexts are:
1139 headline when creating a new headline
1140 item when creating a new item
1141 table in a table field
1142 default the value to be used for all contexts not explicitly
1143 customized"
1144 :group 'org-structure
1145 :group 'org-table
1146 :type '(choice
1147 (const :tag "Always" t)
1148 (const :tag "Never" nil)
1149 (repeat :greedy t :tag "Individual contexts"
1150 (cons
1151 (choice :tag "Context"
1152 (const headline)
1153 (const item)
1154 (const table)
1155 (const default))
1156 (boolean)))))
1159 (defcustom org-insert-heading-respect-content nil
1160 "Non-nil means insert new headings after the current subtree.
1161 When nil, the new heading is created directly after the current line.
1162 The commands \\[org-insert-heading-respect-content] and
1163 \\[org-insert-todo-heading-respect-content] turn this variable on
1164 for the duration of the command."
1165 :group 'org-structure
1166 :type 'boolean)
1168 (defcustom org-blank-before-new-entry '((heading . auto)
1169 (plain-list-item . auto))
1170 "Should `org-insert-heading' leave a blank line before new heading/item?
1171 The value is an alist, with `heading' and `plain-list-item' as CAR,
1172 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1173 which case Org will look at the surrounding headings/items and try to
1174 make an intelligent decision whether to insert a blank line or not.
1176 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1177 set, the setting here is ignored and no empty line is inserted, to avoid
1178 breaking the list structure."
1179 :group 'org-edit-structure
1180 :type '(list
1181 (cons (const heading)
1182 (choice (const :tag "Never" nil)
1183 (const :tag "Always" t)
1184 (const :tag "Auto" auto)))
1185 (cons (const plain-list-item)
1186 (choice (const :tag "Never" nil)
1187 (const :tag "Always" t)
1188 (const :tag "Auto" auto)))))
1190 (defcustom org-insert-heading-hook nil
1191 "Hook being run after inserting a new heading."
1192 :group 'org-edit-structure
1193 :type 'hook)
1195 (defcustom org-enable-fixed-width-editor t
1196 "Non-nil means lines starting with \":\" are treated as fixed-width.
1197 This currently only means they are never auto-wrapped.
1198 When nil, such lines will be treated like ordinary lines.
1199 See also the QUOTE keyword."
1200 :group 'org-edit-structure
1201 :type 'boolean)
1203 (defcustom org-goto-auto-isearch t
1204 "Non-nil means typing characters in `org-goto' starts incremental search."
1205 :group 'org-edit-structure
1206 :type 'boolean)
1208 (defgroup org-sparse-trees nil
1209 "Options concerning sparse trees in Org-mode."
1210 :tag "Org Sparse Trees"
1211 :group 'org-structure)
1213 (defcustom org-highlight-sparse-tree-matches t
1214 "Non-nil means highlight all matches that define a sparse tree.
1215 The highlights will automatically disappear the next time the buffer is
1216 changed by an edit command."
1217 :group 'org-sparse-trees
1218 :type 'boolean)
1220 (defcustom org-remove-highlights-with-change t
1221 "Non-nil means any change to the buffer will remove temporary highlights.
1222 Such highlights are created by `org-occur' and `org-clock-display'.
1223 When nil, `C-c C-c needs to be used to get rid of the highlights.
1224 The highlights created by `org-preview-latex-fragment' always need
1225 `C-c C-c' to be removed."
1226 :group 'org-sparse-trees
1227 :group 'org-time
1228 :type 'boolean)
1231 (defcustom org-occur-hook '(org-first-headline-recenter)
1232 "Hook that is run after `org-occur' has constructed a sparse tree.
1233 This can be used to recenter the window to show as much of the structure
1234 as possible."
1235 :group 'org-sparse-trees
1236 :type 'hook)
1238 (defgroup org-imenu-and-speedbar nil
1239 "Options concerning imenu and speedbar in Org-mode."
1240 :tag "Org Imenu and Speedbar"
1241 :group 'org-structure)
1243 (defcustom org-imenu-depth 2
1244 "The maximum level for Imenu access to Org-mode headlines.
1245 This also applied for speedbar access."
1246 :group 'org-imenu-and-speedbar
1247 :type 'integer)
1249 (defgroup org-table nil
1250 "Options concerning tables in Org-mode."
1251 :tag "Org Table"
1252 :group 'org)
1254 (defcustom org-enable-table-editor 'optimized
1255 "Non-nil means lines starting with \"|\" are handled by the table editor.
1256 When nil, such lines will be treated like ordinary lines.
1258 When equal to the symbol `optimized', the table editor will be optimized to
1259 do the following:
1260 - Automatic overwrite mode in front of whitespace in table fields.
1261 This makes the structure of the table stay in tact as long as the edited
1262 field does not exceed the column width.
1263 - Minimize the number of realigns. Normally, the table is aligned each time
1264 TAB or RET are pressed to move to another field. With optimization this
1265 happens only if changes to a field might have changed the column width.
1266 Optimization requires replacing the functions `self-insert-command',
1267 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1268 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1269 very good at guessing when a re-align will be necessary, but you can always
1270 force one with \\[org-ctrl-c-ctrl-c].
1272 If you would like to use the optimized version in Org-mode, but the
1273 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1275 This variable can be used to turn on and off the table editor during a session,
1276 but in order to toggle optimization, a restart is required.
1278 See also the variable `org-table-auto-blank-field'."
1279 :group 'org-table
1280 :type '(choice
1281 (const :tag "off" nil)
1282 (const :tag "on" t)
1283 (const :tag "on, optimized" optimized)))
1285 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1286 (version<= emacs-version "24.1"))
1287 "Non-nil means cluster self-insert commands for undo when possible.
1288 If this is set, then, like in the Emacs command loop, 20 consecutive
1289 characters will be undone together.
1290 This is configurable, because there is some impact on typing performance."
1291 :group 'org-table
1292 :type 'boolean)
1294 (defcustom org-table-tab-recognizes-table.el t
1295 "Non-nil means TAB will automatically notice a table.el table.
1296 When it sees such a table, it moves point into it and - if necessary -
1297 calls `table-recognize-table'."
1298 :group 'org-table-editing
1299 :type 'boolean)
1301 (defgroup org-link nil
1302 "Options concerning links in Org-mode."
1303 :tag "Org Link"
1304 :group 'org)
1306 (defvar org-link-abbrev-alist-local nil
1307 "Buffer-local version of `org-link-abbrev-alist', which see.
1308 The value of this is taken from the #+LINK lines.")
1309 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1311 (defcustom org-link-abbrev-alist nil
1312 "Alist of link abbreviations.
1313 The car of each element is a string, to be replaced at the start of a link.
1314 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1315 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1317 [[linkkey:tag][description]]
1319 The 'linkkey' must be a word word, starting with a letter, followed
1320 by letters, numbers, '-' or '_'.
1322 If REPLACE is a string, the tag will simply be appended to create the link.
1323 If the string contains \"%s\", the tag will be inserted there. If the string
1324 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1325 at that point (see the function `url-hexify-string'). If the string contains
1326 the specifier \"%(my-function)\", then the custom function `my-function' will
1327 be invoked: this function takes the tag as its only argument and must return
1328 a string.
1330 REPLACE may also be a function that will be called with the tag as the
1331 only argument to create the link, which should be returned as a string.
1333 See the manual for examples."
1334 :group 'org-link
1335 :type '(repeat
1336 (cons
1337 (string :tag "Protocol")
1338 (choice
1339 (string :tag "Format")
1340 (function)))))
1342 (defcustom org-descriptive-links t
1343 "Non-nil means Org will display descriptive links.
1344 E.g. [[http://orgmode.org][Org website]] will be displayed as
1345 \"Org Website\", hiding the link itself and just displaying its
1346 description. When set to `nil', Org will display the full links
1347 literally.
1349 You can interactively set the value of this variable by calling
1350 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1351 :group 'org-link
1352 :type 'boolean)
1354 (defcustom org-link-file-path-type 'adaptive
1355 "How the path name in file links should be stored.
1356 Valid values are:
1358 relative Relative to the current directory, i.e. the directory of the file
1359 into which the link is being inserted.
1360 absolute Absolute path, if possible with ~ for home directory.
1361 noabbrev Absolute path, no abbreviation of home directory.
1362 adaptive Use relative path for files in the current directory and sub-
1363 directories of it. For other files, use an absolute path."
1364 :group 'org-link
1365 :type '(choice
1366 (const relative)
1367 (const absolute)
1368 (const noabbrev)
1369 (const adaptive)))
1371 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1372 "Types of links that should be activated in Org-mode files.
1373 This is a list of symbols, each leading to the activation of a certain link
1374 type. In principle, it does not hurt to turn on most link types - there may
1375 be a small gain when turning off unused link types. The types are:
1377 bracket The recommended [[link][description]] or [[link]] links with hiding.
1378 angle Links in angular brackets that may contain whitespace like
1379 <bbdb:Carsten Dominik>.
1380 plain Plain links in normal text, no whitespace, like http://google.com.
1381 radio Text that is matched by a radio target, see manual for details.
1382 tag Tag settings in a headline (link to tag search).
1383 date Time stamps (link to calendar).
1384 footnote Footnote labels.
1386 Changing this variable requires a restart of Emacs to become effective."
1387 :group 'org-link
1388 :type '(set :greedy t
1389 (const :tag "Double bracket links" bracket)
1390 (const :tag "Angular bracket links" angle)
1391 (const :tag "Plain text links" plain)
1392 (const :tag "Radio target matches" radio)
1393 (const :tag "Tags" tag)
1394 (const :tag "Timestamps" date)
1395 (const :tag "Footnotes" footnote)))
1397 (defcustom org-make-link-description-function nil
1398 "Function to use for generating link descriptions from links.
1399 When nil, the link location will be used. This function must take
1400 two parameters: the first one is the link, the second one is the
1401 description generated by `org-insert-link'. The function should
1402 return the description to use."
1403 :group 'org-link
1404 :type 'function)
1406 (defgroup org-link-store nil
1407 "Options concerning storing links in Org-mode."
1408 :tag "Org Store Link"
1409 :group 'org-link)
1411 (defcustom org-url-hexify-p t
1412 "When non-nil, hexify URL when creating a link."
1413 :type 'boolean
1414 ;; :version "24.3"
1415 :group 'org-link-store)
1417 (defcustom org-email-link-description-format "Email %c: %.30s"
1418 "Format of the description part of a link to an email or usenet message.
1419 The following %-escapes will be replaced by corresponding information:
1421 %F full \"From\" field
1422 %f name, taken from \"From\" field, address if no name
1423 %T full \"To\" field
1424 %t first name in \"To\" field, address if no name
1425 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1426 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1427 %s subject
1428 %d date
1429 %m message-id.
1431 You may use normal field width specification between the % and the letter.
1432 This is for example useful to limit the length of the subject.
1434 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1435 :group 'org-link-store
1436 :type 'string)
1438 (defcustom org-from-is-user-regexp
1439 (let (r1 r2)
1440 (when (and user-mail-address (not (string= user-mail-address "")))
1441 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1442 (when (and user-full-name (not (string= user-full-name "")))
1443 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1444 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1445 "Regexp matched against the \"From:\" header of an email or usenet message.
1446 It should match if the message is from the user him/herself."
1447 :group 'org-link-store
1448 :type 'regexp)
1450 (defcustom org-context-in-file-links t
1451 "Non-nil means file links from `org-store-link' contain context.
1452 A search string will be added to the file name with :: as separator and
1453 used to find the context when the link is activated by the command
1454 `org-open-at-point'. When this option is t, the entire active region
1455 will be placed in the search string of the file link. If set to a
1456 positive integer, only the first n lines of context will be stored.
1458 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1459 negates this setting for the duration of the command."
1460 :group 'org-link-store
1461 :type '(choice boolean integer))
1463 (defcustom org-keep-stored-link-after-insertion nil
1464 "Non-nil means keep link in list for entire session.
1466 The command `org-store-link' adds a link pointing to the current
1467 location to an internal list. These links accumulate during a session.
1468 The command `org-insert-link' can be used to insert links into any
1469 Org-mode file (offering completion for all stored links). When this
1470 option is nil, every link which has been inserted once using \\[org-insert-link]
1471 will be removed from the list, to make completing the unused links
1472 more efficient."
1473 :group 'org-link-store
1474 :type 'boolean)
1476 (defgroup org-link-follow nil
1477 "Options concerning following links in Org-mode."
1478 :tag "Org Follow Link"
1479 :group 'org-link)
1481 (defcustom org-link-translation-function nil
1482 "Function to translate links with different syntax to Org syntax.
1483 This can be used to translate links created for example by the Planner
1484 or emacs-wiki packages to Org syntax.
1485 The function must accept two parameters, a TYPE containing the link
1486 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1487 which is everything after the link protocol. It should return a cons
1488 with possibly modified values of type and path.
1489 Org contains a function for this, so if you set this variable to
1490 `org-translate-link-from-planner', you should be able follow many
1491 links created by planner."
1492 :group 'org-link-follow
1493 :type 'function)
1495 (defcustom org-follow-link-hook nil
1496 "Hook that is run after a link has been followed."
1497 :group 'org-link-follow
1498 :type 'hook)
1500 (defcustom org-tab-follows-link nil
1501 "Non-nil means on links TAB will follow the link.
1502 Needs to be set before org.el is loaded.
1503 This really should not be used, it does not make sense, and the
1504 implementation is bad."
1505 :group 'org-link-follow
1506 :type 'boolean)
1508 (defcustom org-return-follows-link nil
1509 "Non-nil means on links RET will follow the link."
1510 :group 'org-link-follow
1511 :type 'boolean)
1513 (defcustom org-mouse-1-follows-link
1514 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1515 "Non-nil means mouse-1 on a link will follow the link.
1516 A longer mouse click will still set point. Does not work on XEmacs.
1517 Needs to be set before org.el is loaded."
1518 :group 'org-link-follow
1519 :type 'boolean)
1521 (defcustom org-mark-ring-length 4
1522 "Number of different positions to be recorded in the ring.
1523 Changing this requires a restart of Emacs to work correctly."
1524 :group 'org-link-follow
1525 :type 'integer)
1527 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1528 "Non-nil means internal links in Org files must exactly match a headline.
1529 When nil, the link search tries to match a phrase with all words
1530 in the search text."
1531 :group 'org-link-follow
1532 :version "24.1"
1533 :type '(choice
1534 (const :tag "Use fuzzy text search" nil)
1535 (const :tag "Match only exact headline" t)
1536 (const :tag "Match exact headline or query to create it"
1537 query-to-create)))
1539 (defcustom org-link-frame-setup
1540 '((vm . vm-visit-folder-other-frame)
1541 (vm-imap . vm-visit-imap-folder-other-frame)
1542 (gnus . org-gnus-no-new-news)
1543 (file . find-file-other-window)
1544 (wl . wl-other-frame))
1545 "Setup the frame configuration for following links.
1546 When following a link with Emacs, it may often be useful to display
1547 this link in another window or frame. This variable can be used to
1548 set this up for the different types of links.
1549 For VM, use any of
1550 `vm-visit-folder'
1551 `vm-visit-folder-other-window'
1552 `vm-visit-folder-other-frame'
1553 For Gnus, use any of
1554 `gnus'
1555 `gnus-other-frame'
1556 `org-gnus-no-new-news'
1557 For FILE, use any of
1558 `find-file'
1559 `find-file-other-window'
1560 `find-file-other-frame'
1561 For Wanderlust use any of
1562 `wl'
1563 `wl-other-frame'
1564 For the calendar, use the variable `calendar-setup'.
1565 For BBDB, it is currently only possible to display the matches in
1566 another window."
1567 :group 'org-link-follow
1568 :type '(list
1569 (cons (const vm)
1570 (choice
1571 (const vm-visit-folder)
1572 (const vm-visit-folder-other-window)
1573 (const vm-visit-folder-other-frame)))
1574 (cons (const gnus)
1575 (choice
1576 (const gnus)
1577 (const gnus-other-frame)
1578 (const org-gnus-no-new-news)))
1579 (cons (const file)
1580 (choice
1581 (const find-file)
1582 (const find-file-other-window)
1583 (const find-file-other-frame)))
1584 (cons (const wl)
1585 (choice
1586 (const wl)
1587 (const wl-other-frame)))))
1589 (defcustom org-display-internal-link-with-indirect-buffer nil
1590 "Non-nil means use indirect buffer to display infile links.
1591 Activating internal links (from one location in a file to another location
1592 in the same file) normally just jumps to the location. When the link is
1593 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1594 is displayed in
1595 another window. When this option is set, the other window actually displays
1596 an indirect buffer clone of the current buffer, to avoid any visibility
1597 changes to the current buffer."
1598 :group 'org-link-follow
1599 :type 'boolean)
1601 (defcustom org-open-non-existing-files nil
1602 "Non-nil means `org-open-file' will open non-existing files.
1603 When nil, an error will be generated.
1604 This variable applies only to external applications because they
1605 might choke on non-existing files. If the link is to a file that
1606 will be opened in Emacs, the variable is ignored."
1607 :group 'org-link-follow
1608 :type 'boolean)
1610 (defcustom org-open-directory-means-index-dot-org nil
1611 "Non-nil means a link to a directory really means to index.org.
1612 When nil, following a directory link will run dired or open a finder/explorer
1613 window on that directory."
1614 :group 'org-link-follow
1615 :type 'boolean)
1617 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1618 "Function and arguments to call for following mailto links.
1619 This is a list with the first element being a Lisp function, and the
1620 remaining elements being arguments to the function. In string arguments,
1621 %a will be replaced by the address, and %s will be replaced by the subject
1622 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1623 :group 'org-link-follow
1624 :type '(choice
1625 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1626 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1627 (const :tag "message-mail" (message-mail "%a" "%s"))
1628 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1630 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1631 "Non-nil means ask for confirmation before executing shell links.
1632 Shell links can be dangerous: just think about a link
1634 [[shell:rm -rf ~/*][Google Search]]
1636 This link would show up in your Org-mode document as \"Google Search\",
1637 but really it would remove your entire home directory.
1638 Therefore we advise against setting this variable to nil.
1639 Just change it to `y-or-n-p' if you want to confirm with a
1640 single keystroke rather than having to type \"yes\"."
1641 :group 'org-link-follow
1642 :type '(choice
1643 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1644 (const :tag "with y-or-n (faster)" y-or-n-p)
1645 (const :tag "no confirmation (dangerous)" nil)))
1646 (put 'org-confirm-shell-link-function
1647 'safe-local-variable
1648 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1650 (defcustom org-confirm-shell-link-not-regexp ""
1651 "A regexp to skip confirmation for shell links."
1652 :group 'org-link-follow
1653 :version "24.1"
1654 :type 'regexp)
1656 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1657 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1658 Elisp links can be dangerous: just think about a link
1660 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1662 This link would show up in your Org-mode document as \"Google Search\",
1663 but really it would remove your entire home directory.
1664 Therefore we advise against setting this variable to nil.
1665 Just change it to `y-or-n-p' if you want to confirm with a
1666 single keystroke rather than having to type \"yes\"."
1667 :group 'org-link-follow
1668 :type '(choice
1669 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1670 (const :tag "with y-or-n (faster)" y-or-n-p)
1671 (const :tag "no confirmation (dangerous)" nil)))
1672 (put 'org-confirm-shell-link-function
1673 'safe-local-variable
1674 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1676 (defcustom org-confirm-elisp-link-not-regexp ""
1677 "A regexp to skip confirmation for Elisp links."
1678 :group 'org-link-follow
1679 :version "24.1"
1680 :type 'regexp)
1682 (defconst org-file-apps-defaults-gnu
1683 '((remote . emacs)
1684 (system . mailcap)
1685 (t . mailcap))
1686 "Default file applications on a UNIX or GNU/Linux system.
1687 See `org-file-apps'.")
1689 (defconst org-file-apps-defaults-macosx
1690 '((remote . emacs)
1691 (t . "open %s")
1692 (system . "open %s")
1693 ("ps.gz" . "gv %s")
1694 ("eps.gz" . "gv %s")
1695 ("dvi" . "xdvi %s")
1696 ("fig" . "xfig %s"))
1697 "Default file applications on a MacOS X system.
1698 The system \"open\" is known as a default, but we use X11 applications
1699 for some files for which the OS does not have a good default.
1700 See `org-file-apps'.")
1702 (defconst org-file-apps-defaults-windowsnt
1703 (list
1704 '(remote . emacs)
1705 (cons t
1706 (list (if (featurep 'xemacs)
1707 'mswindows-shell-execute
1708 'w32-shell-execute)
1709 "open" 'file))
1710 (cons 'system
1711 (list (if (featurep 'xemacs)
1712 'mswindows-shell-execute
1713 'w32-shell-execute)
1714 "open" 'file)))
1715 "Default file applications on a Windows NT system.
1716 The system \"open\" is used for most files.
1717 See `org-file-apps'.")
1719 (defcustom org-file-apps
1721 (auto-mode . emacs)
1722 ("\\.mm\\'" . default)
1723 ("\\.x?html?\\'" . default)
1724 ("\\.pdf\\'" . default)
1726 "External applications for opening `file:path' items in a document.
1727 Org-mode uses system defaults for different file types, but
1728 you can use this variable to set the application for a given file
1729 extension. The entries in this list are cons cells where the car identifies
1730 files and the cdr the corresponding command. Possible values for the
1731 file identifier are
1732 \"string\" A string as a file identifier can be interpreted in different
1733 ways, depending on its contents:
1735 - Alphanumeric characters only:
1736 Match links with this file extension.
1737 Example: (\"pdf\" . \"evince %s\")
1738 to open PDFs with evince.
1740 - Regular expression: Match links where the
1741 filename matches the regexp. If you want to
1742 use groups here, use shy groups.
1744 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1745 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1746 to open *.html and *.xhtml with firefox.
1748 - Regular expression which contains (non-shy) groups:
1749 Match links where the whole link, including \"::\", and
1750 anything after that, matches the regexp.
1751 In a custom command string, %1, %2, etc. are replaced with
1752 the parts of the link that were matched by the groups.
1753 For backwards compatibility, if a command string is given
1754 that does not use any of the group matches, this case is
1755 handled identically to the second one (i.e. match against
1756 file name only).
1757 In a custom lisp form, you can access the group matches with
1758 (match-string n link).
1760 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1761 to open [[file:document.pdf::5]] with evince at page 5.
1763 `directory' Matches a directory
1764 `remote' Matches a remote file, accessible through tramp or efs.
1765 Remote files most likely should be visited through Emacs
1766 because external applications cannot handle such paths.
1767 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1768 so all files Emacs knows how to handle. Using this with
1769 command `emacs' will open most files in Emacs. Beware that this
1770 will also open html files inside Emacs, unless you add
1771 (\"html\" . default) to the list as well.
1772 t Default for files not matched by any of the other options.
1773 `system' The system command to open files, like `open' on Windows
1774 and Mac OS X, and mailcap under GNU/Linux. This is the command
1775 that will be selected if you call `C-c C-o' with a double
1776 \\[universal-argument] \\[universal-argument] prefix.
1778 Possible values for the command are:
1779 `emacs' The file will be visited by the current Emacs process.
1780 `default' Use the default application for this file type, which is the
1781 association for t in the list, most likely in the system-specific
1782 part.
1783 This can be used to overrule an unwanted setting in the
1784 system-specific variable.
1785 `system' Use the system command for opening files, like \"open\".
1786 This command is specified by the entry whose car is `system'.
1787 Most likely, the system-specific version of this variable
1788 does define this command, but you can overrule/replace it
1789 here.
1790 string A command to be executed by a shell; %s will be replaced
1791 by the path to the file.
1792 sexp A Lisp form which will be evaluated. The file path will
1793 be available in the Lisp variable `file'.
1794 For more examples, see the system specific constants
1795 `org-file-apps-defaults-macosx'
1796 `org-file-apps-defaults-windowsnt'
1797 `org-file-apps-defaults-gnu'."
1798 :group 'org-link-follow
1799 :type '(repeat
1800 (cons (choice :value ""
1801 (string :tag "Extension")
1802 (const :tag "System command to open files" system)
1803 (const :tag "Default for unrecognized files" t)
1804 (const :tag "Remote file" remote)
1805 (const :tag "Links to a directory" directory)
1806 (const :tag "Any files that have Emacs modes"
1807 auto-mode))
1808 (choice :value ""
1809 (const :tag "Visit with Emacs" emacs)
1810 (const :tag "Use default" default)
1811 (const :tag "Use the system command" system)
1812 (string :tag "Command")
1813 (sexp :tag "Lisp form")))))
1815 (defcustom org-doi-server-url "http://dx.doi.org/"
1816 "The URL of the DOI server."
1817 :type 'string
1818 ;; :version "24.3"
1819 :group 'org-link-follow)
1821 (defgroup org-refile nil
1822 "Options concerning refiling entries in Org-mode."
1823 :tag "Org Refile"
1824 :group 'org)
1826 (defcustom org-directory "~/org"
1827 "Directory with org files.
1828 This is just a default location to look for Org files. There is no need
1829 at all to put your files into this directory. It is only used in the
1830 following situations:
1832 1. When a capture template specifies a target file that is not an
1833 absolute path. The path will then be interpreted relative to
1834 `org-directory'
1835 2. When a capture note is filed away in an interactive way (when exiting the
1836 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1837 with `org-directory' as the default path."
1838 :group 'org-refile
1839 :group 'org-remember
1840 :group 'org-capture
1841 :type 'directory)
1843 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1844 "Default target for storing notes.
1845 Used as a fall back file for org-remember.el and org-capture.el, for
1846 templates that do not specify a target file."
1847 :group 'org-refile
1848 :group 'org-remember
1849 :group 'org-capture
1850 :type '(choice
1851 (const :tag "Default from remember-data-file" nil)
1852 file))
1854 (defcustom org-goto-interface 'outline
1855 "The default interface to be used for `org-goto'.
1856 Allowed values are:
1857 outline The interface shows an outline of the relevant file
1858 and the correct heading is found by moving through
1859 the outline or by searching with incremental search.
1860 outline-path-completion Headlines in the current buffer are offered via
1861 completion. This is the interface also used by
1862 the refile command."
1863 :group 'org-refile
1864 :type '(choice
1865 (const :tag "Outline" outline)
1866 (const :tag "Outline-path-completion" outline-path-completion)))
1868 (defcustom org-goto-max-level 5
1869 "Maximum target level when running `org-goto' with refile interface."
1870 :group 'org-refile
1871 :type 'integer)
1873 (defcustom org-reverse-note-order nil
1874 "Non-nil means store new notes at the beginning of a file or entry.
1875 When nil, new notes will be filed to the end of a file or entry.
1876 This can also be a list with cons cells of regular expressions that
1877 are matched against file names, and values."
1878 :group 'org-remember
1879 :group 'org-capture
1880 :group 'org-refile
1881 :type '(choice
1882 (const :tag "Reverse always" t)
1883 (const :tag "Reverse never" nil)
1884 (repeat :tag "By file name regexp"
1885 (cons regexp boolean))))
1887 (defcustom org-log-refile nil
1888 "Information to record when a task is refiled.
1890 Possible values are:
1892 nil Don't add anything
1893 time Add a time stamp to the task
1894 note Prompt for a note and add it with template `org-log-note-headings'
1896 This option can also be set with on a per-file-basis with
1898 #+STARTUP: nologrefile
1899 #+STARTUP: logrefile
1900 #+STARTUP: lognoterefile
1902 You can have local logging settings for a subtree by setting the LOGGING
1903 property to one or more of these keywords.
1905 When bulk-refiling from the agenda, the value `note' is forbidden and
1906 will temporarily be changed to `time'."
1907 :group 'org-refile
1908 :group 'org-progress
1909 :version "24.1"
1910 :type '(choice
1911 (const :tag "No logging" nil)
1912 (const :tag "Record timestamp" time)
1913 (const :tag "Record timestamp with note." note)))
1915 (defcustom org-refile-targets nil
1916 "Targets for refiling entries with \\[org-refile].
1917 This is a list of cons cells. Each cell contains:
1918 - a specification of the files to be considered, either a list of files,
1919 or a symbol whose function or variable value will be used to retrieve
1920 a file name or a list of file names. If you use `org-agenda-files' for
1921 that, all agenda files will be scanned for targets. Nil means consider
1922 headings in the current buffer.
1923 - A specification of how to find candidate refile targets. This may be
1924 any of:
1925 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1926 This tag has to be present in all target headlines, inheritance will
1927 not be considered.
1928 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1929 todo keyword.
1930 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1931 headlines that are refiling targets.
1932 - a cons cell (:level . N). Any headline of level N is considered a target.
1933 Note that, when `org-odd-levels-only' is set, level corresponds to
1934 order in hierarchy, not to the number of stars.
1935 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1936 Note that, when `org-odd-levels-only' is set, level corresponds to
1937 order in hierarchy, not to the number of stars.
1939 Each element of this list generates a set of possible targets.
1940 The union of these sets is presented (with completion) to
1941 the user by `org-refile'.
1943 You can set the variable `org-refile-target-verify-function' to a function
1944 to verify each headline found by the simple criteria above.
1946 When this variable is nil, all top-level headlines in the current buffer
1947 are used, equivalent to the value `((nil . (:level . 1))'."
1948 :group 'org-refile
1949 :type '(repeat
1950 (cons
1951 (choice :value org-agenda-files
1952 (const :tag "All agenda files" org-agenda-files)
1953 (const :tag "Current buffer" nil)
1954 (function) (variable) (file))
1955 (choice :tag "Identify target headline by"
1956 (cons :tag "Specific tag" (const :value :tag) (string))
1957 (cons :tag "TODO keyword" (const :value :todo) (string))
1958 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1959 (cons :tag "Level number" (const :value :level) (integer))
1960 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1962 (defcustom org-refile-target-verify-function nil
1963 "Function to verify if the headline at point should be a refile target.
1964 The function will be called without arguments, with point at the
1965 beginning of the headline. It should return t and leave point
1966 where it is if the headline is a valid target for refiling.
1968 If the target should not be selected, the function must return nil.
1969 In addition to this, it may move point to a place from where the search
1970 should be continued. For example, the function may decide that the entire
1971 subtree of the current entry should be excluded and move point to the end
1972 of the subtree."
1973 :group 'org-refile
1974 :type 'function)
1976 (defcustom org-refile-use-cache nil
1977 "Non-nil means cache refile targets to speed up the process.
1978 The cache for a particular file will be updated automatically when
1979 the buffer has been killed, or when any of the marker used for flagging
1980 refile targets no longer points at a live buffer.
1981 If you have added new entries to a buffer that might themselves be targets,
1982 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1983 find that easier, `C-u C-u C-u C-c C-w'."
1984 :group 'org-refile
1985 :version "24.1"
1986 :type 'boolean)
1988 (defcustom org-refile-use-outline-path nil
1989 "Non-nil means provide refile targets as paths.
1990 So a level 3 headline will be available as level1/level2/level3.
1992 When the value is `file', also include the file name (without directory)
1993 into the path. In this case, you can also stop the completion after
1994 the file name, to get entries inserted as top level in the file.
1996 When `full-file-path', include the full file path."
1997 :group 'org-refile
1998 :type '(choice
1999 (const :tag "Not" nil)
2000 (const :tag "Yes" t)
2001 (const :tag "Start with file name" file)
2002 (const :tag "Start with full file path" full-file-path)))
2004 (defcustom org-outline-path-complete-in-steps t
2005 "Non-nil means complete the outline path in hierarchical steps.
2006 When Org-mode uses the refile interface to select an outline path
2007 \(see variable `org-refile-use-outline-path'), the completion of
2008 the path can be done is a single go, or if can be done in steps down
2009 the headline hierarchy. Going in steps is probably the best if you
2010 do not use a special completion package like `ido' or `icicles'.
2011 However, when using these packages, going in one step can be very
2012 fast, while still showing the whole path to the entry."
2013 :group 'org-refile
2014 :type 'boolean)
2016 (defcustom org-refile-allow-creating-parent-nodes nil
2017 "Non-nil means allow to create new nodes as refile targets.
2018 New nodes are then created by adding \"/new node name\" to the completion
2019 of an existing node. When the value of this variable is `confirm',
2020 new node creation must be confirmed by the user (recommended)
2021 When nil, the completion must match an existing entry.
2023 Note that, if the new heading is not seen by the criteria
2024 listed in `org-refile-targets', multiple instances of the same
2025 heading would be created by trying again to file under the new
2026 heading."
2027 :group 'org-refile
2028 :type '(choice
2029 (const :tag "Never" nil)
2030 (const :tag "Always" t)
2031 (const :tag "Prompt for confirmation" confirm)))
2033 (defcustom org-refile-active-region-within-subtree nil
2034 "Non-nil means also refile active region within a subtree.
2036 By default `org-refile' doesn't allow refiling regions if they
2037 don't contain a set of subtrees, but it might be convenient to
2038 do so sometimes: in that case, the first line of the region is
2039 converted to a headline before refiling."
2040 :group 'org-refile
2041 :version "24.1"
2042 :type 'boolean)
2044 (defgroup org-todo nil
2045 "Options concerning TODO items in Org-mode."
2046 :tag "Org TODO"
2047 :group 'org)
2049 (defgroup org-progress nil
2050 "Options concerning Progress logging in Org-mode."
2051 :tag "Org Progress"
2052 :group 'org-time)
2054 (defvar org-todo-interpretation-widgets
2055 '((:tag "Sequence (cycling hits every state)" sequence)
2056 (:tag "Type (cycling directly to DONE)" type))
2057 "The available interpretation symbols for customizing `org-todo-keywords'.
2058 Interested libraries should add to this list.")
2060 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2061 "List of TODO entry keyword sequences and their interpretation.
2062 \\<org-mode-map>This is a list of sequences.
2064 Each sequence starts with a symbol, either `sequence' or `type',
2065 indicating if the keywords should be interpreted as a sequence of
2066 action steps, or as different types of TODO items. The first
2067 keywords are states requiring action - these states will select a headline
2068 for inclusion into the global TODO list Org-mode produces. If one of
2069 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2070 signify that no further action is necessary. If \"|\" is not found,
2071 the last keyword is treated as the only DONE state of the sequence.
2073 The command \\[org-todo] cycles an entry through these states, and one
2074 additional state where no keyword is present. For details about this
2075 cycling, see the manual.
2077 TODO keywords and interpretation can also be set on a per-file basis with
2078 the special #+SEQ_TODO and #+TYP_TODO lines.
2080 Each keyword can optionally specify a character for fast state selection
2081 \(in combination with the variable `org-use-fast-todo-selection')
2082 and specifiers for state change logging, using the same syntax that
2083 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2084 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2085 indicates to record a time stamp each time this state is selected.
2087 Each keyword may also specify if a timestamp or a note should be
2088 recorded when entering or leaving the state, by adding additional
2089 characters in the parenthesis after the keyword. This looks like this:
2090 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2091 record only the time of the state change. With X and Y being either
2092 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2093 Y when leaving the state if and only if the *target* state does not
2094 define X. You may omit any of the fast-selection key or X or /Y,
2095 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2097 For backward compatibility, this variable may also be just a list
2098 of keywords. In this case the interpretation (sequence or type) will be
2099 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2100 :group 'org-todo
2101 :group 'org-keywords
2102 :type '(choice
2103 (repeat :tag "Old syntax, just keywords"
2104 (string :tag "Keyword"))
2105 (repeat :tag "New syntax"
2106 (cons
2107 (choice
2108 :tag "Interpretation"
2109 ;;Quick and dirty way to see
2110 ;;`org-todo-interpretations'. This takes the
2111 ;;place of item arguments
2112 :convert-widget
2113 (lambda (widget)
2114 (widget-put widget
2115 :args (mapcar
2116 #'(lambda (x)
2117 (widget-convert
2118 (cons 'const x)))
2119 org-todo-interpretation-widgets))
2120 widget))
2121 (repeat
2122 (string :tag "Keyword"))))))
2124 (defvar org-todo-keywords-1 nil
2125 "All TODO and DONE keywords active in a buffer.")
2126 (make-variable-buffer-local 'org-todo-keywords-1)
2127 (defvar org-todo-keywords-for-agenda nil)
2128 (defvar org-done-keywords-for-agenda nil)
2129 (defvar org-drawers-for-agenda nil)
2130 (defvar org-todo-keyword-alist-for-agenda nil)
2131 (defvar org-tag-alist-for-agenda nil)
2132 (defvar org-agenda-contributing-files nil)
2133 (defvar org-not-done-keywords nil)
2134 (make-variable-buffer-local 'org-not-done-keywords)
2135 (defvar org-done-keywords nil)
2136 (make-variable-buffer-local 'org-done-keywords)
2137 (defvar org-todo-heads nil)
2138 (make-variable-buffer-local 'org-todo-heads)
2139 (defvar org-todo-sets nil)
2140 (make-variable-buffer-local 'org-todo-sets)
2141 (defvar org-todo-log-states nil)
2142 (make-variable-buffer-local 'org-todo-log-states)
2143 (defvar org-todo-kwd-alist nil)
2144 (make-variable-buffer-local 'org-todo-kwd-alist)
2145 (defvar org-todo-key-alist nil)
2146 (make-variable-buffer-local 'org-todo-key-alist)
2147 (defvar org-todo-key-trigger nil)
2148 (make-variable-buffer-local 'org-todo-key-trigger)
2150 (defcustom org-todo-interpretation 'sequence
2151 "Controls how TODO keywords are interpreted.
2152 This variable is in principle obsolete and is only used for
2153 backward compatibility, if the interpretation of todo keywords is
2154 not given already in `org-todo-keywords'. See that variable for
2155 more information."
2156 :group 'org-todo
2157 :group 'org-keywords
2158 :type '(choice (const sequence)
2159 (const type)))
2161 (defcustom org-use-fast-todo-selection t
2162 "Non-nil means use the fast todo selection scheme with C-c C-t.
2163 This variable describes if and under what circumstances the cycling
2164 mechanism for TODO keywords will be replaced by a single-key, direct
2165 selection scheme.
2167 When nil, fast selection is never used.
2169 When the symbol `prefix', it will be used when `org-todo' is called
2170 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2171 `C-u t' in an agenda buffer.
2173 When t, fast selection is used by default. In this case, the prefix
2174 argument forces cycling instead.
2176 In all cases, the special interface is only used if access keys have
2177 actually been assigned by the user, i.e. if keywords in the configuration
2178 are followed by a letter in parenthesis, like TODO(t)."
2179 :group 'org-todo
2180 :type '(choice
2181 (const :tag "Never" nil)
2182 (const :tag "By default" t)
2183 (const :tag "Only with C-u C-c C-t" prefix)))
2185 (defcustom org-provide-todo-statistics t
2186 "Non-nil means update todo statistics after insert and toggle.
2187 ALL-HEADLINES means update todo statistics by including headlines
2188 with no TODO keyword as well, counting them as not done.
2189 A list of TODO keywords means the same, but skip keywords that are
2190 not in this list.
2192 When this is set, todo statistics is updated in the parent of the
2193 current entry each time a todo state is changed."
2194 :group 'org-todo
2195 :type '(choice
2196 (const :tag "Yes, only for TODO entries" t)
2197 (const :tag "Yes, including all entries" 'all-headlines)
2198 (repeat :tag "Yes, for TODOs in this list"
2199 (string :tag "TODO keyword"))
2200 (other :tag "No TODO statistics" nil)))
2202 (defcustom org-hierarchical-todo-statistics t
2203 "Non-nil means TODO statistics covers just direct children.
2204 When nil, all entries in the subtree are considered.
2205 This has only an effect if `org-provide-todo-statistics' is set.
2206 To set this to nil for only a single subtree, use a COOKIE_DATA
2207 property and include the word \"recursive\" into the value."
2208 :group 'org-todo
2209 :type 'boolean)
2211 (defcustom org-after-todo-state-change-hook nil
2212 "Hook which is run after the state of a TODO item was changed.
2213 The new state (a string with a TODO keyword, or nil) is available in the
2214 Lisp variable `org-state'."
2215 :group 'org-todo
2216 :type 'hook)
2218 (defvar org-blocker-hook nil
2219 "Hook for functions that are allowed to block a state change.
2221 Each function gets as its single argument a property list, see
2222 `org-trigger-hook' for more information about this list.
2224 If any of the functions in this hook returns nil, the state change
2225 is blocked.")
2227 (defvar org-trigger-hook nil
2228 "Hook for functions that are triggered by a state change.
2230 Each function gets as its single argument a property list with at least
2231 the following elements:
2233 (:type type-of-change :position pos-at-entry-start
2234 :from old-state :to new-state)
2236 Depending on the type, more properties may be present.
2238 This mechanism is currently implemented for:
2240 TODO state changes
2241 ------------------
2242 :type todo-state-change
2243 :from previous state (keyword as a string), or nil, or a symbol
2244 'todo' or 'done', to indicate the general type of state.
2245 :to new state, like in :from")
2247 (defcustom org-enforce-todo-dependencies nil
2248 "Non-nil means undone TODO entries will block switching the parent to DONE.
2249 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2250 be blocked if any prior sibling is not yet done.
2251 Finally, if the parent is blocked because of ordered siblings of its own,
2252 the child will also be blocked."
2253 :set (lambda (var val)
2254 (set var val)
2255 (if val
2256 (add-hook 'org-blocker-hook
2257 'org-block-todo-from-children-or-siblings-or-parent)
2258 (remove-hook 'org-blocker-hook
2259 'org-block-todo-from-children-or-siblings-or-parent)))
2260 :group 'org-todo
2261 :type 'boolean)
2263 (defcustom org-enforce-todo-checkbox-dependencies nil
2264 "Non-nil means unchecked boxes will block switching the parent to DONE.
2265 When this is nil, checkboxes have no influence on switching TODO states.
2266 When non-nil, you first need to check off all check boxes before the TODO
2267 entry can be switched to DONE.
2268 This variable needs to be set before org.el is loaded, and you need to
2269 restart Emacs after a change to make the change effective. The only way
2270 to change is while Emacs is running is through the customize interface."
2271 :set (lambda (var val)
2272 (set var val)
2273 (if val
2274 (add-hook 'org-blocker-hook
2275 'org-block-todo-from-checkboxes)
2276 (remove-hook 'org-blocker-hook
2277 'org-block-todo-from-checkboxes)))
2278 :group 'org-todo
2279 :type 'boolean)
2281 (defcustom org-treat-insert-todo-heading-as-state-change nil
2282 "Non-nil means inserting a TODO heading is treated as state change.
2283 So when the command \\[org-insert-todo-heading] is used, state change
2284 logging will apply if appropriate. When nil, the new TODO item will
2285 be inserted directly, and no logging will take place."
2286 :group 'org-todo
2287 :type 'boolean)
2289 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2290 "Non-nil means switching TODO states with S-cursor counts as state change.
2291 This is the default behavior. However, setting this to nil allows a
2292 convenient way to select a TODO state and bypass any logging associated
2293 with that."
2294 :group 'org-todo
2295 :type 'boolean)
2297 (defcustom org-todo-state-tags-triggers nil
2298 "Tag changes that should be triggered by TODO state changes.
2299 This is a list. Each entry is
2301 (state-change (tag . flag) .......)
2303 State-change can be a string with a state, and empty string to indicate the
2304 state that has no TODO keyword, or it can be one of the symbols `todo'
2305 or `done', meaning any not-done or done state, respectively."
2306 :group 'org-todo
2307 :group 'org-tags
2308 :type '(repeat
2309 (cons (choice :tag "When changing to"
2310 (const :tag "Not-done state" todo)
2311 (const :tag "Done state" done)
2312 (string :tag "State"))
2313 (repeat
2314 (cons :tag "Tag action"
2315 (string :tag "Tag")
2316 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2318 (defcustom org-log-done nil
2319 "Information to record when a task moves to the DONE state.
2321 Possible values are:
2323 nil Don't add anything, just change the keyword
2324 time Add a time stamp to the task
2325 note Prompt for a note and add it with template `org-log-note-headings'
2327 This option can also be set with on a per-file-basis with
2329 #+STARTUP: nologdone
2330 #+STARTUP: logdone
2331 #+STARTUP: lognotedone
2333 You can have local logging settings for a subtree by setting the LOGGING
2334 property to one or more of these keywords."
2335 :group 'org-todo
2336 :group 'org-progress
2337 :type '(choice
2338 (const :tag "No logging" nil)
2339 (const :tag "Record CLOSED timestamp" time)
2340 (const :tag "Record CLOSED timestamp with note." note)))
2342 ;; Normalize old uses of org-log-done.
2343 (cond
2344 ((eq org-log-done t) (setq org-log-done 'time))
2345 ((and (listp org-log-done) (memq 'done org-log-done))
2346 (setq org-log-done 'note)))
2348 (defcustom org-log-reschedule nil
2349 "Information to record when the scheduling date of a tasks is modified.
2351 Possible values are:
2353 nil Don't add anything, just change the date
2354 time Add a time stamp to the task
2355 note Prompt for a note and add it with template `org-log-note-headings'
2357 This option can also be set with on a per-file-basis with
2359 #+STARTUP: nologreschedule
2360 #+STARTUP: logreschedule
2361 #+STARTUP: lognotereschedule"
2362 :group 'org-todo
2363 :group 'org-progress
2364 :type '(choice
2365 (const :tag "No logging" nil)
2366 (const :tag "Record timestamp" time)
2367 (const :tag "Record timestamp with note." note)))
2369 (defcustom org-log-redeadline nil
2370 "Information to record when the deadline date of a tasks is modified.
2372 Possible values are:
2374 nil Don't add anything, just change the date
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologredeadline
2381 #+STARTUP: logredeadline
2382 #+STARTUP: lognoteredeadline
2384 You can have local logging settings for a subtree by setting the LOGGING
2385 property to one or more of these keywords."
2386 :group 'org-todo
2387 :group 'org-progress
2388 :type '(choice
2389 (const :tag "No logging" nil)
2390 (const :tag "Record timestamp" time)
2391 (const :tag "Record timestamp with note." note)))
2393 (defcustom org-log-note-clock-out nil
2394 "Non-nil means record a note when clocking out of an item.
2395 This can also be configured on a per-file basis by adding one of
2396 the following lines anywhere in the buffer:
2398 #+STARTUP: lognoteclock-out
2399 #+STARTUP: nolognoteclock-out"
2400 :group 'org-todo
2401 :group 'org-progress
2402 :type 'boolean)
2404 (defcustom org-log-done-with-time t
2405 "Non-nil means the CLOSED time stamp will contain date and time.
2406 When nil, only the date will be recorded."
2407 :group 'org-progress
2408 :type 'boolean)
2410 (defcustom org-log-note-headings
2411 '((done . "CLOSING NOTE %t")
2412 (state . "State %-12s from %-12S %t")
2413 (note . "Note taken on %t")
2414 (reschedule . "Rescheduled from %S on %t")
2415 (delschedule . "Not scheduled, was %S on %t")
2416 (redeadline . "New deadline from %S on %t")
2417 (deldeadline . "Removed deadline, was %S on %t")
2418 (refile . "Refiled on %t")
2419 (clock-out . ""))
2420 "Headings for notes added to entries.
2421 The value is an alist, with the car being a symbol indicating the note
2422 context, and the cdr is the heading to be used. The heading may also be the
2423 empty string.
2424 %t in the heading will be replaced by a time stamp.
2425 %T will be an active time stamp instead the default inactive one
2426 %d will be replaced by a short-format time stamp.
2427 %D will be replaced by an active short-format time stamp.
2428 %s will be replaced by the new TODO state, in double quotes.
2429 %S will be replaced by the old TODO state, in double quotes.
2430 %u will be replaced by the user name.
2431 %U will be replaced by the full user name.
2433 In fact, it is not a good idea to change the `state' entry, because
2434 agenda log mode depends on the format of these entries."
2435 :group 'org-todo
2436 :group 'org-progress
2437 :type '(list :greedy t
2438 (cons (const :tag "Heading when closing an item" done) string)
2439 (cons (const :tag
2440 "Heading when changing todo state (todo sequence only)"
2441 state) string)
2442 (cons (const :tag "Heading when just taking a note" note) string)
2443 (cons (const :tag "Heading when clocking out" clock-out) string)
2444 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2445 (cons (const :tag "Heading when rescheduling" reschedule) string)
2446 (cons (const :tag "Heading when changing deadline" redeadline) string)
2447 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2448 (cons (const :tag "Heading when refiling" refile) string)))
2450 (unless (assq 'note org-log-note-headings)
2451 (push '(note . "%t") org-log-note-headings))
2453 (defcustom org-log-into-drawer nil
2454 "Non-nil means insert state change notes and time stamps into a drawer.
2455 When nil, state changes notes will be inserted after the headline and
2456 any scheduling and clock lines, but not inside a drawer.
2458 The value of this variable should be the name of the drawer to use.
2459 LOGBOOK is proposed as the default drawer for this purpose, you can
2460 also set this to a string to define the drawer of your choice.
2462 A value of t is also allowed, representing \"LOGBOOK\".
2464 If this variable is set, `org-log-state-notes-insert-after-drawers'
2465 will be ignored.
2467 You can set the property LOG_INTO_DRAWER to overrule this setting for
2468 a subtree."
2469 :group 'org-todo
2470 :group 'org-progress
2471 :type '(choice
2472 (const :tag "Not into a drawer" nil)
2473 (const :tag "LOGBOOK" t)
2474 (string :tag "Other")))
2476 (if (fboundp 'defvaralias)
2477 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2479 (defun org-log-into-drawer ()
2480 "Return the value of `org-log-into-drawer', but let properties overrule.
2481 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2482 used instead of the default value."
2483 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2484 (cond
2485 ((or (not p) (equal p "nil")) org-log-into-drawer)
2486 ((equal p "t") "LOGBOOK")
2487 (t p))))
2489 (defcustom org-log-state-notes-insert-after-drawers nil
2490 "Non-nil means insert state change notes after any drawers in entry.
2491 Only the drawers that *immediately* follow the headline and the
2492 deadline/scheduled line are skipped.
2493 When nil, insert notes right after the heading and perhaps the line
2494 with deadline/scheduling if present.
2496 This variable will have no effect if `org-log-into-drawer' is
2497 set."
2498 :group 'org-todo
2499 :group 'org-progress
2500 :type 'boolean)
2502 (defcustom org-log-states-order-reversed t
2503 "Non-nil means the latest state note will be directly after heading.
2504 When nil, the state change notes will be ordered according to time."
2505 :group 'org-todo
2506 :group 'org-progress
2507 :type 'boolean)
2509 (defcustom org-todo-repeat-to-state nil
2510 "The TODO state to which a repeater should return the repeating task.
2511 By default this is the first task in a TODO sequence, or the previous state
2512 in a TODO_TYP set. But you can specify another task here.
2513 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2514 :group 'org-todo
2515 :version "24.1"
2516 :type '(choice (const :tag "Head of sequence" nil)
2517 (string :tag "Specific state")))
2519 (defcustom org-log-repeat 'time
2520 "Non-nil means record moving through the DONE state when triggering repeat.
2521 An auto-repeating task is immediately switched back to TODO when
2522 marked DONE. If you are not logging state changes (by adding \"@\"
2523 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2524 record a closing note, there will be no record of the task moving
2525 through DONE. This variable forces taking a note anyway.
2527 nil Don't force a record
2528 time Record a time stamp
2529 note Prompt for a note and add it with template `org-log-note-headings'
2531 This option can also be set with on a per-file-basis with
2533 #+STARTUP: nologrepeat
2534 #+STARTUP: logrepeat
2535 #+STARTUP: lognoterepeat
2537 You can have local logging settings for a subtree by setting the LOGGING
2538 property to one or more of these keywords."
2539 :group 'org-todo
2540 :group 'org-progress
2541 :type '(choice
2542 (const :tag "Don't force a record" nil)
2543 (const :tag "Force recording the DONE state" time)
2544 (const :tag "Force recording a note with the DONE state" note)))
2547 (defgroup org-priorities nil
2548 "Priorities in Org-mode."
2549 :tag "Org Priorities"
2550 :group 'org-todo)
2552 (defcustom org-enable-priority-commands t
2553 "Non-nil means priority commands are active.
2554 When nil, these commands will be disabled, so that you never accidentally
2555 set a priority."
2556 :group 'org-priorities
2557 :type 'boolean)
2559 (defcustom org-highest-priority ?A
2560 "The highest priority of TODO items. A character like ?A, ?B etc.
2561 Must have a smaller ASCII number than `org-lowest-priority'."
2562 :group 'org-priorities
2563 :type 'character)
2565 (defcustom org-lowest-priority ?C
2566 "The lowest priority of TODO items. A character like ?A, ?B etc.
2567 Must have a larger ASCII number than `org-highest-priority'."
2568 :group 'org-priorities
2569 :type 'character)
2571 (defcustom org-default-priority ?B
2572 "The default priority of TODO items.
2573 This is the priority an item gets if no explicit priority is given.
2574 When starting to cycle on an empty priority the first step in the cycle
2575 depends on `org-priority-start-cycle-with-default'. The resulting first
2576 step priority must not exceed the range from `org-highest-priority' to
2577 `org-lowest-priority' which means that `org-default-priority' has to be
2578 in this range exclusive or inclusive the range boundaries. Else the
2579 first step refuses to set the default and the second will fall back
2580 to (depending on the command used) the highest or lowest priority."
2581 :group 'org-priorities
2582 :type 'character)
2584 (defcustom org-priority-start-cycle-with-default t
2585 "Non-nil means start with default priority when starting to cycle.
2586 When this is nil, the first step in the cycle will be (depending on the
2587 command used) one higher or lower than the default priority.
2588 See also `org-default-priority'."
2589 :group 'org-priorities
2590 :type 'boolean)
2592 (defcustom org-get-priority-function nil
2593 "Function to extract the priority from a string.
2594 The string is normally the headline. If this is nil Org computes the
2595 priority from the priority cookie like [#A] in the headline. It returns
2596 an integer, increasing by 1000 for each priority level.
2597 The user can set a different function here, which should take a string
2598 as an argument and return the numeric priority."
2599 :group 'org-priorities
2600 :version "24.1"
2601 :type 'function)
2603 (defgroup org-time nil
2604 "Options concerning time stamps and deadlines in Org-mode."
2605 :tag "Org Time"
2606 :group 'org)
2608 (defcustom org-insert-labeled-timestamps-at-point nil
2609 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2610 When nil, these labeled time stamps are forces into the second line of an
2611 entry, just after the headline. When scheduling from the global TODO list,
2612 the time stamp will always be forced into the second line."
2613 :group 'org-time
2614 :type 'boolean)
2616 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2617 "Formats for `format-time-string' which are used for time stamps.
2618 It is not recommended to change this constant.")
2620 (defcustom org-time-stamp-rounding-minutes '(0 5)
2621 "Number of minutes to round time stamps to.
2622 These are two values, the first applies when first creating a time stamp.
2623 The second applies when changing it with the commands `S-up' and `S-down'.
2624 When changing the time stamp, this means that it will change in steps
2625 of N minutes, as given by the second value.
2627 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2628 numbers should be factors of 60, so for example 5, 10, 15.
2630 When this is larger than 1, you can still force an exact time stamp by using
2631 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2632 and by using a prefix arg to `S-up/down' to specify the exact number
2633 of minutes to shift."
2634 :group 'org-time
2635 :get #'(lambda (var) ; Make sure both elements are there
2636 (if (integerp (default-value var))
2637 (list (default-value var) 5)
2638 (default-value var)))
2639 :type '(list
2640 (integer :tag "when inserting times")
2641 (integer :tag "when modifying times")))
2643 ;; Normalize old customizations of this variable.
2644 (when (integerp org-time-stamp-rounding-minutes)
2645 (setq org-time-stamp-rounding-minutes
2646 (list org-time-stamp-rounding-minutes
2647 org-time-stamp-rounding-minutes)))
2649 (defcustom org-display-custom-times nil
2650 "Non-nil means overlay custom formats over all time stamps.
2651 The formats are defined through the variable `org-time-stamp-custom-formats'.
2652 To turn this on on a per-file basis, insert anywhere in the file:
2653 #+STARTUP: customtime"
2654 :group 'org-time
2655 :set 'set-default
2656 :type 'sexp)
2657 (make-variable-buffer-local 'org-display-custom-times)
2659 (defcustom org-time-stamp-custom-formats
2660 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2661 "Custom formats for time stamps. See `format-time-string' for the syntax.
2662 These are overlaid over the default ISO format if the variable
2663 `org-display-custom-times' is set. Time like %H:%M should be at the
2664 end of the second format. The custom formats are also honored by export
2665 commands, if custom time display is turned on at the time of export."
2666 :group 'org-time
2667 :type 'sexp)
2669 (defun org-time-stamp-format (&optional long inactive)
2670 "Get the right format for a time string."
2671 (let ((f (if long (cdr org-time-stamp-formats)
2672 (car org-time-stamp-formats))))
2673 (if inactive
2674 (concat "[" (substring f 1 -1) "]")
2675 f)))
2677 (defcustom org-time-clocksum-format "%d:%02d"
2678 "The format string used when creating CLOCKSUM lines.
2679 This is also used when org-mode generates a time duration."
2680 :group 'org-time
2681 :type 'string)
2683 (defcustom org-time-clocksum-use-fractional nil
2684 "If non-nil, \\[org-clock-display] uses fractional times.
2685 org-mode generates a time duration."
2686 :group 'org-time
2687 :type 'boolean)
2689 (defcustom org-time-clocksum-fractional-format "%.2f"
2690 "The format string used when creating CLOCKSUM lines, or when
2691 org-mode generates a time duration."
2692 :group 'org-time
2693 :type 'string)
2695 (defcustom org-deadline-warning-days 14
2696 "No. of days before expiration during which a deadline becomes active.
2697 This variable governs the display in sparse trees and in the agenda.
2698 When 0 or negative, it means use this number (the absolute value of it)
2699 even if a deadline has a different individual lead time specified.
2701 Custom commands can set this variable in the options section."
2702 :group 'org-time
2703 :group 'org-agenda-daily/weekly
2704 :type 'integer)
2706 (defcustom org-read-date-prefer-future t
2707 "Non-nil means assume future for incomplete date input from user.
2708 This affects the following situations:
2709 1. The user gives a month but not a year.
2710 For example, if it is April and you enter \"feb 2\", this will be read
2711 as Feb 2, *next* year. \"May 5\", however, will be this year.
2712 2. The user gives a day, but no month.
2713 For example, if today is the 15th, and you enter \"3\", Org-mode will
2714 read this as the third of *next* month. However, if you enter \"17\",
2715 it will be considered as *this* month.
2717 If you set this variable to the symbol `time', then also the following
2718 will work:
2720 3. If the user gives a time.
2721 If the time is before now, it will be interpreted as tomorrow.
2723 Currently none of this works for ISO week specifications.
2725 When this option is nil, the current day, month and year will always be
2726 used as defaults.
2728 See also `org-agenda-jump-prefer-future'."
2729 :group 'org-time
2730 :type '(choice
2731 (const :tag "Never" nil)
2732 (const :tag "Check month and day" t)
2733 (const :tag "Check month, day, and time" time)))
2735 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2736 "Should the agenda jump command prefer the future for incomplete dates?
2737 The default is to do the same as configured in `org-read-date-prefer-future'.
2738 But you can also set a deviating value here.
2739 This may t or nil, or the symbol `org-read-date-prefer-future'."
2740 :group 'org-agenda
2741 :group 'org-time
2742 :version "24.1"
2743 :type '(choice
2744 (const :tag "Use org-read-date-prefer-future"
2745 org-read-date-prefer-future)
2746 (const :tag "Never" nil)
2747 (const :tag "Always" t)))
2749 (defcustom org-read-date-force-compatible-dates t
2750 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2752 Depending on the system Emacs is running on, certain dates cannot
2753 be represented with the type used internally to represent time.
2754 Dates between 1970-1-1 and 2038-1-1 can always be represented
2755 correctly. Some systems allow for earlier dates, some for later,
2756 some for both. One way to find out it to insert any date into an
2757 Org buffer, putting the cursor on the year and hitting S-up and
2758 S-down to test the range.
2760 When this variable is set to t, the date/time prompt will not let
2761 you specify dates outside the 1970-2037 range, so it is certain that
2762 these dates will work in whatever version of Emacs you are
2763 running, and also that you can move a file from one Emacs implementation
2764 to another. WHenever Org is forcing the year for you, it will display
2765 a message and beep.
2767 When this variable is nil, Org will check if the date is
2768 representable in the specific Emacs implementation you are using.
2769 If not, it will force a year, usually the current year, and beep
2770 to remind you. Currently this setting is not recommended because
2771 the likelihood that you will open your Org files in an Emacs that
2772 has limited date range is not negligible.
2774 A workaround for this problem is to use diary sexp dates for time
2775 stamps outside of this range."
2776 :group 'org-time
2777 :version "24.1"
2778 :type 'boolean)
2780 (defcustom org-read-date-display-live t
2781 "Non-nil means display current interpretation of date prompt live.
2782 This display will be in an overlay, in the minibuffer."
2783 :group 'org-time
2784 :type 'boolean)
2786 (defcustom org-read-date-popup-calendar t
2787 "Non-nil means pop up a calendar when prompting for a date.
2788 In the calendar, the date can be selected with mouse-1. However, the
2789 minibuffer will also be active, and you can simply enter the date as well.
2790 When nil, only the minibuffer will be available."
2791 :group 'org-time
2792 :type 'boolean)
2793 (if (fboundp 'defvaralias)
2794 (defvaralias 'org-popup-calendar-for-date-prompt
2795 'org-read-date-popup-calendar))
2797 (defcustom org-read-date-minibuffer-setup-hook nil
2798 "Hook to be used to set up keys for the date/time interface.
2799 Add key definitions to `minibuffer-local-map', which will be a temporary
2800 copy."
2801 :group 'org-time
2802 :type 'hook)
2804 (defcustom org-extend-today-until 0
2805 "The hour when your day really ends. Must be an integer.
2806 This has influence for the following applications:
2807 - When switching the agenda to \"today\". It it is still earlier than
2808 the time given here, the day recognized as TODAY is actually yesterday.
2809 - When a date is read from the user and it is still before the time given
2810 here, the current date and time will be assumed to be yesterday, 23:59.
2811 Also, timestamps inserted in capture templates follow this rule.
2813 IMPORTANT: This is a feature whose implementation is and likely will
2814 remain incomplete. Really, it is only here because past midnight seems to
2815 be the favorite working time of John Wiegley :-)"
2816 :group 'org-time
2817 :type 'integer)
2819 (defcustom org-use-effective-time nil
2820 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2821 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2822 \"effective time\" of any timestamps between midnight and 8am will be
2823 23:59 of the previous day."
2824 :group 'org-time
2825 :version "24.1"
2826 :type 'boolean)
2828 (defcustom org-edit-timestamp-down-means-later nil
2829 "Non-nil means S-down will increase the time in a time stamp.
2830 When nil, S-up will increase."
2831 :group 'org-time
2832 :type 'boolean)
2834 (defcustom org-calendar-follow-timestamp-change t
2835 "Non-nil means make the calendar window follow timestamp changes.
2836 When a timestamp is modified and the calendar window is visible, it will be
2837 moved to the new date."
2838 :group 'org-time
2839 :type 'boolean)
2841 (defgroup org-tags nil
2842 "Options concerning tags in Org-mode."
2843 :tag "Org Tags"
2844 :group 'org)
2846 (defcustom org-tag-alist nil
2847 "List of tags allowed in Org-mode files.
2848 When this list is nil, Org-mode will base TAG input on what is already in the
2849 buffer.
2850 The value of this variable is an alist, the car of each entry must be a
2851 keyword as a string, the cdr may be a character that is used to select
2852 that tag through the fast-tag-selection interface.
2853 See the manual for details."
2854 :group 'org-tags
2855 :type '(repeat
2856 (choice
2857 (cons (string :tag "Tag name")
2858 (character :tag "Access char"))
2859 (list :tag "Start radio group"
2860 (const :startgroup)
2861 (option (string :tag "Group description")))
2862 (list :tag "End radio group"
2863 (const :endgroup)
2864 (option (string :tag "Group description")))
2865 (const :tag "New line" (:newline)))))
2867 (defcustom org-tag-persistent-alist nil
2868 "List of tags that will always appear in all Org-mode files.
2869 This is in addition to any in buffer settings or customizations
2870 of `org-tag-alist'.
2871 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2872 The value of this variable is an alist, the car of each entry must be a
2873 keyword as a string, the cdr may be a character that is used to select
2874 that tag through the fast-tag-selection interface.
2875 See the manual for details.
2876 To disable these tags on a per-file basis, insert anywhere in the file:
2877 #+STARTUP: noptag"
2878 :group 'org-tags
2879 :type '(repeat
2880 (choice
2881 (cons (string :tag "Tag name")
2882 (character :tag "Access char"))
2883 (const :tag "Start radio group" (:startgroup))
2884 (const :tag "End radio group" (:endgroup))
2885 (const :tag "New line" (:newline)))))
2887 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2888 "If non-nil, always offer completion for all tags of all agenda files.
2889 Instead of customizing this variable directly, you might want to
2890 set it locally for capture buffers, because there no list of
2891 tags in that file can be created dynamically (there are none).
2893 (add-hook 'org-capture-mode-hook
2894 (lambda ()
2895 (set (make-local-variable
2896 'org-complete-tags-always-offer-all-agenda-tags)
2897 t)))"
2898 :group 'org-tags
2899 :version "24.1"
2900 :type 'boolean)
2902 (defvar org-file-tags nil
2903 "List of tags that can be inherited by all entries in the file.
2904 The tags will be inherited if the variable `org-use-tag-inheritance'
2905 says they should be.
2906 This variable is populated from #+FILETAGS lines.")
2908 (defcustom org-use-fast-tag-selection 'auto
2909 "Non-nil means use fast tag selection scheme.
2910 This is a special interface to select and deselect tags with single keys.
2911 When nil, fast selection is never used.
2912 When the symbol `auto', fast selection is used if and only if selection
2913 characters for tags have been configured, either through the variable
2914 `org-tag-alist' or through a #+TAGS line in the buffer.
2915 When t, fast selection is always used and selection keys are assigned
2916 automatically if necessary."
2917 :group 'org-tags
2918 :type '(choice
2919 (const :tag "Always" t)
2920 (const :tag "Never" nil)
2921 (const :tag "When selection characters are configured" 'auto)))
2923 (defcustom org-fast-tag-selection-single-key nil
2924 "Non-nil means fast tag selection exits after first change.
2925 When nil, you have to press RET to exit it.
2926 During fast tag selection, you can toggle this flag with `C-c'.
2927 This variable can also have the value `expert'. In this case, the window
2928 displaying the tags menu is not even shown, until you press C-c again."
2929 :group 'org-tags
2930 :type '(choice
2931 (const :tag "No" nil)
2932 (const :tag "Yes" t)
2933 (const :tag "Expert" expert)))
2935 (defvar org-fast-tag-selection-include-todo nil
2936 "Non-nil means fast tags selection interface will also offer TODO states.
2937 This is an undocumented feature, you should not rely on it.")
2939 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2940 "The column to which tags should be indented in a headline.
2941 If this number is positive, it specifies the column. If it is negative,
2942 it means that the tags should be flushright to that column. For example,
2943 -80 works well for a normal 80 character screen.
2944 When 0, place tags directly after headline text, with only one space in
2945 between."
2946 :group 'org-tags
2947 :type 'integer)
2949 (defcustom org-auto-align-tags t
2950 "Non-nil keeps tags aligned when modifying headlines.
2951 Some operations (i.e. demoting) change the length of a headline and
2952 therefore shift the tags around. With this option turned on, after
2953 each such operation the tags are again aligned to `org-tags-column'."
2954 :group 'org-tags
2955 :type 'boolean)
2957 (defcustom org-use-tag-inheritance t
2958 "Non-nil means tags in levels apply also for sublevels.
2959 When nil, only the tags directly given in a specific line apply there.
2960 This may also be a list of tags that should be inherited, or a regexp that
2961 matches tags that should be inherited. Additional control is possible
2962 with the variable `org-tags-exclude-from-inheritance' which gives an
2963 explicit list of tags to be excluded from inheritance., even if the value of
2964 `org-use-tag-inheritance' would select it for inheritance.
2966 If this option is t, a match early-on in a tree can lead to a large
2967 number of matches in the subtree when constructing the agenda or creating
2968 a sparse tree. If you only want to see the first match in a tree during
2969 a search, check out the variable `org-tags-match-list-sublevels'."
2970 :group 'org-tags
2971 :type '(choice
2972 (const :tag "Not" nil)
2973 (const :tag "Always" t)
2974 (repeat :tag "Specific tags" (string :tag "Tag"))
2975 (regexp :tag "Tags matched by regexp")))
2977 (defcustom org-tags-exclude-from-inheritance nil
2978 "List of tags that should never be inherited.
2979 This is a way to exclude a few tags from inheritance. For way to do
2980 the opposite, to actively allow inheritance for selected tags,
2981 see the variable `org-use-tag-inheritance'."
2982 :group 'org-tags
2983 :type '(repeat (string :tag "Tag")))
2985 (defun org-tag-inherit-p (tag)
2986 "Check if TAG is one that should be inherited."
2987 (cond
2988 ((member tag org-tags-exclude-from-inheritance) nil)
2989 ((eq org-use-tag-inheritance t) t)
2990 ((not org-use-tag-inheritance) nil)
2991 ((stringp org-use-tag-inheritance)
2992 (string-match org-use-tag-inheritance tag))
2993 ((listp org-use-tag-inheritance)
2994 (member tag org-use-tag-inheritance))
2995 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2997 (defcustom org-tags-match-list-sublevels t
2998 "Non-nil means list also sublevels of headlines matching a search.
2999 This variable applies to tags/property searches, and also to stuck
3000 projects because this search is based on a tags match as well.
3002 When set to the symbol `indented', sublevels are indented with
3003 leading dots.
3005 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3006 the sublevels of a headline matching a tag search often also match
3007 the same search. Listing all of them can create very long lists.
3008 Setting this variable to nil causes subtrees of a match to be skipped.
3010 This variable is semi-obsolete and probably should always be true. It
3011 is better to limit inheritance to certain tags using the variables
3012 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3013 :group 'org-tags
3014 :type '(choice
3015 (const :tag "No, don't list them" nil)
3016 (const :tag "Yes, do list them" t)
3017 (const :tag "List them, indented with leading dots" indented)))
3019 (defcustom org-tags-sort-function nil
3020 "When set, tags are sorted using this function as a comparator."
3021 :group 'org-tags
3022 :type '(choice
3023 (const :tag "No sorting" nil)
3024 (const :tag "Alphabetical" string<)
3025 (const :tag "Reverse alphabetical" string>)
3026 (function :tag "Custom function" nil)))
3028 (defvar org-tags-history nil
3029 "History of minibuffer reads for tags.")
3030 (defvar org-last-tags-completion-table nil
3031 "The last used completion table for tags.")
3032 (defvar org-after-tags-change-hook nil
3033 "Hook that is run after the tags in a line have changed.")
3035 (defgroup org-properties nil
3036 "Options concerning properties in Org-mode."
3037 :tag "Org Properties"
3038 :group 'org)
3040 (defcustom org-property-format "%-10s %s"
3041 "How property key/value pairs should be formatted by `indent-line'.
3042 When `indent-line' hits a property definition, it will format the line
3043 according to this format, mainly to make sure that the values are
3044 lined-up with respect to each other."
3045 :group 'org-properties
3046 :type 'string)
3048 (defcustom org-properties-postprocess-alist nil
3049 "Alist of properties and functions to adjust inserted values.
3050 Elements of this alist must be of the form
3052 ([string] [function])
3054 where [string] must be a property name and [function] must be a
3055 lambda expression: this lambda expression must take one argument,
3056 the value to adjust, and return the new value as a string.
3058 For example, this element will allow the property \"Remaining\"
3059 to be updated wrt the relation between the \"Effort\" property
3060 and the clock summary:
3062 ((\"Remaining\" (lambda(value)
3063 (let ((clocksum (org-clock-sum-current-item))
3064 (effort (org-duration-string-to-minutes
3065 (org-entry-get (point) \"Effort\"))))
3066 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3067 :group 'org-properties
3068 :version "24.1"
3069 :type '(alist :key-type (string :tag "Property")
3070 :value-type (function :tag "Function")))
3072 (defcustom org-use-property-inheritance nil
3073 "Non-nil means properties apply also for sublevels.
3075 This setting is chiefly used during property searches. Turning it on can
3076 cause significant overhead when doing a search, which is why it is not
3077 on by default.
3079 When nil, only the properties directly given in the current entry count.
3080 When t, every property is inherited. The value may also be a list of
3081 properties that should have inheritance, or a regular expression matching
3082 properties that should be inherited.
3084 However, note that some special properties use inheritance under special
3085 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3086 and the properties ending in \"_ALL\" when they are used as descriptor
3087 for valid values of a property.
3089 Note for programmers:
3090 When querying an entry with `org-entry-get', you can control if inheritance
3091 should be used. By default, `org-entry-get' looks only at the local
3092 properties. You can request inheritance by setting the inherit argument
3093 to t (to force inheritance) or to `selective' (to respect the setting
3094 in this variable)."
3095 :group 'org-properties
3096 :type '(choice
3097 (const :tag "Not" nil)
3098 (const :tag "Always" t)
3099 (repeat :tag "Specific properties" (string :tag "Property"))
3100 (regexp :tag "Properties matched by regexp")))
3102 (defun org-property-inherit-p (property)
3103 "Check if PROPERTY is one that should be inherited."
3104 (cond
3105 ((eq org-use-property-inheritance t) t)
3106 ((not org-use-property-inheritance) nil)
3107 ((stringp org-use-property-inheritance)
3108 (string-match org-use-property-inheritance property))
3109 ((listp org-use-property-inheritance)
3110 (member property org-use-property-inheritance))
3111 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3113 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3114 "The default column format, if no other format has been defined.
3115 This variable can be set on the per-file basis by inserting a line
3117 #+COLUMNS: %25ITEM ....."
3118 :group 'org-properties
3119 :type 'string)
3121 (defcustom org-columns-ellipses ".."
3122 "The ellipses to be used when a field in column view is truncated.
3123 When this is the empty string, as many characters as possible are shown,
3124 but then there will be no visual indication that the field has been truncated.
3125 When this is a string of length N, the last N characters of a truncated
3126 field are replaced by this string. If the column is narrower than the
3127 ellipses string, only part of the ellipses string will be shown."
3128 :group 'org-properties
3129 :type 'string)
3131 (defcustom org-columns-modify-value-for-display-function nil
3132 "Function that modifies values for display in column view.
3133 For example, it can be used to cut out a certain part from a time stamp.
3134 The function must take 2 arguments:
3136 column-title The title of the column (*not* the property name)
3137 value The value that should be modified.
3139 The function should return the value that should be displayed,
3140 or nil if the normal value should be used."
3141 :group 'org-properties
3142 :type 'function)
3144 (defcustom org-effort-property "Effort"
3145 "The property that is being used to keep track of effort estimates.
3146 Effort estimates given in this property need to have the format H:MM."
3147 :group 'org-properties
3148 :group 'org-progress
3149 :type '(string :tag "Property"))
3151 (defconst org-global-properties-fixed
3152 '(("VISIBILITY_ALL" . "folded children content all")
3153 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3154 "List of property/value pairs that can be inherited by any entry.
3156 These are fixed values, for the preset properties. The user variable
3157 that can be used to add to this list is `org-global-properties'.
3159 The entries in this list are cons cells where the car is a property
3160 name and cdr is a string with the value. If the value represents
3161 multiple items like an \"_ALL\" property, separate the items by
3162 spaces.")
3164 (defcustom org-global-properties nil
3165 "List of property/value pairs that can be inherited by any entry.
3167 This list will be combined with the constant `org-global-properties-fixed'.
3169 The entries in this list are cons cells where the car is a property
3170 name and cdr is a string with the value.
3172 You can set buffer-local values for the same purpose in the variable
3173 `org-file-properties' this by adding lines like
3175 #+PROPERTY: NAME VALUE"
3176 :group 'org-properties
3177 :type '(repeat
3178 (cons (string :tag "Property")
3179 (string :tag "Value"))))
3181 (defvar org-file-properties nil
3182 "List of property/value pairs that can be inherited by any entry.
3183 Valid for the current buffer.
3184 This variable is populated from #+PROPERTY lines.")
3185 (make-variable-buffer-local 'org-file-properties)
3187 (defgroup org-agenda nil
3188 "Options concerning agenda views in Org-mode."
3189 :tag "Org Agenda"
3190 :group 'org)
3192 (defvar org-category nil
3193 "Variable used by org files to set a category for agenda display.
3194 Such files should use a file variable to set it, for example
3196 # -*- mode: org; org-category: \"ELisp\"
3198 or contain a special line
3200 #+CATEGORY: ELisp
3202 If the file does not specify a category, then file's base name
3203 is used instead.")
3204 (make-variable-buffer-local 'org-category)
3205 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3207 (defcustom org-agenda-files nil
3208 "The files to be used for agenda display.
3209 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3210 \\[org-remove-file]. You can also use customize to edit the list.
3212 If an entry is a directory, all files in that directory that are matched by
3213 `org-agenda-file-regexp' will be part of the file list.
3215 If the value of the variable is not a list but a single file name, then
3216 the list of agenda files is actually stored and maintained in that file, one
3217 agenda file per line. In this file paths can be given relative to
3218 `org-directory'. Tilde expansion and environment variable substitution
3219 are also made."
3220 :group 'org-agenda
3221 :type '(choice
3222 (repeat :tag "List of files and directories" file)
3223 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3225 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3226 "Regular expression to match files for `org-agenda-files'.
3227 If any element in the list in that variable contains a directory instead
3228 of a normal file, all files in that directory that are matched by this
3229 regular expression will be included."
3230 :group 'org-agenda
3231 :type 'regexp)
3233 (defcustom org-agenda-text-search-extra-files nil
3234 "List of extra files to be searched by text search commands.
3235 These files will be search in addition to the agenda files by the
3236 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3237 Note that these files will only be searched for text search commands,
3238 not for the other agenda views like todo lists, tag searches or the weekly
3239 agenda. This variable is intended to list notes and possibly archive files
3240 that should also be searched by these two commands.
3241 In fact, if the first element in the list is the symbol `agenda-archives',
3242 than all archive files of all agenda files will be added to the search
3243 scope."
3244 :group 'org-agenda
3245 :type '(set :greedy t
3246 (const :tag "Agenda Archives" agenda-archives)
3247 (repeat :inline t (file))))
3249 (if (fboundp 'defvaralias)
3250 (defvaralias 'org-agenda-multi-occur-extra-files
3251 'org-agenda-text-search-extra-files))
3253 (defcustom org-agenda-skip-unavailable-files nil
3254 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3255 A nil value means to remove them, after a query, from the list."
3256 :group 'org-agenda
3257 :type 'boolean)
3259 (defcustom org-calendar-to-agenda-key [?c]
3260 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3261 The command `org-calendar-goto-agenda' will be bound to this key. The
3262 default is the character `c' because then `c' can be used to switch back and
3263 forth between agenda and calendar."
3264 :group 'org-agenda
3265 :type 'sexp)
3267 (defcustom org-calendar-agenda-action-key [?k]
3268 "The key to be installed in `calendar-mode-map' for agenda-action.
3269 The command `org-agenda-action' will be bound to this key. The
3270 default is the character `k' because we use the same key in the agenda."
3271 :group 'org-agenda
3272 :type 'sexp)
3274 (defcustom org-calendar-insert-diary-entry-key [?i]
3275 "The key to be installed in `calendar-mode-map' for adding diary entries.
3276 This option is irrelevant until `org-agenda-diary-file' has been configured
3277 to point to an Org-mode file. When that is the case, the command
3278 `org-agenda-diary-entry' will be bound to the key given here, by default
3279 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3280 if you want to continue doing this, you need to change this to a different
3281 key."
3282 :group 'org-agenda
3283 :type 'sexp)
3285 (defcustom org-agenda-diary-file 'diary-file
3286 "File to which to add new entries with the `i' key in agenda and calendar.
3287 When this is the symbol `diary-file', the functionality in the Emacs
3288 calendar will be used to add entries to the `diary-file'. But when this
3289 points to a file, `org-agenda-diary-entry' will be used instead."
3290 :group 'org-agenda
3291 :type '(choice
3292 (const :tag "The standard Emacs diary file" diary-file)
3293 (file :tag "Special Org file diary entries")))
3295 (eval-after-load "calendar"
3296 '(progn
3297 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3298 'org-calendar-goto-agenda)
3299 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3300 'org-agenda-action)
3301 (add-hook 'calendar-mode-hook
3302 (lambda ()
3303 (unless (eq org-agenda-diary-file 'diary-file)
3304 (define-key calendar-mode-map
3305 org-calendar-insert-diary-entry-key
3306 'org-agenda-diary-entry))))))
3308 (defgroup org-latex nil
3309 "Options for embedding LaTeX code into Org-mode."
3310 :tag "Org LaTeX"
3311 :group 'org)
3313 (defcustom org-format-latex-options
3314 '(:foreground default :background default :scale 1.0
3315 :html-foreground "Black" :html-background "Transparent"
3316 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3317 "Options for creating images from LaTeX fragments.
3318 This is a property list with the following properties:
3319 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3320 `default' means use the foreground of the default face.
3321 :background the background color, or \"Transparent\".
3322 `default' means use the background of the default face.
3323 :scale a scaling factor for the size of the images, to get more pixels
3324 :html-foreground, :html-background, :html-scale
3325 the same numbers for HTML export.
3326 :matchers a list indicating which matchers should be used to
3327 find LaTeX fragments. Valid members of this list are:
3328 \"begin\" find environments
3329 \"$1\" find single characters surrounded by $.$
3330 \"$\" find math expressions surrounded by $...$
3331 \"$$\" find math expressions surrounded by $$....$$
3332 \"\\(\" find math expressions surrounded by \\(...\\)
3333 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3334 :group 'org-latex
3335 :type 'plist)
3337 (defcustom org-format-latex-signal-error t
3338 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3339 When nil, just push out a message."
3340 :group 'org-latex
3341 :version "24.1"
3342 :type 'boolean)
3344 (defcustom org-latex-to-mathml-jar-file nil
3345 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3346 Use this to specify additional executable file say a jar file.
3348 When using MathToWeb as the converter, specify the full-path to
3349 your mathtoweb.jar file."
3350 :group 'org-latex
3351 :version "24.1"
3352 :type '(choice
3353 (const :tag "None" nil)
3354 (file :tag "JAR file" :must-match t)))
3356 (defcustom org-latex-to-mathml-convert-command nil
3357 "Command to convert LaTeX fragments to MathML.
3358 Replace format-specifiers in the command as noted below and use
3359 `shell-command' to convert LaTeX to MathML.
3360 %j: Executable file in fully expanded form as specified by
3361 `org-latex-to-mathml-jar-file'.
3362 %I: Input LaTeX file in fully expanded form
3363 %o: Output MathML file
3364 This command is used by `org-create-math-formula'.
3366 When using MathToWeb as the converter, set this to
3367 \"java -jar %j -unicode -force -df %o %I\"."
3368 :group 'org-latex
3369 :version "24.1"
3370 :type '(choice
3371 (const :tag "None" nil)
3372 (string :tag "\nShell command")))
3374 (defcustom org-latex-create-formula-image-program 'dvipng
3375 "Program to convert LaTeX fragments with.
3377 dvipng Process the LaTeX fragments to dvi file, then convert
3378 dvi files to png files using dvipng.
3379 This will also include processing of non-math environments.
3380 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3381 to convert pdf files to png files"
3382 :group 'org-latex
3383 :version "24.1"
3384 :type '(choice
3385 (const :tag "dvipng" dvipng)
3386 (const :tag "imagemagick" imagemagick)))
3388 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3389 "Path to store latex preview images. A relative path here creates many
3390 directories relative to the processed org files paths. An absolute path
3391 puts all preview images at the same place."
3392 :group 'org-latex
3393 ;; :version "24.3"
3394 :type 'string)
3396 (defun org-format-latex-mathml-available-p ()
3397 "Return t if `org-latex-to-mathml-convert-command' is usable."
3398 (save-match-data
3399 (when (and (boundp 'org-latex-to-mathml-convert-command)
3400 org-latex-to-mathml-convert-command)
3401 (let ((executable (car (split-string
3402 org-latex-to-mathml-convert-command))))
3403 (when (executable-find executable)
3404 (if (string-match
3405 "%j" org-latex-to-mathml-convert-command)
3406 (file-readable-p org-latex-to-mathml-jar-file)
3407 t))))))
3409 (defcustom org-format-latex-header "\\documentclass{article}
3410 \\usepackage[usenames]{color}
3411 \\usepackage{amsmath}
3412 \\usepackage[mathscr]{eucal}
3413 \\pagestyle{empty} % do not remove
3414 \[PACKAGES]
3415 \[DEFAULT-PACKAGES]
3416 % The settings below are copied from fullpage.sty
3417 \\setlength{\\textwidth}{\\paperwidth}
3418 \\addtolength{\\textwidth}{-3cm}
3419 \\setlength{\\oddsidemargin}{1.5cm}
3420 \\addtolength{\\oddsidemargin}{-2.54cm}
3421 \\setlength{\\evensidemargin}{\\oddsidemargin}
3422 \\setlength{\\textheight}{\\paperheight}
3423 \\addtolength{\\textheight}{-\\headheight}
3424 \\addtolength{\\textheight}{-\\headsep}
3425 \\addtolength{\\textheight}{-\\footskip}
3426 \\addtolength{\\textheight}{-3cm}
3427 \\setlength{\\topmargin}{1.5cm}
3428 \\addtolength{\\topmargin}{-2.54cm}"
3429 "The document header used for processing LaTeX fragments.
3430 It is imperative that this header make sure that no page number
3431 appears on the page. The package defined in the variables
3432 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3433 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3434 will be appended."
3435 :group 'org-latex
3436 :type 'string)
3438 (defvar org-format-latex-header-extra nil)
3440 (defun org-set-packages-alist (var val)
3441 "Set the packages alist and make sure it has 3 elements per entry."
3442 (set var (mapcar (lambda (x)
3443 (if (and (consp x) (= (length x) 2))
3444 (list (car x) (nth 1 x) t)
3446 val)))
3448 (defun org-get-packages-alist (var)
3450 "Get the packages alist and make sure it has 3 elements per entry."
3451 (mapcar (lambda (x)
3452 (if (and (consp x) (= (length x) 2))
3453 (list (car x) (nth 1 x) t)
3455 (default-value var)))
3457 ;; The following variables are defined here because is it also used
3458 ;; when formatting latex fragments. Originally it was part of the
3459 ;; LaTeX exporter, which is why the name includes "export".
3460 (defcustom org-export-latex-default-packages-alist
3461 '(("AUTO" "inputenc" t)
3462 ("T1" "fontenc" t)
3463 ("" "fixltx2e" nil)
3464 ("" "graphicx" t)
3465 ("" "longtable" nil)
3466 ("" "float" nil)
3467 ("" "wrapfig" nil)
3468 ("" "soul" t)
3469 ("" "textcomp" t)
3470 ("" "marvosym" t)
3471 ("" "wasysym" t)
3472 ("" "latexsym" t)
3473 ("" "amssymb" t)
3474 ("" "hyperref" nil)
3475 "\\tolerance=1000"
3477 "Alist of default packages to be inserted in the header.
3478 Change this only if one of the packages here causes an incompatibility
3479 with another package you are using.
3480 The packages in this list are needed by one part or another of Org-mode
3481 to function properly.
3483 - inputenc, fontenc: for basic font and character selection
3484 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3485 for interpreting the entities in `org-entities'. You can skip some of these
3486 packages if you don't use any of the symbols in it.
3487 - graphicx: for including images
3488 - float, wrapfig: for figure placement
3489 - longtable: for long tables
3490 - hyperref: for cross references
3492 Therefore you should not modify this variable unless you know what you
3493 are doing. The one reason to change it anyway is that you might be loading
3494 some other package that conflicts with one of the default packages.
3495 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3496 If SNIPPET-FLAG is t, the package also needs to be included when
3497 compiling LaTeX snippets into images for inclusion into HTML."
3498 :group 'org-export-latex
3499 :set 'org-set-packages-alist
3500 :get 'org-get-packages-alist
3501 :version "24.1"
3502 :type '(repeat
3503 (choice
3504 (list :tag "options/package pair"
3505 (string :tag "options")
3506 (string :tag "package")
3507 (boolean :tag "Snippet"))
3508 (string :tag "A line of LaTeX"))))
3510 (defcustom org-export-latex-packages-alist nil
3511 "Alist of packages to be inserted in every LaTeX header.
3512 These will be inserted after `org-export-latex-default-packages-alist'.
3513 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3514 SNIPPET-FLAG, when t, indicates that this package is also needed when
3515 turning LaTeX snippets into images for inclusion into HTML.
3516 Make sure that you only list packages here which:
3517 - you want in every file
3518 - do not conflict with the default packages in
3519 `org-export-latex-default-packages-alist'
3520 - do not conflict with the setup in `org-format-latex-header'."
3521 :group 'org-export-latex
3522 :set 'org-set-packages-alist
3523 :get 'org-get-packages-alist
3524 :type '(repeat
3525 (choice
3526 (list :tag "options/package pair"
3527 (string :tag "options")
3528 (string :tag "package")
3529 (boolean :tag "Snippet"))
3530 (string :tag "A line of LaTeX"))))
3533 (defgroup org-appearance nil
3534 "Settings for Org-mode appearance."
3535 :tag "Org Appearance"
3536 :group 'org)
3538 (defcustom org-level-color-stars-only nil
3539 "Non-nil means fontify only the stars in each headline.
3540 When nil, the entire headline is fontified.
3541 Changing it requires restart of `font-lock-mode' to become effective
3542 also in regions already fontified."
3543 :group 'org-appearance
3544 :type 'boolean)
3546 (defcustom org-hide-leading-stars nil
3547 "Non-nil means hide the first N-1 stars in a headline.
3548 This works by using the face `org-hide' for these stars. This
3549 face is white for a light background, and black for a dark
3550 background. You may have to customize the face `org-hide' to
3551 make this work.
3552 Changing it requires restart of `font-lock-mode' to become effective
3553 also in regions already fontified.
3554 You may also set this on a per-file basis by adding one of the following
3555 lines to the buffer:
3557 #+STARTUP: hidestars
3558 #+STARTUP: showstars"
3559 :group 'org-appearance
3560 :type 'boolean)
3562 (defcustom org-hidden-keywords nil
3563 "List of symbols corresponding to keywords to be hidden the org buffer.
3564 For example, a value '(title) for this list will make the document's title
3565 appear in the buffer without the initial #+TITLE: keyword."
3566 :group 'org-appearance
3567 :version "24.1"
3568 :type '(set (const :tag "#+AUTHOR" author)
3569 (const :tag "#+DATE" date)
3570 (const :tag "#+EMAIL" email)
3571 (const :tag "#+TITLE" title)))
3573 (defcustom org-custom-properties nil
3574 "List of properties (as strings) with a special meaning.
3575 The default use of these custom properties is to let the user
3576 hide them with `org-toggle-custom-properties-visibility'."
3577 :group 'org-properties
3578 :group 'org-appearance
3579 ;; :version "24.3"
3580 :type '(repeat (string :tag "Property Name")))
3582 (defcustom org-fontify-done-headline nil
3583 "Non-nil means change the face of a headline if it is marked DONE.
3584 Normally, only the TODO/DONE keyword indicates the state of a headline.
3585 When this is non-nil, the headline after the keyword is set to the
3586 `org-headline-done' as an additional indication."
3587 :group 'org-appearance
3588 :type 'boolean)
3590 (defcustom org-fontify-emphasized-text t
3591 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3592 Changing this variable requires a restart of Emacs to take effect."
3593 :group 'org-appearance
3594 :type 'boolean)
3596 (defcustom org-fontify-whole-heading-line nil
3597 "Non-nil means fontify the whole line for headings.
3598 This is useful when setting a background color for the
3599 org-level-* faces."
3600 :group 'org-appearance
3601 :type 'boolean)
3603 (defcustom org-highlight-latex-fragments-and-specials nil
3604 "Non-nil means fontify what is treated specially by the exporters."
3605 :group 'org-appearance
3606 :type 'boolean)
3608 (defcustom org-hide-emphasis-markers nil
3609 "Non-nil mean font-lock should hide the emphasis marker characters."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-pretty-entities nil
3614 "Non-nil means show entities as UTF8 characters.
3615 When nil, the \\name form remains in the buffer."
3616 :group 'org-appearance
3617 :version "24.1"
3618 :type 'boolean)
3620 (defcustom org-pretty-entities-include-sub-superscripts t
3621 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3622 :group 'org-appearance
3623 :version "24.1"
3624 :type 'boolean)
3626 (defvar org-emph-re nil
3627 "Regular expression for matching emphasis.
3628 After a match, the match groups contain these elements:
3629 0 The match of the full regular expression, including the characters
3630 before and after the proper match
3631 1 The character before the proper match, or empty at beginning of line
3632 2 The proper match, including the leading and trailing markers
3633 3 The leading marker like * or /, indicating the type of highlighting
3634 4 The text between the emphasis markers, not including the markers
3635 5 The character after the match, empty at the end of a line")
3636 (defvar org-verbatim-re nil
3637 "Regular expression for matching verbatim text.")
3638 (defvar org-emphasis-regexp-components) ; defined just below
3639 (defvar org-emphasis-alist) ; defined just below
3640 (defun org-set-emph-re (var val)
3641 "Set variable and compute the emphasis regular expression."
3642 (set var val)
3643 (when (and (boundp 'org-emphasis-alist)
3644 (boundp 'org-emphasis-regexp-components)
3645 org-emphasis-alist org-emphasis-regexp-components)
3646 (let* ((e org-emphasis-regexp-components)
3647 (pre (car e))
3648 (post (nth 1 e))
3649 (border (nth 2 e))
3650 (body (nth 3 e))
3651 (nl (nth 4 e))
3652 (body1 (concat body "*?"))
3653 (markers (mapconcat 'car org-emphasis-alist ""))
3654 (vmarkers (mapconcat
3655 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3656 org-emphasis-alist "")))
3657 ;; make sure special characters appear at the right position in the class
3658 (if (string-match "\\^" markers)
3659 (setq markers (concat (replace-match "" t t markers) "^")))
3660 (if (string-match "-" markers)
3661 (setq markers (concat (replace-match "" t t markers) "-")))
3662 (if (string-match "\\^" vmarkers)
3663 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3664 (if (string-match "-" vmarkers)
3665 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3666 (if (> nl 0)
3667 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3668 (int-to-string nl) "\\}")))
3669 ;; Make the regexp
3670 (setq org-emph-re
3671 (concat "\\([" pre "]\\|^\\)"
3672 "\\("
3673 "\\([" markers "]\\)"
3674 "\\("
3675 "[^" border "]\\|"
3676 "[^" border "]"
3677 body1
3678 "[^" border "]"
3679 "\\)"
3680 "\\3\\)"
3681 "\\([" post "]\\|$\\)"))
3682 (setq org-verbatim-re
3683 (concat "\\([" pre "]\\|^\\)"
3684 "\\("
3685 "\\([" vmarkers "]\\)"
3686 "\\("
3687 "[^" border "]\\|"
3688 "[^" border "]"
3689 body1
3690 "[^" border "]"
3691 "\\)"
3692 "\\3\\)"
3693 "\\([" post "]\\|$\\)")))))
3695 (defcustom org-emphasis-regexp-components
3696 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3697 "Components used to build the regular expression for emphasis.
3698 This is a list with five entries. Terminology: In an emphasis string
3699 like \" *strong word* \", we call the initial space PREMATCH, the final
3700 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3701 and \"trong wor\" is the body. The different components in this variable
3702 specify what is allowed/forbidden in each part:
3704 pre Chars allowed as prematch. Beginning of line will be allowed too.
3705 post Chars allowed as postmatch. End of line will be allowed too.
3706 border The chars *forbidden* as border characters.
3707 body-regexp A regexp like \".\" to match a body character. Don't use
3708 non-shy groups here, and don't allow newline here.
3709 newline The maximum number of newlines allowed in an emphasis exp.
3711 Use customize to modify this, or restart Emacs after changing it."
3712 :group 'org-appearance
3713 :set 'org-set-emph-re
3714 :type '(list
3715 (sexp :tag "Allowed chars in pre ")
3716 (sexp :tag "Allowed chars in post ")
3717 (sexp :tag "Forbidden chars in border ")
3718 (sexp :tag "Regexp for body ")
3719 (integer :tag "number of newlines allowed")
3720 (option (boolean :tag "Please ignore this button"))))
3722 (defcustom org-emphasis-alist
3723 `(("*" bold "<b>" "</b>")
3724 ("/" italic "<i>" "</i>")
3725 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3726 ("=" org-code "<code>" "</code>" verbatim)
3727 ("~" org-verbatim "<code>" "</code>" verbatim)
3728 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3729 "<del>" "</del>")
3731 "Special syntax for emphasized text.
3732 Text starting and ending with a special character will be emphasized, for
3733 example *bold*, _underlined_ and /italic/. This variable sets the marker
3734 characters, the face to be used by font-lock for highlighting in Org-mode
3735 Emacs buffers, and the HTML tags to be used for this.
3736 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3737 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3738 Use customize to modify this, or restart Emacs after changing it."
3739 :group 'org-appearance
3740 :set 'org-set-emph-re
3741 :type '(repeat
3742 (list
3743 (string :tag "Marker character")
3744 (choice
3745 (face :tag "Font-lock-face")
3746 (plist :tag "Face property list"))
3747 (string :tag "HTML start tag")
3748 (string :tag "HTML end tag")
3749 (option (const verbatim)))))
3751 (defvar org-protecting-blocks
3752 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3753 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3754 This is needed for font-lock setup.")
3756 ;;; Miscellaneous options
3758 (defgroup org-completion nil
3759 "Completion in Org-mode."
3760 :tag "Org Completion"
3761 :group 'org)
3763 (defcustom org-completion-use-ido nil
3764 "Non-nil means use ido completion wherever possible.
3765 Note that `ido-mode' must be active for this variable to be relevant.
3766 If you decide to turn this variable on, you might well want to turn off
3767 `org-outline-path-complete-in-steps'.
3768 See also `org-completion-use-iswitchb'."
3769 :group 'org-completion
3770 :type 'boolean)
3772 (defcustom org-completion-use-iswitchb nil
3773 "Non-nil means use iswitchb completion wherever possible.
3774 Note that `iswitchb-mode' must be active for this variable to be relevant.
3775 If you decide to turn this variable on, you might well want to turn off
3776 `org-outline-path-complete-in-steps'.
3777 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3778 :group 'org-completion
3779 :type 'boolean)
3781 (defcustom org-completion-fallback-command 'hippie-expand
3782 "The expansion command called by \\[pcomplete] in normal context.
3783 Normal means, no org-mode-specific context."
3784 :group 'org-completion
3785 :type 'function)
3787 ;;; Functions and variables from their packages
3788 ;; Declared here to avoid compiler warnings
3790 ;; XEmacs only
3791 (defvar outline-mode-menu-heading)
3792 (defvar outline-mode-menu-show)
3793 (defvar outline-mode-menu-hide)
3794 (defvar zmacs-regions) ; XEmacs regions
3796 ;; Emacs only
3797 (defvar mark-active)
3799 ;; Various packages
3800 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3801 (declare-function calendar-forward-day "cal-move" (arg))
3802 (declare-function calendar-goto-date "cal-move" (date))
3803 (declare-function calendar-goto-today "cal-move" ())
3804 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3805 (defvar calc-embedded-close-formula)
3806 (defvar calc-embedded-open-formula)
3807 (declare-function cdlatex-tab "ext:cdlatex" ())
3808 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3809 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3810 (defvar font-lock-unfontify-region-function)
3811 (declare-function iswitchb-read-buffer "iswitchb"
3812 (prompt &optional default require-match start matches-set))
3813 (defvar iswitchb-temp-buflist)
3814 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3815 (defvar org-agenda-tags-todo-honor-ignore-options)
3816 (declare-function org-agenda-skip "org-agenda" ())
3817 (declare-function
3818 org-agenda-format-item "org-agenda"
3819 (extra txt &optional category tags dotime noprefix remove-re habitp))
3820 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3821 (declare-function org-agenda-change-all-lines "org-agenda"
3822 (newhead hdmarker &optional fixface just-this))
3823 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3824 (declare-function org-agenda-maybe-redo "org-agenda" ())
3825 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3826 (beg end))
3827 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3828 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3829 "org-agenda" (&optional end))
3830 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3831 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3832 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3833 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3834 (declare-function org-indent-mode "org-indent" (&optional arg))
3835 (declare-function parse-time-string "parse-time" (string))
3836 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3837 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3838 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3839 (defvar remember-data-file)
3840 (defvar texmathp-why)
3841 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3842 (declare-function table--at-cell-p "table" (position &optional object at-column))
3844 (defvar w3m-current-url)
3845 (defvar w3m-current-title)
3847 (defvar org-latex-regexps)
3849 ;;; Autoload and prepare some org modules
3851 ;; Some table stuff that needs to be defined here, because it is used
3852 ;; by the functions setting up org-mode or checking for table context.
3854 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3855 "Detect an org-type or table-type table.")
3856 (defconst org-table-line-regexp "^[ \t]*|"
3857 "Detect an org-type table line.")
3858 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3859 "Detect an org-type table line.")
3860 (defconst org-table-hline-regexp "^[ \t]*|-"
3861 "Detect an org-type table hline.")
3862 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3863 "Detect a table-type table hline.")
3864 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3865 "Detect the first line outside a table when searching from within it.
3866 This works for both table types.")
3868 ;; Autoload the functions in org-table.el that are needed by functions here.
3870 (eval-and-compile
3871 (org-autoload "org-table"
3872 '(org-table-align org-table-begin org-table-blank-field
3873 org-table-convert org-table-convert-region org-table-copy-down
3874 org-table-copy-region org-table-create
3875 org-table-create-or-convert-from-region
3876 org-table-create-with-table.el org-table-current-dline
3877 org-table-cut-region org-table-delete-column org-table-edit-field
3878 org-table-edit-formulas org-table-end org-table-eval-formula
3879 org-table-export org-table-field-info
3880 org-table-get-stored-formulas org-table-goto-column
3881 org-table-hline-and-move org-table-import org-table-insert-column
3882 org-table-insert-hline org-table-insert-row org-table-iterate
3883 org-table-justify-field-maybe org-table-kill-row
3884 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3885 org-table-move-column org-table-move-column-left
3886 org-table-move-column-right org-table-move-row
3887 org-table-move-row-down org-table-move-row-up
3888 org-table-next-field org-table-next-row org-table-paste-rectangle
3889 org-table-previous-field org-table-recalculate
3890 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3891 org-table-toggle-coordinate-overlays
3892 org-table-toggle-formula-debugger org-table-wrap-region
3893 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3894 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3895 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3897 (defun org-at-table-p (&optional table-type)
3898 "Return t if the cursor is inside an org-type table.
3899 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3900 (if org-enable-table-editor
3901 (save-excursion
3902 (beginning-of-line 1)
3903 (looking-at (if table-type org-table-any-line-regexp
3904 org-table-line-regexp)))
3905 nil))
3906 (defsubst org-table-p () (org-at-table-p))
3908 (defun org-at-table.el-p ()
3909 "Return t if and only if we are at a table.el table."
3910 (and (org-at-table-p 'any)
3911 (save-excursion
3912 (goto-char (org-table-begin 'any))
3913 (looking-at org-table1-hline-regexp))))
3914 (defun org-table-recognize-table.el ()
3915 "If there is a table.el table nearby, recognize it and move into it."
3916 (if org-table-tab-recognizes-table.el
3917 (if (org-at-table.el-p)
3918 (progn
3919 (beginning-of-line 1)
3920 (if (looking-at org-table-dataline-regexp)
3922 (if (looking-at org-table1-hline-regexp)
3923 (progn
3924 (beginning-of-line 2)
3925 (if (looking-at org-table-any-border-regexp)
3926 (beginning-of-line -1)))))
3927 (if (re-search-forward "|" (org-table-end t) t)
3928 (progn
3929 (require 'table)
3930 (if (table--at-cell-p (point))
3932 (message "recognizing table.el table...")
3933 (table-recognize-table)
3934 (message "recognizing table.el table...done")))
3935 (error "This should not happen"))
3937 nil)
3938 nil))
3940 (defun org-at-table-hline-p ()
3941 "Return t if the cursor is inside a hline in a table."
3942 (if org-enable-table-editor
3943 (save-excursion
3944 (beginning-of-line 1)
3945 (looking-at org-table-hline-regexp))
3946 nil))
3948 (defvar org-table-clean-did-remove-column nil)
3950 (defun org-table-map-tables (function &optional quietly)
3951 "Apply FUNCTION to the start of all tables in the buffer."
3952 (save-excursion
3953 (save-restriction
3954 (widen)
3955 (goto-char (point-min))
3956 (while (re-search-forward org-table-any-line-regexp nil t)
3957 (unless quietly
3958 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3959 (beginning-of-line 1)
3960 (when (and (looking-at org-table-line-regexp)
3961 ;; Exclude tables in src/example/verbatim/clocktable blocks
3962 (not (org-in-block-p '("src" "example"))))
3963 (save-excursion (funcall function))
3964 (or (looking-at org-table-line-regexp)
3965 (forward-char 1)))
3966 (re-search-forward org-table-any-border-regexp nil 1))))
3967 (unless quietly (message "Mapping tables: done")))
3969 ;; Declare and autoload functions from org-exp.el & Co
3971 (declare-function org-default-export-plist "org-exp")
3972 (declare-function org-infile-export-plist "org-exp")
3973 (declare-function org-get-current-options "org-exp")
3974 (eval-and-compile
3975 (org-autoload "org-exp"
3976 '(org-export org-export-visible
3977 org-insert-export-options-template
3978 org-table-clean-before-export))
3979 (org-autoload "org-ascii"
3980 '(org-export-as-ascii org-export-ascii-preprocess
3981 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3982 org-export-region-as-ascii))
3983 (org-autoload "org-latex"
3984 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3985 org-replace-region-by-latex org-export-region-as-latex
3986 org-export-as-latex org-export-as-pdf
3987 org-export-as-pdf-and-open))
3988 (org-autoload "org-html"
3989 '(org-export-as-html-and-open
3990 org-export-as-html-batch org-export-as-html-to-buffer
3991 org-replace-region-by-html org-export-region-as-html
3992 org-export-as-html))
3993 (org-autoload "org-docbook"
3994 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3995 org-replace-region-by-docbook org-export-region-as-docbook
3996 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3997 org-export-as-docbook))
3998 (org-autoload "org-icalendar"
3999 '(org-export-icalendar-this-file
4000 org-export-icalendar-all-agenda-files
4001 org-export-icalendar-combine-agenda-files))
4002 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4003 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4005 ;; Declare and autoload functions from org-agenda.el
4007 (eval-and-compile
4008 (org-autoload "org-agenda"
4009 '(org-agenda org-agenda-list org-search-view
4010 org-todo-list org-tags-view org-agenda-list-stuck-projects
4011 org-diary org-agenda-to-appt
4012 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4014 ;; Autoload org-remember
4016 (eval-and-compile
4017 (org-autoload "org-remember"
4018 '(org-remember-insinuate org-remember-annotation
4019 org-remember-apply-template org-remember org-remember-handler)))
4021 (eval-and-compile
4022 (org-autoload "org-capture"
4023 '(org-capture org-capture-insert-template-here
4024 org-capture-import-remember-templates)))
4026 ;; Autoload org-clock.el
4028 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4029 (beg end))
4030 (declare-function org-clock-update-mode-line "org-clock" ())
4031 (declare-function org-resolve-clocks "org-clock"
4032 (&optional also-non-dangling-p prompt last-valid))
4033 (defvar org-clock-start-time)
4034 (defvar org-clock-marker (make-marker)
4035 "Marker recording the last clock-in.")
4036 (defvar org-clock-hd-marker (make-marker)
4037 "Marker recording the last clock-in, but the headline position.")
4038 (defvar org-clock-heading ""
4039 "The heading of the current clock entry.")
4040 (defun org-clock-is-active ()
4041 "Return non-nil if clock is currently running.
4042 The return value is actually the clock marker."
4043 (marker-buffer org-clock-marker))
4045 (eval-and-compile
4046 (org-autoload
4047 "org-clock"
4048 '(org-clock-in org-clock-out org-clock-cancel
4049 org-clock-goto org-clock-sum org-clock-display
4050 org-clock-remove-overlays org-clock-report
4051 org-clocktable-shift org-dblock-write:clocktable
4052 org-get-clocktable org-resolve-clocks)))
4054 (defun org-clock-update-time-maybe ()
4055 "If this is a CLOCK line, update it and return t.
4056 Otherwise, return nil."
4057 (interactive)
4058 (save-excursion
4059 (beginning-of-line 1)
4060 (skip-chars-forward " \t")
4061 (when (looking-at org-clock-string)
4062 (let ((re (concat "[ \t]*" org-clock-string
4063 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4064 "\\([ \t]*=>.*\\)?\\)?"))
4065 ts te h m s neg)
4066 (cond
4067 ((not (looking-at re))
4068 nil)
4069 ((not (match-end 2))
4070 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4071 (> org-clock-marker (point))
4072 (<= org-clock-marker (point-at-eol)))
4073 ;; The clock is running here
4074 (setq org-clock-start-time
4075 (apply 'encode-time
4076 (org-parse-time-string (match-string 1))))
4077 (org-clock-update-mode-line)))
4079 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4080 (end-of-line 1)
4081 (setq ts (match-string 1)
4082 te (match-string 3))
4083 (setq s (- (org-float-time
4084 (apply 'encode-time (org-parse-time-string te)))
4085 (org-float-time
4086 (apply 'encode-time (org-parse-time-string ts))))
4087 neg (< s 0)
4088 s (abs s)
4089 h (floor (/ s 3600))
4090 s (- s (* 3600 h))
4091 m (floor (/ s 60))
4092 s (- s (* 60 s)))
4093 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4094 t))))))
4096 (defun org-check-running-clock ()
4097 "Check if the current buffer contains the running clock.
4098 If yes, offer to stop it and to save the buffer with the changes."
4099 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4100 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4101 (buffer-name))))
4102 (org-clock-out)
4103 (when (y-or-n-p "Save changed buffer?")
4104 (save-buffer))))
4106 (defun org-clocktable-try-shift (dir n)
4107 "Check if this line starts a clock table, if yes, shift the time block."
4108 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4109 (org-clocktable-shift dir n)))
4111 ;; Autoload org-timer.el
4113 (eval-and-compile
4114 (org-autoload
4115 "org-timer"
4116 '(org-timer-start org-timer org-timer-item
4117 org-timer-change-times-in-region
4118 org-timer-set-timer
4119 org-timer-reset-timers
4120 org-timer-show-remaining-time)))
4122 ;; Autoload org-feed.el
4124 (eval-and-compile
4125 (org-autoload
4126 "org-feed"
4127 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4130 ;; Autoload org-indent.el
4132 ;; Define the variable already here, to make sure we have it.
4133 (defvar org-indent-mode nil
4134 "Non-nil if Org-Indent mode is enabled.
4135 Use the command `org-indent-mode' to change this variable.")
4137 (eval-and-compile
4138 (org-autoload
4139 "org-indent"
4140 '(org-indent-mode)))
4142 ;; Autoload org-mobile.el
4144 (eval-and-compile
4145 (org-autoload
4146 "org-mobile"
4147 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4149 ;; Autoload archiving code
4150 ;; The stuff that is needed for cycling and tags has to be defined here.
4152 (defgroup org-archive nil
4153 "Options concerning archiving in Org-mode."
4154 :tag "Org Archive"
4155 :group 'org-structure)
4157 (defcustom org-archive-location "%s_archive::"
4158 "The location where subtrees should be archived.
4160 The value of this variable is a string, consisting of two parts,
4161 separated by a double-colon. The first part is a filename and
4162 the second part is a headline.
4164 When the filename is omitted, archiving happens in the same file.
4165 %s in the filename will be replaced by the current file
4166 name (without the directory part). Archiving to a different file
4167 is useful to keep archived entries from contributing to the
4168 Org-mode Agenda.
4170 The archived entries will be filed as subtrees of the specified
4171 headline. When the headline is omitted, the subtrees are simply
4172 filed away at the end of the file, as top-level entries. Also in
4173 the heading you can use %s to represent the file name, this can be
4174 useful when using the same archive for a number of different files.
4176 Here are a few examples:
4177 \"%s_archive::\"
4178 If the current file is Projects.org, archive in file
4179 Projects.org_archive, as top-level trees. This is the default.
4181 \"::* Archived Tasks\"
4182 Archive in the current file, under the top-level headline
4183 \"* Archived Tasks\".
4185 \"~/org/archive.org::\"
4186 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4188 \"~/org/archive.org::* From %s\"
4189 Archive in file ~/org/archive.org (absolute path), under headlines
4190 \"From FILENAME\" where file name is the current file name.
4192 \"~/org/datetree.org::datetree/* Finished Tasks\"
4193 The \"datetree/\" string is special, signifying to archive
4194 items to the datetree. Items are placed in either the CLOSED
4195 date of the item, or the current date if there is no CLOSED date.
4196 The heading will be a subentry to the current date. There doesn't
4197 need to be a heading, but there always needs to be a slash after
4198 datetree. For example, to store archived items directly in the
4199 datetree, use \"~/org/datetree.org::datetree/\".
4201 \"basement::** Finished Tasks\"
4202 Archive in file ./basement (relative path), as level 3 trees
4203 below the level 2 heading \"** Finished Tasks\".
4205 You may set this option on a per-file basis by adding to the buffer a
4206 line like
4208 #+ARCHIVE: basement::** Finished Tasks
4210 You may also define it locally for a subtree by setting an ARCHIVE property
4211 in the entry. If such a property is found in an entry, or anywhere up
4212 the hierarchy, it will be used."
4213 :group 'org-archive
4214 :type 'string)
4216 (defcustom org-archive-tag "ARCHIVE"
4217 "The tag that marks a subtree as archived.
4218 An archived subtree does not open during visibility cycling, and does
4219 not contribute to the agenda listings.
4220 After changing this, font-lock must be restarted in the relevant buffers to
4221 get the proper fontification."
4222 :group 'org-archive
4223 :group 'org-keywords
4224 :type 'string)
4226 (defcustom org-agenda-skip-archived-trees t
4227 "Non-nil means the agenda will skip any items located in archived trees.
4228 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4229 variable is no longer recommended, you should leave it at the value t.
4230 Instead, use the key `v' to cycle the archives-mode in the agenda."
4231 :group 'org-archive
4232 :group 'org-agenda-skip
4233 :type 'boolean)
4235 (defcustom org-columns-skip-archived-trees t
4236 "Non-nil means ignore archived trees when creating column view."
4237 :group 'org-archive
4238 :group 'org-properties
4239 :type 'boolean)
4241 (defcustom org-cycle-open-archived-trees nil
4242 "Non-nil means `org-cycle' will open archived trees.
4243 An archived tree is a tree marked with the tag ARCHIVE.
4244 When nil, archived trees will stay folded. You can still open them with
4245 normal outline commands like `show-all', but not with the cycling commands."
4246 :group 'org-archive
4247 :group 'org-cycle
4248 :type 'boolean)
4250 (defcustom org-sparse-tree-open-archived-trees nil
4251 "Non-nil means sparse tree construction shows matches in archived trees.
4252 When nil, matches in these trees are highlighted, but the trees are kept in
4253 collapsed state."
4254 :group 'org-archive
4255 :group 'org-sparse-trees
4256 :type 'boolean)
4258 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4259 "The default date type when building a sparse tree.
4260 When this is nil, a date is a scheduled or a deadline timestamp.
4261 Otherwise, these types are allowed:
4263 all: all timestamps
4264 active: only active timestamps (<...>)
4265 inactive: only inactive timestamps (<...)
4266 scheduled: only scheduled timestamps
4267 deadline: only deadline timestamps"
4268 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4269 (const :tag "All timestamps" all)
4270 (const :tag "Only active timestamps" active)
4271 (const :tag "Only inactive timestamps" inactive)
4272 (const :tag "Only scheduled timestamps" scheduled)
4273 (const :tag "Only deadline timestamps" deadline))
4274 ;; :version "24.3"
4275 :group 'org-sparse-trees)
4277 (defun org-cycle-hide-archived-subtrees (state)
4278 "Re-hide all archived subtrees after a visibility state change."
4279 (when (and (not org-cycle-open-archived-trees)
4280 (not (memq state '(overview folded))))
4281 (save-excursion
4282 (let* ((globalp (memq state '(contents all)))
4283 (beg (if globalp (point-min) (point)))
4284 (end (if globalp (point-max) (org-end-of-subtree t))))
4285 (org-hide-archived-subtrees beg end)
4286 (goto-char beg)
4287 (if (looking-at (concat ".*:" org-archive-tag ":"))
4288 (message "%s" (substitute-command-keys
4289 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4291 (defun org-force-cycle-archived ()
4292 "Cycle subtree even if it is archived."
4293 (interactive)
4294 (setq this-command 'org-cycle)
4295 (let ((org-cycle-open-archived-trees t))
4296 (call-interactively 'org-cycle)))
4298 (defun org-hide-archived-subtrees (beg end)
4299 "Re-hide all archived subtrees after a visibility state change."
4300 (save-excursion
4301 (let* ((re (concat ":" org-archive-tag ":")))
4302 (goto-char beg)
4303 (while (re-search-forward re end t)
4304 (when (org-at-heading-p)
4305 (org-flag-subtree t)
4306 (org-end-of-subtree t))))))
4308 (declare-function outline-end-of-heading "outline" ())
4309 (declare-function outline-flag-region "outline" (from to flag))
4310 (defun org-flag-subtree (flag)
4311 (save-excursion
4312 (org-back-to-heading t)
4313 (outline-end-of-heading)
4314 (outline-flag-region (point)
4315 (progn (org-end-of-subtree t) (point))
4316 flag)))
4318 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4320 (eval-and-compile
4321 (org-autoload "org-archive"
4322 '(org-add-archive-files org-archive-subtree
4323 org-archive-to-archive-sibling org-toggle-archive-tag
4324 org-archive-subtree-default
4325 org-archive-subtree-default-with-confirmation)))
4327 ;; Autoload Column View Code
4329 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4330 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4331 (declare-function org-columns-compute "org-colview" (property))
4333 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4334 '(org-columns-number-to-string org-columns-get-format-and-top-level
4335 org-columns-compute org-agenda-columns org-columns-remove-overlays
4336 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4338 ;; Autoload ID code
4340 (declare-function org-id-store-link "org-id")
4341 (declare-function org-id-locations-load "org-id")
4342 (declare-function org-id-locations-save "org-id")
4343 (defvar org-id-track-globally)
4344 (org-autoload "org-id"
4345 '(org-id-get-create org-id-new org-id-copy org-id-get
4346 org-id-get-with-outline-path-completion
4347 org-id-get-with-outline-drilling org-id-store-link
4348 org-id-goto org-id-find org-id-store-link))
4350 ;; Autoload Plotting Code
4352 (org-autoload "org-plot"
4353 '(org-plot/gnuplot))
4355 ;;; Variables for pre-computed regular expressions, all buffer local
4357 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4358 "Matches first line of a hidden block.")
4359 (make-variable-buffer-local 'org-drawer-regexp)
4360 (defvar org-todo-regexp nil
4361 "Matches any of the TODO state keywords.")
4362 (make-variable-buffer-local 'org-todo-regexp)
4363 (defvar org-not-done-regexp nil
4364 "Matches any of the TODO state keywords except the last one.")
4365 (make-variable-buffer-local 'org-not-done-regexp)
4366 (defvar org-not-done-heading-regexp nil
4367 "Matches a TODO headline that is not done.")
4368 (make-variable-buffer-local 'org-not-done-regexp)
4369 (defvar org-todo-line-regexp nil
4370 "Matches a headline and puts TODO state into group 2 if present.")
4371 (make-variable-buffer-local 'org-todo-line-regexp)
4372 (defvar org-complex-heading-regexp nil
4373 "Matches a headline and puts everything into groups:
4374 group 1: the stars
4375 group 2: The todo keyword, maybe
4376 group 3: Priority cookie
4377 group 4: True headline
4378 group 5: Tags")
4379 (make-variable-buffer-local 'org-complex-heading-regexp)
4380 (defvar org-complex-heading-regexp-format nil
4381 "Printf format to make regexp to match an exact headline.
4382 This regexp will match the headline of any node which has the
4383 exact headline text that is put into the format, but may have any
4384 TODO state, priority and tags.")
4385 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4386 (defvar org-todo-line-tags-regexp nil
4387 "Matches a headline and puts TODO state into group 2 if present.
4388 Also put tags into group 4 if tags are present.")
4389 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4390 (defvar org-ds-keyword-length 12
4391 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4392 (make-variable-buffer-local 'org-ds-keyword-length)
4393 (defvar org-deadline-regexp nil
4394 "Matches the DEADLINE keyword.")
4395 (make-variable-buffer-local 'org-deadline-regexp)
4396 (defvar org-deadline-time-regexp nil
4397 "Matches the DEADLINE keyword together with a time stamp.")
4398 (make-variable-buffer-local 'org-deadline-time-regexp)
4399 (defvar org-deadline-line-regexp nil
4400 "Matches the DEADLINE keyword and the rest of the line.")
4401 (make-variable-buffer-local 'org-deadline-line-regexp)
4402 (defvar org-scheduled-regexp nil
4403 "Matches the SCHEDULED keyword.")
4404 (make-variable-buffer-local 'org-scheduled-regexp)
4405 (defvar org-scheduled-time-regexp nil
4406 "Matches the SCHEDULED keyword together with a time stamp.")
4407 (make-variable-buffer-local 'org-scheduled-time-regexp)
4408 (defvar org-closed-time-regexp nil
4409 "Matches the CLOSED keyword together with a time stamp.")
4410 (make-variable-buffer-local 'org-closed-time-regexp)
4412 (defvar org-keyword-time-regexp nil
4413 "Matches any of the 4 keywords, together with the time stamp.")
4414 (make-variable-buffer-local 'org-keyword-time-regexp)
4415 (defvar org-keyword-time-not-clock-regexp nil
4416 "Matches any of the 3 keywords, together with the time stamp.")
4417 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4418 (defvar org-maybe-keyword-time-regexp nil
4419 "Matches a timestamp, possibly preceded by a keyword.")
4420 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4421 (defvar org-all-time-keywords nil
4422 "List of time keywords.")
4423 (make-variable-buffer-local 'org-all-time-keywords)
4425 (defconst org-plain-time-of-day-regexp
4426 (concat
4427 "\\(\\<[012]?[0-9]"
4428 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4429 "\\(--?"
4430 "\\(\\<[012]?[0-9]"
4431 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4432 "\\)?")
4433 "Regular expression to match a plain time or time range.
4434 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4435 groups carry important information:
4436 0 the full match
4437 1 the first time, range or not
4438 8 the second time, if it is a range.")
4440 (defconst org-plain-time-extension-regexp
4441 (concat
4442 "\\(\\<[012]?[0-9]"
4443 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4444 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4445 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4446 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4447 groups carry important information:
4448 0 the full match
4449 7 hours of duration
4450 9 minutes of duration")
4452 (defconst org-stamp-time-of-day-regexp
4453 (concat
4454 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4455 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4456 "\\(--?"
4457 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4458 "Regular expression to match a timestamp time or time range.
4459 After a match, the following groups carry important information:
4460 0 the full match
4461 1 date plus weekday, for back referencing to make sure both times are on the same day
4462 2 the first time, range or not
4463 4 the second time, if it is a range.")
4465 (defconst org-startup-options
4466 '(("fold" org-startup-folded t)
4467 ("overview" org-startup-folded t)
4468 ("nofold" org-startup-folded nil)
4469 ("showall" org-startup-folded nil)
4470 ("showeverything" org-startup-folded showeverything)
4471 ("content" org-startup-folded content)
4472 ("indent" org-startup-indented t)
4473 ("noindent" org-startup-indented nil)
4474 ("hidestars" org-hide-leading-stars t)
4475 ("showstars" org-hide-leading-stars nil)
4476 ("odd" org-odd-levels-only t)
4477 ("oddeven" org-odd-levels-only nil)
4478 ("align" org-startup-align-all-tables t)
4479 ("noalign" org-startup-align-all-tables nil)
4480 ("inlineimages" org-startup-with-inline-images t)
4481 ("noinlineimages" org-startup-with-inline-images nil)
4482 ("customtime" org-display-custom-times t)
4483 ("logdone" org-log-done time)
4484 ("lognotedone" org-log-done note)
4485 ("nologdone" org-log-done nil)
4486 ("lognoteclock-out" org-log-note-clock-out t)
4487 ("nolognoteclock-out" org-log-note-clock-out nil)
4488 ("logrepeat" org-log-repeat state)
4489 ("lognoterepeat" org-log-repeat note)
4490 ("nologrepeat" org-log-repeat nil)
4491 ("logreschedule" org-log-reschedule time)
4492 ("lognotereschedule" org-log-reschedule note)
4493 ("nologreschedule" org-log-reschedule nil)
4494 ("logredeadline" org-log-redeadline time)
4495 ("lognoteredeadline" org-log-redeadline note)
4496 ("nologredeadline" org-log-redeadline nil)
4497 ("logrefile" org-log-refile time)
4498 ("lognoterefile" org-log-refile note)
4499 ("nologrefile" org-log-refile nil)
4500 ("fninline" org-footnote-define-inline t)
4501 ("nofninline" org-footnote-define-inline nil)
4502 ("fnlocal" org-footnote-section nil)
4503 ("fnauto" org-footnote-auto-label t)
4504 ("fnprompt" org-footnote-auto-label nil)
4505 ("fnconfirm" org-footnote-auto-label confirm)
4506 ("fnplain" org-footnote-auto-label plain)
4507 ("fnadjust" org-footnote-auto-adjust t)
4508 ("nofnadjust" org-footnote-auto-adjust nil)
4509 ("constcgs" constants-unit-system cgs)
4510 ("constSI" constants-unit-system SI)
4511 ("noptag" org-tag-persistent-alist nil)
4512 ("hideblocks" org-hide-block-startup t)
4513 ("nohideblocks" org-hide-block-startup nil)
4514 ("beamer" org-startup-with-beamer-mode t)
4515 ("entitiespretty" org-pretty-entities t)
4516 ("entitiesplain" org-pretty-entities nil))
4517 "Variable associated with STARTUP options for org-mode.
4518 Each element is a list of three items: the startup options (as written
4519 in the #+STARTUP line), the corresponding variable, and the value to set
4520 this variable to if the option is found. An optional forth element PUSH
4521 means to push this value onto the list in the variable.")
4523 (defun org-update-property-plist (key val props)
4524 "Update PROPS with KEY and VAL."
4525 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4526 (key (if appending (substring key 0 (- (length key) 1)) key))
4527 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4528 (previous (cdr (assoc key props))))
4529 (if appending
4530 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4531 (cons (cons key val) remainder))))
4533 (defconst org-block-regexp
4534 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4535 "Regular expression for hiding blocks.")
4536 (defconst org-heading-keyword-regexp-format
4537 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4538 "Printf format for a regexp matching an headline with some keyword.
4539 This regexp will match the headline of any node which has the
4540 exact keyword that is put into the format. The keyword isn't in
4541 any group by default, but the stars and the body are.")
4542 (defconst org-heading-keyword-maybe-regexp-format
4543 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4544 "Printf format for a regexp matching an headline, possibly with some keyword.
4545 This regexp can match any headline with the specified keyword, or
4546 without a keyword. The keyword isn't in any group by default,
4547 but the stars and the body are.")
4549 (defun org-set-regexps-and-options ()
4550 "Precompute regular expressions for current buffer."
4551 (when (derived-mode-p 'org-mode)
4552 (org-set-local 'org-todo-kwd-alist nil)
4553 (org-set-local 'org-todo-key-alist nil)
4554 (org-set-local 'org-todo-key-trigger nil)
4555 (org-set-local 'org-todo-keywords-1 nil)
4556 (org-set-local 'org-done-keywords nil)
4557 (org-set-local 'org-todo-heads nil)
4558 (org-set-local 'org-todo-sets nil)
4559 (org-set-local 'org-todo-log-states nil)
4560 (org-set-local 'org-file-properties nil)
4561 (org-set-local 'org-file-tags nil)
4562 (let ((re (org-make-options-regexp
4563 '("CATEGORY" "TODO" "COLUMNS"
4564 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4565 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4566 "OPTIONS")
4567 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4568 (splitre "[ \t]+")
4569 (scripts org-use-sub-superscripts)
4570 kwds kws0 kwsa key log value cat arch tags const links hw dws
4571 tail sep kws1 prio props ftags drawers beamer-p
4572 ext-setup-or-nil setup-contents (start 0))
4573 (save-excursion
4574 (save-restriction
4575 (widen)
4576 (goto-char (point-min))
4577 (while (or (and ext-setup-or-nil
4578 (string-match re ext-setup-or-nil start)
4579 (setq start (match-end 0)))
4580 (and (setq ext-setup-or-nil nil start 0)
4581 (re-search-forward re nil t)))
4582 (setq key (upcase (match-string 1 ext-setup-or-nil))
4583 value (org-match-string-no-properties 2 ext-setup-or-nil))
4584 (if (stringp value) (setq value (org-trim value)))
4585 (cond
4586 ((equal key "CATEGORY")
4587 (setq cat value))
4588 ((member key '("SEQ_TODO" "TODO"))
4589 (push (cons 'sequence (org-split-string value splitre)) kwds))
4590 ((equal key "TYP_TODO")
4591 (push (cons 'type (org-split-string value splitre)) kwds))
4592 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4593 ;; general TODO-like setup
4594 (push (cons (intern (downcase (match-string 1 key)))
4595 (org-split-string value splitre)) kwds))
4596 ((equal key "TAGS")
4597 (setq tags (append tags (if tags '("\\n") nil)
4598 (org-split-string value splitre))))
4599 ((equal key "COLUMNS")
4600 (org-set-local 'org-columns-default-format value))
4601 ((equal key "LINK")
4602 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4603 (push (cons (match-string 1 value)
4604 (org-trim (match-string 2 value)))
4605 links)))
4606 ((equal key "PRIORITIES")
4607 (setq prio (org-split-string value " +")))
4608 ((equal key "PROPERTY")
4609 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4610 (setq props (org-update-property-plist (match-string 1 value)
4611 (match-string 2 value)
4612 props))))
4613 ((equal key "FILETAGS")
4614 (when (string-match "\\S-" value)
4615 (setq ftags
4616 (append
4617 ftags
4618 (apply 'append
4619 (mapcar (lambda (x) (org-split-string x ":"))
4620 (org-split-string value)))))))
4621 ((equal key "DRAWERS")
4622 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4623 ((equal key "CONSTANTS")
4624 (setq const (append const (org-split-string value splitre))))
4625 ((equal key "STARTUP")
4626 (let ((opts (org-split-string value splitre))
4627 l var val)
4628 (while (setq l (pop opts))
4629 (when (setq l (assoc l org-startup-options))
4630 (setq var (nth 1 l) val (nth 2 l))
4631 (if (not (nth 3 l))
4632 (set (make-local-variable var) val)
4633 (if (not (listp (symbol-value var)))
4634 (set (make-local-variable var) nil))
4635 (set (make-local-variable var) (symbol-value var))
4636 (add-to-list var val))))))
4637 ((equal key "ARCHIVE")
4638 (setq arch value)
4639 (remove-text-properties 0 (length arch)
4640 '(face t fontified t) arch))
4641 ((equal key "LATEX_CLASS")
4642 (setq beamer-p (equal value "beamer")))
4643 ((equal key "OPTIONS")
4644 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4645 (setq scripts (read (match-string 2 value)))))
4646 ((equal key "SETUPFILE")
4647 (setq setup-contents (org-file-contents
4648 (expand-file-name
4649 (org-remove-double-quotes value))
4650 'noerror))
4651 (if (not ext-setup-or-nil)
4652 (setq ext-setup-or-nil setup-contents start 0)
4653 (setq ext-setup-or-nil
4654 (concat (substring ext-setup-or-nil 0 start)
4655 "\n" setup-contents "\n"
4656 (substring ext-setup-or-nil start)))))))
4657 ;; search for property blocks
4658 (goto-char (point-min))
4659 (while (re-search-forward org-block-regexp nil t)
4660 (when (equal "PROPERTY" (upcase (match-string 1)))
4661 (setq value (replace-regexp-in-string
4662 "[\n\r]" " " (match-string 4)))
4663 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4664 (setq props (org-update-property-plist (match-string 1 value)
4665 (match-string 2 value)
4666 props)))))))
4667 (org-set-local 'org-use-sub-superscripts scripts)
4668 (when cat
4669 (org-set-local 'org-category (intern cat))
4670 (push (cons "CATEGORY" cat) props))
4671 (when prio
4672 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4673 (setq prio (mapcar 'string-to-char prio))
4674 (org-set-local 'org-highest-priority (nth 0 prio))
4675 (org-set-local 'org-lowest-priority (nth 1 prio))
4676 (org-set-local 'org-default-priority (nth 2 prio)))
4677 (and props (org-set-local 'org-file-properties (nreverse props)))
4678 (and ftags (org-set-local 'org-file-tags
4679 (mapcar 'org-add-prop-inherited ftags)))
4680 (and drawers (org-set-local 'org-drawers drawers))
4681 (and arch (org-set-local 'org-archive-location arch))
4682 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4683 ;; Process the TODO keywords
4684 (unless kwds
4685 ;; Use the global values as if they had been given locally.
4686 (setq kwds (default-value 'org-todo-keywords))
4687 (if (stringp (car kwds))
4688 (setq kwds (list (cons org-todo-interpretation
4689 (default-value 'org-todo-keywords)))))
4690 (setq kwds (reverse kwds)))
4691 (setq kwds (nreverse kwds))
4692 (let (inter kws kw)
4693 (while (setq kws (pop kwds))
4694 (let ((kws (or
4695 (run-hook-with-args-until-success
4696 'org-todo-setup-filter-hook kws)
4697 kws)))
4698 (setq inter (pop kws) sep (member "|" kws)
4699 kws0 (delete "|" (copy-sequence kws))
4700 kwsa nil
4701 kws1 (mapcar
4702 (lambda (x)
4703 ;; 1 2
4704 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4705 (progn
4706 (setq kw (match-string 1 x)
4707 key (and (match-end 2) (match-string 2 x))
4708 log (org-extract-log-state-settings x))
4709 (push (cons kw (and key (string-to-char key))) kwsa)
4710 (and log (push log org-todo-log-states))
4712 (error "Invalid TODO keyword %s" x)))
4713 kws0)
4714 kwsa (if kwsa (append '((:startgroup))
4715 (nreverse kwsa)
4716 '((:endgroup))))
4717 hw (car kws1)
4718 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4719 tail (list inter hw (car dws) (org-last dws))))
4720 (add-to-list 'org-todo-heads hw 'append)
4721 (push kws1 org-todo-sets)
4722 (setq org-done-keywords (append org-done-keywords dws nil))
4723 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4724 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4725 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4726 (setq org-todo-sets (nreverse org-todo-sets)
4727 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4728 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4729 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4730 ;; Process the constants
4731 (when const
4732 (let (e cst)
4733 (while (setq e (pop const))
4734 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4735 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4736 (setq org-table-formula-constants-local cst)))
4738 ;; Process the tags.
4739 (when tags
4740 (let (e tgs)
4741 (while (setq e (pop tags))
4742 (cond
4743 ((equal e "{") (push '(:startgroup) tgs))
4744 ((equal e "}") (push '(:endgroup) tgs))
4745 ((equal e "\\n") (push '(:newline) tgs))
4746 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4747 (push (cons (match-string 1 e)
4748 (string-to-char (match-string 2 e)))
4749 tgs))
4750 (t (push (list e) tgs))))
4751 (org-set-local 'org-tag-alist nil)
4752 (while (setq e (pop tgs))
4753 (or (and (stringp (car e))
4754 (assoc (car e) org-tag-alist))
4755 (push e org-tag-alist)))))
4757 ;; Compute the regular expressions and other local variables.
4758 ;; Using `org-outline-regexp-bol' would complicate them much,
4759 ;; because of the fixed white space at the end of that string.
4760 (if (not org-done-keywords)
4761 (setq org-done-keywords (and org-todo-keywords-1
4762 (list (org-last org-todo-keywords-1)))))
4763 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4764 (length org-scheduled-string)
4765 (length org-clock-string)
4766 (length org-closed-string)))
4767 org-drawer-regexp
4768 (concat "^[ \t]*:\\("
4769 (mapconcat 'regexp-quote org-drawers "\\|")
4770 "\\):[ \t]*$")
4771 org-not-done-keywords
4772 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4773 org-todo-regexp
4774 (concat "\\("
4775 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4776 "\\)")
4777 org-not-done-regexp
4778 (concat "\\("
4779 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4780 "\\)")
4781 org-not-done-heading-regexp
4782 (format org-heading-keyword-regexp-format org-not-done-regexp)
4783 org-todo-line-regexp
4784 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4785 org-complex-heading-regexp
4786 (concat "^\\(\\*+\\)"
4787 "\\(?: +" org-todo-regexp "\\)?"
4788 "\\(?: +\\(\\[#.\\]\\)\\)?"
4789 "\\(?: +\\(.*?\\)\\)??"
4790 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4791 "[ \t]*$")
4792 org-complex-heading-regexp-format
4793 (concat "^\\(\\*+\\)"
4794 "\\(?: +" org-todo-regexp "\\)?"
4795 "\\(?: +\\(\\[#.\\]\\)\\)?"
4796 "\\(?: +"
4797 ;; Stats cookies can be stuck to body.
4798 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4799 "\\(%s\\)"
4800 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4801 "\\)"
4802 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4803 "[ \t]*$")
4804 org-todo-line-tags-regexp
4805 (concat "^\\(\\*+\\)"
4806 "\\(?: +" org-todo-regexp "\\)?"
4807 "\\(?: +\\(.*?\\)\\)??"
4808 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4809 "[ \t]*$")
4810 org-deadline-regexp (concat "\\<" org-deadline-string)
4811 org-deadline-time-regexp
4812 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4813 org-deadline-line-regexp
4814 (concat "\\<\\(" org-deadline-string "\\).*")
4815 org-scheduled-regexp
4816 (concat "\\<" org-scheduled-string)
4817 org-scheduled-time-regexp
4818 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4819 org-closed-time-regexp
4820 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4821 org-keyword-time-regexp
4822 (concat "\\<\\(" org-scheduled-string
4823 "\\|" org-deadline-string
4824 "\\|" org-closed-string
4825 "\\|" org-clock-string "\\)"
4826 " *[[<]\\([^]>]+\\)[]>]")
4827 org-keyword-time-not-clock-regexp
4828 (concat "\\<\\(" org-scheduled-string
4829 "\\|" org-deadline-string
4830 "\\|" org-closed-string
4831 "\\)"
4832 " *[[<]\\([^]>]+\\)[]>]")
4833 org-maybe-keyword-time-regexp
4834 (concat "\\(\\<\\(" org-scheduled-string
4835 "\\|" org-deadline-string
4836 "\\|" org-closed-string
4837 "\\|" org-clock-string "\\)\\)?"
4838 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4839 org-all-time-keywords
4840 (mapcar (lambda (w) (substring w 0 -1))
4841 (list org-scheduled-string org-deadline-string
4842 org-clock-string org-closed-string))
4844 (org-compute-latex-and-specials-regexp)
4845 (org-set-font-lock-defaults))))
4847 (defun org-file-contents (file &optional noerror)
4848 "Return the contents of FILE, as a string."
4849 (if (or (not file)
4850 (not (file-readable-p file)))
4851 (if noerror
4852 (progn
4853 (message "Cannot read file \"%s\"" file)
4854 (ding) (sit-for 2)
4856 (error "Cannot read file \"%s\"" file))
4857 (with-temp-buffer
4858 (insert-file-contents file)
4859 (buffer-string))))
4861 (defun org-extract-log-state-settings (x)
4862 "Extract the log state setting from a TODO keyword string.
4863 This will extract info from a string like \"WAIT(w@/!)\"."
4864 (let (kw key log1 log2)
4865 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4866 (setq kw (match-string 1 x)
4867 key (and (match-end 2) (match-string 2 x))
4868 log1 (and (match-end 3) (match-string 3 x))
4869 log2 (and (match-end 4) (match-string 4 x)))
4870 (and (or log1 log2)
4871 (list kw
4872 (and log1 (if (equal log1 "!") 'time 'note))
4873 (and log2 (if (equal log2 "!") 'time 'note)))))))
4875 (defun org-remove-keyword-keys (list)
4876 "Remove a pair of parenthesis at the end of each string in LIST."
4877 (mapcar (lambda (x)
4878 (if (string-match "(.*)$" x)
4879 (substring x 0 (match-beginning 0))
4881 list))
4883 (defun org-assign-fast-keys (alist)
4884 "Assign fast keys to a keyword-key alist.
4885 Respect keys that are already there."
4886 (let (new e (alt ?0))
4887 (while (setq e (pop alist))
4888 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4889 (cdr e)) ;; Key already assigned.
4890 (push e new)
4891 (let ((clist (string-to-list (downcase (car e))))
4892 (used (append new alist)))
4893 (when (= (car clist) ?@)
4894 (pop clist))
4895 (while (and clist (rassoc (car clist) used))
4896 (pop clist))
4897 (unless clist
4898 (while (rassoc alt used)
4899 (incf alt)))
4900 (push (cons (car e) (or (car clist) alt)) new))))
4901 (nreverse new)))
4903 ;;; Some variables used in various places
4905 (defvar org-window-configuration nil
4906 "Used in various places to store a window configuration.")
4907 (defvar org-selected-window nil
4908 "Used in various places to store a window configuration.")
4909 (defvar org-finish-function nil
4910 "Function to be called when `C-c C-c' is used.
4911 This is for getting out of special buffers like capture.")
4914 ;; FIXME: Occasionally check by commenting these, to make sure
4915 ;; no other functions uses these, forgetting to let-bind them.
4916 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4917 (defvar org-last-state)
4918 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4920 ;; Defined somewhere in this file, but used before definition.
4921 (defvar org-entities) ;; defined in org-entities.el
4922 (defvar org-struct-menu)
4923 (defvar org-org-menu)
4924 (defvar org-tbl-menu)
4926 ;;;; Define the Org-mode
4928 ;; We use a before-change function to check if a table might need
4929 ;; an update.
4930 (defvar org-table-may-need-update t
4931 "Indicates that a table might need an update.
4932 This variable is set by `org-before-change-function'.
4933 `org-table-align' sets it back to nil.")
4934 (defun org-before-change-function (beg end)
4935 "Every change indicates that a table might need an update."
4936 (setq org-table-may-need-update t))
4937 (defvar org-mode-map)
4938 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4939 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4940 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4941 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4942 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4943 (defvar org-table-buffer-is-an nil)
4945 (defvar bidi-paragraph-direction)
4946 (defvar buffer-face-mode-face)
4948 (require 'outline)
4949 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4950 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4951 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4953 ;; Other stuff we need.
4954 (require 'time-date)
4955 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4956 (require 'easymenu)
4957 (require 'overlay)
4959 (require 'org-macs)
4960 (require 'org-entities)
4961 ;; (require 'org-compat) moved higher up in the file before it is first used
4962 (require 'org-faces)
4963 (require 'org-list)
4964 (require 'org-pcomplete)
4965 (require 'org-src)
4966 (require 'org-footnote)
4968 ;; babel
4969 (require 'ob)
4970 (require 'ob-table)
4971 (require 'ob-lob)
4972 (require 'ob-ref)
4973 (require 'ob-tangle)
4974 (require 'ob-comint)
4975 (require 'ob-keys)
4977 ;;;###autoload
4978 (define-derived-mode org-mode outline-mode "Org"
4979 "Outline-based notes management and organizer, alias
4980 \"Carsten's outline-mode for keeping track of everything.\"
4982 Org-mode develops organizational tasks around a NOTES file which
4983 contains information about projects as plain text. Org-mode is
4984 implemented on top of outline-mode, which is ideal to keep the content
4985 of large files well structured. It supports ToDo items, deadlines and
4986 time stamps, which magically appear in the diary listing of the Emacs
4987 calendar. Tables are easily created with a built-in table editor.
4988 Plain text URL-like links connect to websites, emails (VM), Usenet
4989 messages (Gnus), BBDB entries, and any files related to the project.
4990 For printing and sharing of notes, an Org-mode file (or a part of it)
4991 can be exported as a structured ASCII or HTML file.
4993 The following commands are available:
4995 \\{org-mode-map}"
4997 ;; Get rid of Outline menus, they are not needed
4998 ;; Need to do this here because define-derived-mode sets up
4999 ;; the keymap so late. Still, it is a waste to call this each time
5000 ;; we switch another buffer into org-mode.
5001 (if (featurep 'xemacs)
5002 (when (boundp 'outline-mode-menu-heading)
5003 ;; Assume this is Greg's port, it uses easymenu
5004 (easy-menu-remove outline-mode-menu-heading)
5005 (easy-menu-remove outline-mode-menu-show)
5006 (easy-menu-remove outline-mode-menu-hide))
5007 (define-key org-mode-map [menu-bar headings] 'undefined)
5008 (define-key org-mode-map [menu-bar hide] 'undefined)
5009 (define-key org-mode-map [menu-bar show] 'undefined))
5011 (org-load-modules-maybe)
5012 (easy-menu-add org-org-menu)
5013 (easy-menu-add org-tbl-menu)
5014 (org-install-agenda-files-menu)
5015 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5016 (add-to-invisibility-spec '(org-cwidth))
5017 (add-to-invisibility-spec '(org-hide-block . t))
5018 (when (featurep 'xemacs)
5019 (org-set-local 'line-move-ignore-invisible t))
5020 (org-set-local 'outline-regexp org-outline-regexp)
5021 (org-set-local 'outline-level 'org-outline-level)
5022 (setq bidi-paragraph-direction 'left-to-right)
5023 (when (and org-ellipsis
5024 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5025 (fboundp 'make-glyph-code))
5026 (unless org-display-table
5027 (setq org-display-table (make-display-table)))
5028 (set-display-table-slot
5029 org-display-table 4
5030 (vconcat (mapcar
5031 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5032 org-ellipsis)))
5033 (if (stringp org-ellipsis) org-ellipsis "..."))))
5034 (setq buffer-display-table org-display-table))
5035 (org-set-regexps-and-options)
5036 (when (and org-tag-faces (not org-tags-special-faces-re))
5037 ;; tag faces set outside customize.... force initialization.
5038 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5039 ;; Calc embedded
5040 (org-set-local 'calc-embedded-open-mode "# ")
5041 (modify-syntax-entry ?@ "w")
5042 (if org-startup-truncated (setq truncate-lines t))
5043 (org-set-local 'font-lock-unfontify-region-function
5044 'org-unfontify-region)
5045 ;; Activate before-change-function
5046 (org-set-local 'org-table-may-need-update t)
5047 (org-add-hook 'before-change-functions 'org-before-change-function nil
5048 'local)
5049 ;; Check for running clock before killing a buffer
5050 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5051 ;; Indentation.
5052 (org-set-local 'indent-line-function 'org-indent-line)
5053 (org-set-local 'indent-region-function 'org-indent-region)
5054 ;; Initialize radio targets.
5055 (org-update-radio-target-regexp)
5056 ;; Filling and auto-filling.
5057 (org-setup-filling)
5058 ;; Comments.
5059 (org-setup-comments-handling)
5060 ;; Beginning/end of defun
5061 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5062 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5063 ;; Next error for sparse trees
5064 (org-set-local 'next-error-function 'org-occur-next-match)
5065 ;; Make sure dependence stuff works reliably, even for users who set it
5066 ;; too late :-(
5067 (if org-enforce-todo-dependencies
5068 (add-hook 'org-blocker-hook
5069 'org-block-todo-from-children-or-siblings-or-parent)
5070 (remove-hook 'org-blocker-hook
5071 'org-block-todo-from-children-or-siblings-or-parent))
5072 (if org-enforce-todo-checkbox-dependencies
5073 (add-hook 'org-blocker-hook
5074 'org-block-todo-from-checkboxes)
5075 (remove-hook 'org-blocker-hook
5076 'org-block-todo-from-checkboxes))
5078 ;; Align options lines
5079 (org-set-local
5080 'align-mode-rules-list
5081 '((org-in-buffer-settings
5082 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5083 (modes . '(org-mode)))))
5085 ;; Imenu
5086 (org-set-local 'imenu-create-index-function
5087 'org-imenu-get-tree)
5089 ;; Make isearch reveal context
5090 (if (or (featurep 'xemacs)
5091 (not (boundp 'outline-isearch-open-invisible-function)))
5092 ;; Emacs 21 and XEmacs make use of the hook
5093 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5094 ;; Emacs 22 deals with this through a special variable
5095 (org-set-local 'outline-isearch-open-invisible-function
5096 (lambda (&rest ignore) (org-show-context 'isearch))))
5098 ;; Turn on org-beamer-mode?
5099 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5101 ;; Setup the pcomplete hooks
5102 (set (make-local-variable 'pcomplete-command-completion-function)
5103 'org-pcomplete-initial)
5104 (set (make-local-variable 'pcomplete-command-name-function)
5105 'org-command-at-point)
5106 (set (make-local-variable 'pcomplete-default-completion-function)
5107 'ignore)
5108 (set (make-local-variable 'pcomplete-parse-arguments-function)
5109 'org-parse-arguments)
5110 (set (make-local-variable 'pcomplete-termination-string) "")
5111 (when (>= emacs-major-version 23)
5112 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5114 ;; If empty file that did not turn on org-mode automatically, make it to.
5115 (if (and org-insert-mode-line-in-empty-file
5116 (org-called-interactively-p 'any)
5117 (= (point-min) (point-max)))
5118 (insert "# -*- mode: org -*-\n\n"))
5119 (unless org-inhibit-startup
5120 (when org-startup-align-all-tables
5121 (let ((bmp (buffer-modified-p)))
5122 (org-table-map-tables 'org-table-align 'quietly)
5123 (set-buffer-modified-p bmp)))
5124 (when org-startup-with-inline-images
5125 (org-display-inline-images))
5126 (when org-startup-indented
5127 (require 'org-indent)
5128 (org-indent-mode 1))
5129 (unless org-inhibit-startup-visibility-stuff
5130 (org-set-startup-visibility)))
5131 ;; Try to set org-hide correctly
5132 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5134 (when (fboundp 'abbrev-table-put)
5135 (abbrev-table-put org-mode-abbrev-table
5136 :parents (list text-mode-abbrev-table)))
5138 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5141 (defun org-find-invisible-foreground ()
5142 (let ((candidates (remove
5143 "unspecified-bg"
5144 (list
5145 (face-background 'default)
5146 (face-background 'org-default)
5147 (cdr (assoc 'background-color default-frame-alist))
5148 (cdr (assoc 'background-color initial-frame-alist))
5149 (cdr (assoc 'background-color window-system-default-frame-alist))
5150 (face-foreground 'org-hide)))))
5151 (car (remove nil candidates))))
5153 (defun org-current-time ()
5154 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5155 (if (> (car org-time-stamp-rounding-minutes) 1)
5156 (let ((r (car org-time-stamp-rounding-minutes))
5157 (time (decode-time)))
5158 (apply 'encode-time
5159 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5160 (nthcdr 2 time))))
5161 (current-time)))
5163 (defun org-today ()
5164 "Return today date, considering `org-extend-today-until'."
5165 (time-to-days
5166 (time-subtract (current-time)
5167 (list 0 (* 3600 org-extend-today-until) 0))))
5169 ;;;; Font-Lock stuff, including the activators
5171 (defvar org-mouse-map (make-sparse-keymap))
5172 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5173 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5174 (when org-mouse-1-follows-link
5175 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5176 (when org-tab-follows-link
5177 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5178 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5180 (require 'font-lock)
5182 (defconst org-non-link-chars "]\t\n\r<>")
5183 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5184 "shell" "elisp" "doi" "message"))
5185 (defvar org-link-types-re nil
5186 "Matches a link that has a url-like prefix like \"http:\"")
5187 (defvar org-link-re-with-space nil
5188 "Matches a link with spaces, optional angular brackets around it.")
5189 (defvar org-link-re-with-space2 nil
5190 "Matches a link with spaces, optional angular brackets around it.")
5191 (defvar org-link-re-with-space3 nil
5192 "Matches a link with spaces, only for internal part in bracket links.")
5193 (defvar org-angle-link-re nil
5194 "Matches link with angular brackets, spaces are allowed.")
5195 (defvar org-plain-link-re nil
5196 "Matches plain link, without spaces.")
5197 (defvar org-bracket-link-regexp nil
5198 "Matches a link in double brackets.")
5199 (defvar org-bracket-link-analytic-regexp nil
5200 "Regular expression used to analyze links.
5201 Here is what the match groups contain after a match:
5202 1: http:
5203 2: http
5204 3: path
5205 4: [desc]
5206 5: desc")
5207 (defvar org-bracket-link-analytic-regexp++ nil
5208 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5209 (defvar org-any-link-re nil
5210 "Regular expression matching any link.")
5212 (defcustom org-match-sexp-depth 3
5213 "Number of stacked braces for sub/superscript matching.
5214 This has to be set before loading org.el to be effective."
5215 :group 'org-export-translation ; ??????????????????????????/
5216 :type 'integer)
5218 (defun org-create-multibrace-regexp (left right n)
5219 "Create a regular expression which will match a balanced sexp.
5220 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5221 as single character strings.
5222 The regexp returned will match the entire expression including the
5223 delimiters. It will also define a single group which contains the
5224 match except for the outermost delimiters. The maximum depth of
5225 stacked delimiters is N. Escaping delimiters is not possible."
5226 (let* ((nothing (concat "[^" left right "]*?"))
5227 (or "\\|")
5228 (re nothing)
5229 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5230 (while (> n 1)
5231 (setq n (1- n)
5232 re (concat re or next)
5233 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5234 (concat left "\\(" re "\\)" right)))
5236 (defvar org-match-substring-regexp
5237 (concat
5238 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5239 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5240 "\\|"
5241 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5242 "\\|"
5243 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5244 "The regular expression matching a sub- or superscript.")
5246 (defvar org-match-substring-with-braces-regexp
5247 (concat
5248 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5249 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5250 "\\)")
5251 "The regular expression matching a sub- or superscript, forcing braces.")
5253 (defun org-make-link-regexps ()
5254 "Update the link regular expressions.
5255 This should be called after the variable `org-link-types' has changed."
5256 (setq org-link-types-re
5257 (concat
5258 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5259 org-link-re-with-space
5260 (concat
5261 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5262 "\\([^" org-non-link-chars " ]"
5263 "[^" org-non-link-chars "]*"
5264 "[^" org-non-link-chars " ]\\)>?")
5265 org-link-re-with-space2
5266 (concat
5267 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5268 "\\([^" org-non-link-chars " ]"
5269 "[^\t\n\r]*"
5270 "[^" org-non-link-chars " ]\\)>?")
5271 org-link-re-with-space3
5272 (concat
5273 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5274 "\\([^" org-non-link-chars " ]"
5275 "[^\t\n\r]*\\)")
5276 org-angle-link-re
5277 (concat
5278 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5279 "\\([^" org-non-link-chars " ]"
5280 "[^" org-non-link-chars "]*"
5281 "\\)>")
5282 org-plain-link-re
5283 (concat
5284 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5285 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5286 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5287 org-bracket-link-regexp
5288 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5289 org-bracket-link-analytic-regexp
5290 (concat
5291 "\\[\\["
5292 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5293 "\\([^]]+\\)"
5294 "\\]"
5295 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5296 "\\]")
5297 org-bracket-link-analytic-regexp++
5298 (concat
5299 "\\[\\["
5300 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5301 "\\([^]]+\\)"
5302 "\\]"
5303 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5304 "\\]")
5305 org-any-link-re
5306 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5307 org-angle-link-re "\\)\\|\\("
5308 org-plain-link-re "\\)")))
5310 (org-make-link-regexps)
5312 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5313 "Regular expression for fast time stamp matching.")
5314 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5315 "Regular expression for fast time stamp matching.")
5316 (defconst org-ts-regexp0
5317 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5318 "Regular expression matching time strings for analysis.
5319 This one does not require the space after the date, so it can be used
5320 on a string that terminates immediately after the date.")
5321 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5322 "Regular expression matching time strings for analysis.")
5323 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5324 "Regular expression matching time stamps, with groups.")
5325 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5326 "Regular expression matching time stamps (also [..]), with groups.")
5327 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5328 "Regular expression matching a time stamp range.")
5329 (defconst org-tr-regexp-both
5330 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5331 "Regular expression matching a time stamp range.")
5332 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5333 org-ts-regexp "\\)?")
5334 "Regular expression matching a time stamp or time stamp range.")
5335 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5336 org-ts-regexp-both "\\)?")
5337 "Regular expression matching a time stamp or time stamp range.
5338 The time stamps may be either active or inactive.")
5340 (defvar org-emph-face nil)
5342 (defun org-do-emphasis-faces (limit)
5343 "Run through the buffer and add overlays to emphasized strings."
5344 (let (rtn a)
5345 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5346 (if (not (= (char-after (match-beginning 3))
5347 (char-after (match-beginning 4))))
5348 (progn
5349 (setq rtn t)
5350 (setq a (assoc (match-string 3) org-emphasis-alist))
5351 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5352 'face
5353 (nth 1 a))
5354 (and (nth 4 a)
5355 (org-remove-flyspell-overlays-in
5356 (match-beginning 0) (match-end 0)))
5357 (add-text-properties (match-beginning 2) (match-end 2)
5358 '(font-lock-multiline t org-emphasis t))
5359 (when org-hide-emphasis-markers
5360 (add-text-properties (match-end 4) (match-beginning 5)
5361 '(invisible org-link))
5362 (add-text-properties (match-beginning 3) (match-end 3)
5363 '(invisible org-link)))))
5364 (backward-char 1))
5365 rtn))
5367 (defun org-emphasize (&optional char)
5368 "Insert or change an emphasis, i.e. a font like bold or italic.
5369 If there is an active region, change that region to a new emphasis.
5370 If there is no region, just insert the marker characters and position
5371 the cursor between them.
5372 CHAR should be either the marker character, or the first character of the
5373 HTML tag associated with that emphasis. If CHAR is a space, the means
5374 to remove the emphasis of the selected region.
5375 If char is not given (for example in an interactive call) it
5376 will be prompted for."
5377 (interactive)
5378 (let ((eal org-emphasis-alist) e det
5379 (erc org-emphasis-regexp-components)
5380 (prompt "")
5381 (string "") beg end move tag c s)
5382 (if (org-region-active-p)
5383 (setq beg (region-beginning) end (region-end)
5384 string (buffer-substring beg end))
5385 (setq move t))
5387 (while (setq e (pop eal))
5388 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5389 c (aref tag 0))
5390 (push (cons c (string-to-char (car e))) det)
5391 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5392 (substring tag 1)))))
5393 (setq det (nreverse det))
5394 (unless char
5395 (message "%s" (concat "Emphasis marker or tag:" prompt))
5396 (setq char (read-char-exclusive)))
5397 (setq char (or (cdr (assoc char det)) char))
5398 (if (equal char ?\ )
5399 (setq s "" move nil)
5400 (unless (assoc (char-to-string char) org-emphasis-alist)
5401 (error "No such emphasis marker: \"%c\"" char))
5402 (setq s (char-to-string char)))
5403 (while (and (> (length string) 1)
5404 (equal (substring string 0 1) (substring string -1))
5405 (assoc (substring string 0 1) org-emphasis-alist))
5406 (setq string (substring string 1 -1)))
5407 (setq string (concat s string s))
5408 (if beg (delete-region beg end))
5409 (unless (or (bolp)
5410 (string-match (concat "[" (nth 0 erc) "\n]")
5411 (char-to-string (char-before (point)))))
5412 (insert " "))
5413 (unless (or (eobp)
5414 (string-match (concat "[" (nth 1 erc) "\n]")
5415 (char-to-string (char-after (point)))))
5416 (insert " ") (backward-char 1))
5417 (insert string)
5418 (and move (backward-char 1))))
5420 (defconst org-nonsticky-props
5421 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5423 (defsubst org-rear-nonsticky-at (pos)
5424 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5426 (defun org-activate-plain-links (limit)
5427 "Run through the buffer and add overlays to links."
5428 (catch 'exit
5429 (let (f)
5430 (when (re-search-forward (concat org-plain-link-re) limit t)
5431 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5432 (setq f (get-text-property (match-beginning 0) 'face))
5433 (if (or (eq f 'org-tag)
5434 (and (listp f) (memq 'org-tag f)))
5436 (add-text-properties (match-beginning 0) (match-end 0)
5437 (list 'mouse-face 'highlight
5438 'face 'org-link
5439 'keymap org-mouse-map))
5440 (org-rear-nonsticky-at (match-end 0)))
5441 t))))
5443 (defun org-activate-code (limit)
5444 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5445 (progn
5446 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5447 (remove-text-properties (match-beginning 0) (match-end 0)
5448 '(display t invisible t intangible t))
5449 t)))
5451 (defcustom org-src-fontify-natively nil
5452 "When non-nil, fontify code in code blocks."
5453 :type 'boolean
5454 :version "24.1"
5455 :group 'org-appearance
5456 :group 'org-babel)
5458 (defcustom org-allow-promoting-top-level-subtree nil
5459 "When non-nil, allow promoting a top level subtree.
5460 The leading star of the top level headline will be replaced
5461 by a #."
5462 :type 'boolean
5463 :version "24.1"
5464 :group 'org-appearance)
5466 (defun org-fontify-meta-lines-and-blocks (limit)
5467 (condition-case nil
5468 (org-fontify-meta-lines-and-blocks-1 limit)
5469 (error (message "org-mode fontification error"))))
5471 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5472 "Fontify #+ lines and blocks, in the correct ways."
5473 (let ((case-fold-search t))
5474 (if (re-search-forward
5475 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5476 limit t)
5477 (let ((beg (match-beginning 0))
5478 (block-start (match-end 0))
5479 (block-end nil)
5480 (lang (match-string 7))
5481 (beg1 (line-beginning-position 2))
5482 (dc1 (downcase (match-string 2)))
5483 (dc3 (downcase (match-string 3)))
5484 end end1 quoting block-type ovl)
5485 (cond
5486 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5487 ;; a single line of backend-specific content
5488 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5489 (remove-text-properties (match-beginning 0) (match-end 0)
5490 '(display t invisible t intangible t))
5491 (add-text-properties (match-beginning 1) (match-end 3)
5492 '(font-lock-fontified t face org-meta-line))
5493 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5494 '(font-lock-fontified t face org-block))
5495 ; for backend-specific code
5497 ((and (match-end 4) (equal dc3 "+begin"))
5498 ;; Truly a block
5499 (setq block-type (downcase (match-string 5))
5500 quoting (member block-type org-protecting-blocks))
5501 (when (re-search-forward
5502 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5503 nil t) ;; on purpose, we look further than LIMIT
5504 (setq end (min (point-max) (match-end 0))
5505 end1 (min (point-max) (1- (match-beginning 0))))
5506 (setq block-end (match-beginning 0))
5507 (when quoting
5508 (remove-text-properties beg end
5509 '(display t invisible t intangible t)))
5510 (add-text-properties
5511 beg end
5512 '(font-lock-fontified t font-lock-multiline t))
5513 (add-text-properties beg beg1 '(face org-meta-line))
5514 (add-text-properties end1 (min (point-max) (1+ end))
5515 '(face org-meta-line)) ; for end_src
5516 (cond
5517 ((and lang (not (string= lang "")) org-src-fontify-natively)
5518 (org-src-font-lock-fontify-block lang block-start block-end)
5519 ;; remove old background overlays
5520 (mapc (lambda (ov)
5521 (if (eq (overlay-get ov 'face) 'org-block-background)
5522 (delete-overlay ov)))
5523 (overlays-at (/ (+ beg1 block-end) 2)))
5524 ;; add a background overlay
5525 (setq ovl (make-overlay beg1 block-end))
5526 (overlay-put ovl 'face 'org-block-background)
5527 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5528 (quoting
5529 (add-text-properties beg1 (min (point-max) (1+ end1))
5530 '(face org-block))) ; end of source block
5531 ((not org-fontify-quote-and-verse-blocks))
5532 ((string= block-type "quote")
5533 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5534 ((string= block-type "verse")
5535 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5536 (add-text-properties beg beg1 '(face org-block-begin-line))
5537 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5538 '(face org-block-end-line))
5540 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5541 (add-text-properties
5542 beg (match-end 3)
5543 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5544 '(font-lock-fontified t invisible t)
5545 '(font-lock-fontified t face org-document-info-keyword)))
5546 (add-text-properties
5547 (match-beginning 6) (match-end 6)
5548 (if (string-equal dc1 "+title:")
5549 '(font-lock-fontified t face org-document-title)
5550 '(font-lock-fontified t face org-document-info))))
5551 ((or (equal dc1 "+results")
5552 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5553 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5554 "+call:" "+header:" "+headers:" "+name:"))
5555 (and (match-end 4) (equal dc3 "+attr")))
5556 (add-text-properties
5557 beg (match-end 0)
5558 '(font-lock-fontified t face org-meta-line))
5560 ((member dc3 '(" " ""))
5561 (add-text-properties
5562 beg (match-end 0)
5563 '(font-lock-fontified t face font-lock-comment-face)))
5564 ((not (member (char-after beg) '(?\ ?\t)))
5565 ;; just any other in-buffer setting, but not indented
5566 (add-text-properties
5567 beg (match-end 0)
5568 '(font-lock-fontified t face org-meta-line))
5570 (t nil))))))
5572 (defun org-strip-protective-commas (beg end)
5573 "Strip protective commas between BEG and END in the current buffer."
5574 (interactive "r")
5575 (save-excursion
5576 (save-match-data
5577 (goto-char beg)
5578 (let ((front-line (save-excursion
5579 (re-search-forward
5580 "[^[:space:]]" end t)
5581 (goto-char (match-beginning 0))
5582 (current-column))))
5583 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5584 (goto-char (match-beginning 1))
5585 (when (= (current-column) front-line)
5586 (replace-match "" nil nil nil 1)))))))
5588 (defun org-activate-angle-links (limit)
5589 "Run through the buffer and add overlays to links."
5590 (if (re-search-forward org-angle-link-re limit t)
5591 (progn
5592 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5593 (add-text-properties (match-beginning 0) (match-end 0)
5594 (list 'mouse-face 'highlight
5595 'keymap org-mouse-map))
5596 (org-rear-nonsticky-at (match-end 0))
5597 t)))
5599 (defun org-activate-footnote-links (limit)
5600 "Run through the buffer and add overlays to footnotes."
5601 (let ((fn (org-footnote-next-reference-or-definition limit)))
5602 (when fn
5603 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5604 (org-remove-flyspell-overlays-in beg end)
5605 (add-text-properties beg end
5606 (list 'mouse-face 'highlight
5607 'keymap org-mouse-map
5608 'help-echo
5609 (if (= (point-at-bol) beg)
5610 "Footnote definition"
5611 "Footnote reference")
5612 'font-lock-fontified t
5613 'font-lock-multiline t
5614 'face 'org-footnote))))))
5616 (defun org-activate-bracket-links (limit)
5617 "Run through the buffer and add overlays to bracketed links."
5618 (if (re-search-forward org-bracket-link-regexp limit t)
5619 (let* ((help (concat "LINK: "
5620 (org-match-string-no-properties 1)))
5621 ;; FIXME: above we should remove the escapes.
5622 ;; but that requires another match, protecting match data,
5623 ;; a lot of overhead for font-lock.
5624 (ip (org-maybe-intangible
5625 (list 'invisible 'org-link
5626 'keymap org-mouse-map 'mouse-face 'highlight
5627 'font-lock-multiline t 'help-echo help)))
5628 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5629 'font-lock-multiline t 'help-echo help)))
5630 ;; We need to remove the invisible property here. Table narrowing
5631 ;; may have made some of this invisible.
5632 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5633 (remove-text-properties (match-beginning 0) (match-end 0)
5634 '(invisible nil))
5635 (if (match-end 3)
5636 (progn
5637 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5638 (org-rear-nonsticky-at (match-beginning 3))
5639 (add-text-properties (match-beginning 3) (match-end 3) vp)
5640 (org-rear-nonsticky-at (match-end 3))
5641 (add-text-properties (match-end 3) (match-end 0) ip)
5642 (org-rear-nonsticky-at (match-end 0)))
5643 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5644 (org-rear-nonsticky-at (match-beginning 1))
5645 (add-text-properties (match-beginning 1) (match-end 1) vp)
5646 (org-rear-nonsticky-at (match-end 1))
5647 (add-text-properties (match-end 1) (match-end 0) ip)
5648 (org-rear-nonsticky-at (match-end 0)))
5649 t)))
5651 (defun org-activate-dates (limit)
5652 "Run through the buffer and add overlays to dates."
5653 (if (re-search-forward org-tsr-regexp-both limit t)
5654 (progn
5655 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5656 (add-text-properties (match-beginning 0) (match-end 0)
5657 (list 'mouse-face 'highlight
5658 'keymap org-mouse-map))
5659 (org-rear-nonsticky-at (match-end 0))
5660 (when org-display-custom-times
5661 (if (match-end 3)
5662 (org-display-custom-time (match-beginning 3) (match-end 3)))
5663 (org-display-custom-time (match-beginning 1) (match-end 1)))
5664 t)))
5666 (defvar org-target-link-regexp nil
5667 "Regular expression matching radio targets in plain text.")
5668 (make-variable-buffer-local 'org-target-link-regexp)
5669 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5670 "Regular expression matching a link target.")
5671 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5672 "Regular expression matching a radio target.")
5673 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5674 "Regular expression matching any target.")
5676 (defun org-activate-target-links (limit)
5677 "Run through the buffer and add overlays to target matches."
5678 (when org-target-link-regexp
5679 (let ((case-fold-search t))
5680 (if (re-search-forward org-target-link-regexp limit t)
5681 (progn
5682 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5683 (add-text-properties (match-beginning 0) (match-end 0)
5684 (list 'mouse-face 'highlight
5685 'keymap org-mouse-map
5686 'help-echo "Radio target link"
5687 'org-linked-text t))
5688 (org-rear-nonsticky-at (match-end 0))
5689 t)))))
5691 (defun org-update-radio-target-regexp ()
5692 "Find all radio targets in this file and update the regular expression."
5693 (interactive)
5694 (when (memq 'radio org-activate-links)
5695 (setq org-target-link-regexp
5696 (org-make-target-link-regexp (org-all-targets 'radio)))
5697 (org-restart-font-lock)))
5699 (defun org-hide-wide-columns (limit)
5700 (let (s e)
5701 (setq s (text-property-any (point) (or limit (point-max))
5702 'org-cwidth t))
5703 (when s
5704 (setq e (next-single-property-change s 'org-cwidth))
5705 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5706 (goto-char e)
5707 t)))
5709 (defvar org-latex-and-specials-regexp nil
5710 "Regular expression for highlighting export special stuff.")
5711 (defvar org-match-substring-regexp)
5712 (defvar org-match-substring-with-braces-regexp)
5714 ;; This should be with the exporter code, but we also use if for font-locking
5715 (defconst org-export-html-special-string-regexps
5716 '(("\\\\-" . "&shy;")
5717 ("---\\([^-]\\)" . "&mdash;\\1")
5718 ("--\\([^-]\\)" . "&ndash;\\1")
5719 ("\\.\\.\\." . "&hellip;"))
5720 "Regular expressions for special string conversion.")
5723 (defun org-compute-latex-and-specials-regexp ()
5724 "Compute regular expression for stuff treated specially by exporters."
5725 (if (not org-highlight-latex-fragments-and-specials)
5726 (org-set-local 'org-latex-and-specials-regexp nil)
5727 (require 'org-exp)
5728 (let*
5729 ((matchers (plist-get org-format-latex-options :matchers))
5730 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5731 org-latex-regexps)))
5732 (org-export-allow-BIND nil)
5733 (options (org-combine-plists (org-default-export-plist)
5734 (org-infile-export-plist)))
5735 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5736 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5737 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5738 (org-export-html-expand (plist-get options :expand-quoted-html))
5739 (org-export-with-special-strings (plist-get options :special-strings))
5740 (re-sub
5741 (cond
5742 ((equal org-export-with-sub-superscripts '{})
5743 (list org-match-substring-with-braces-regexp))
5744 (org-export-with-sub-superscripts
5745 (list org-match-substring-regexp))))
5746 (re-latex
5747 (if org-export-with-LaTeX-fragments
5748 (mapcar (lambda (x) (nth 1 x)) latexs)))
5749 (re-macros
5750 (if org-export-with-TeX-macros
5751 (list (concat "\\\\"
5752 (regexp-opt
5753 (append
5755 (delq nil
5756 (mapcar 'car-safe
5757 (append org-entities-user
5758 org-entities)))
5759 (if (boundp 'org-latex-entities)
5760 (mapcar (lambda (x)
5761 (or (car-safe x) x))
5762 org-latex-entities)
5763 nil))
5764 'words))) ; FIXME
5766 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5767 (re-special (if org-export-with-special-strings
5768 (mapcar (lambda (x) (car x))
5769 org-export-html-special-string-regexps)))
5770 (re-rest
5771 (delq nil
5772 (list
5773 (if org-export-html-expand "@<[^>\n]+>")
5774 ))))
5775 (org-set-local
5776 'org-latex-and-specials-regexp
5777 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5778 re-rest) "\\|")))))
5780 (defun org-do-latex-and-special-faces (limit)
5781 "Run through the buffer and add overlays to links."
5782 (when org-latex-and-specials-regexp
5783 (let (rtn d)
5784 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5785 limit t))
5786 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5787 'face))
5788 '(org-code org-verbatim underline)))
5789 (progn
5790 (setq rtn t
5791 d (cond ((member (char-after (1+ (match-beginning 0)))
5792 '(?_ ?^)) 1)
5793 (t 0)))
5794 (font-lock-prepend-text-property
5795 (+ d (match-beginning 0)) (match-end 0)
5796 'face 'org-latex-and-export-specials)
5797 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5798 '(font-lock-multiline t)))))
5799 rtn)))
5801 (defun org-restart-font-lock ()
5802 "Restart `font-lock-mode', to force refontification."
5803 (when (and (boundp 'font-lock-mode) font-lock-mode)
5804 (font-lock-mode -1)
5805 (font-lock-mode 1)))
5807 (defun org-all-targets (&optional radio)
5808 "Return a list of all targets in this file.
5809 With optional argument RADIO, only find radio targets."
5810 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5811 rtn)
5812 (save-excursion
5813 (goto-char (point-min))
5814 (while (re-search-forward re nil t)
5815 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5816 rtn)))
5818 (defun org-make-target-link-regexp (targets)
5819 "Make regular expression matching all strings in TARGETS.
5820 The regular expression finds the targets also if there is a line break
5821 between words."
5822 (and targets
5823 (concat
5824 "\\<\\("
5825 (mapconcat
5826 (lambda (x)
5827 (setq x (regexp-quote x))
5828 (while (string-match " +" x)
5829 (setq x (replace-match "\\s-+" t t x)))
5831 targets
5832 "\\|")
5833 "\\)\\>")))
5835 (defun org-activate-tags (limit)
5836 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5837 (progn
5838 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5839 (add-text-properties (match-beginning 1) (match-end 1)
5840 (list 'mouse-face 'highlight
5841 'keymap org-mouse-map))
5842 (org-rear-nonsticky-at (match-end 1))
5843 t)))
5845 (defun org-outline-level ()
5846 "Compute the outline level of the heading at point.
5847 This function assumes that the cursor is at the beginning of a line matched
5848 by `outline-regexp'. Otherwise it returns garbage.
5849 If this is called at a normal headline, the level is the number of stars.
5850 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5851 (save-excursion
5852 (looking-at org-outline-regexp)
5853 (1- (- (match-end 0) (match-beginning 0)))))
5855 (defvar org-font-lock-keywords nil)
5857 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5858 "Regular expression matching a property line.")
5860 (defvar org-font-lock-hook nil
5861 "Functions to be called for special font lock stuff.")
5863 (defvar org-font-lock-set-keywords-hook nil
5864 "Functions that can manipulate `org-font-lock-extra-keywords'.
5865 This is called after `org-font-lock-extra-keywords' is defined, but before
5866 it is installed to be used by font lock. This can be useful if something
5867 needs to be inserted at a specific position in the font-lock sequence.")
5869 (defun org-font-lock-hook (limit)
5870 "Run `org-font-lock-hook' within LIMIT."
5871 (run-hook-with-args 'org-font-lock-hook limit))
5873 (defun org-set-font-lock-defaults ()
5874 "Set font lock defaults for the current buffer."
5875 (let* ((em org-fontify-emphasized-text)
5876 (lk org-activate-links)
5877 (org-font-lock-extra-keywords
5878 (list
5879 ;; Call the hook
5880 '(org-font-lock-hook)
5881 ;; Headlines
5882 `(,(if org-fontify-whole-heading-line
5883 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5884 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5885 (1 (org-get-level-face 1))
5886 (2 (org-get-level-face 2))
5887 (3 (org-get-level-face 3)))
5888 ;; Table lines
5889 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5890 (1 'org-table t))
5891 ;; Table internals
5892 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5893 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5894 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5895 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5896 ;; Drawers
5897 (list org-drawer-regexp '(0 'org-special-keyword t))
5898 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5899 ;; Properties
5900 (list org-property-re
5901 '(1 'org-special-keyword t)
5902 '(3 'org-property-value t))
5903 ;; Links
5904 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5905 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5906 (if (memq 'plain lk) '(org-activate-plain-links))
5907 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5908 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5909 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5910 (if (memq 'footnote lk) '(org-activate-footnote-links))
5911 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5912 '(org-hide-wide-columns (0 nil append))
5913 ;; TODO keyword
5914 (list (format org-heading-keyword-regexp-format
5915 org-todo-regexp)
5916 '(2 (org-get-todo-face 2) t))
5917 ;; DONE
5918 (if org-fontify-done-headline
5919 (list (format org-heading-keyword-regexp-format
5920 (concat
5921 "\\(?:"
5922 (mapconcat 'regexp-quote org-done-keywords "\\|")
5923 "\\)"))
5924 '(2 'org-headline-done t))
5925 nil)
5926 ;; Priorities
5927 '(org-font-lock-add-priority-faces)
5928 ;; Tags
5929 '(org-font-lock-add-tag-faces)
5930 ;; Special keywords
5931 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5932 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5933 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5934 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5935 ;; Emphasis
5936 (if em
5937 (if (featurep 'xemacs)
5938 '(org-do-emphasis-faces (0 nil append))
5939 '(org-do-emphasis-faces)))
5940 ;; Checkboxes
5941 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5942 1 'org-checkbox prepend)
5943 (if (cdr (assq 'checkbox org-list-automatic-rules))
5944 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5945 (0 (org-get-checkbox-statistics-face) t)))
5946 ;; Description list items
5947 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5948 1 'org-list-dt prepend)
5949 ;; ARCHIVEd headings
5950 (list (concat
5951 org-outline-regexp-bol
5952 "\\(.*:" org-archive-tag ":.*\\)")
5953 '(1 'org-archived prepend))
5954 ;; Specials
5955 '(org-do-latex-and-special-faces)
5956 '(org-fontify-entities)
5957 '(org-raise-scripts)
5958 ;; Code
5959 '(org-activate-code (1 'org-code t))
5960 ;; COMMENT
5961 (list (format org-heading-keyword-regexp-format
5962 (concat "\\("
5963 org-comment-string "\\|" org-quote-string
5964 "\\)"))
5965 '(2 'org-special-keyword t))
5966 ;; Blocks and meta lines
5967 '(org-fontify-meta-lines-and-blocks)
5969 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5970 (run-hooks 'org-font-lock-set-keywords-hook)
5971 ;; Now set the full font-lock-keywords
5972 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5973 (org-set-local 'font-lock-defaults
5974 '(org-font-lock-keywords t nil nil backward-paragraph))
5975 (kill-local-variable 'font-lock-keywords) nil))
5977 (defun org-toggle-pretty-entities ()
5978 "Toggle the composition display of entities as UTF8 characters."
5979 (interactive)
5980 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5981 (org-restart-font-lock)
5982 (if org-pretty-entities
5983 (message "Entities are displayed as UTF8 characters")
5984 (save-restriction
5985 (widen)
5986 (org-decompose-region (point-min) (point-max))
5987 (message "Entities are displayed plain"))))
5989 (defvar org-custom-properties-overlays nil
5990 "List of overlays used for custom properties.")
5991 (make-variable-buffer-local 'org-custom-properties-overlays)
5993 (defun org-toggle-custom-properties-visibility ()
5994 "Display or hide properties in `org-custom-properties'."
5995 (interactive)
5996 (if org-custom-properties-overlays
5997 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5998 (setq org-custom-properties-overlays nil))
5999 (unless (not org-custom-properties)
6000 (save-excursion
6001 (save-restriction
6002 (widen)
6003 (goto-char (point-min))
6004 (while (re-search-forward org-property-re nil t)
6005 (mapc (lambda(p)
6006 (when (equal p (substring (match-string 1) 1 -1))
6007 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6008 (overlay-put o 'invisible t)
6009 (overlay-put o 'org-custom-property t)
6010 (push o org-custom-properties-overlays))))
6011 org-custom-properties)))))))
6013 (defun org-fontify-entities (limit)
6014 "Find an entity to fontify."
6015 (let (ee)
6016 (when org-pretty-entities
6017 (catch 'match
6018 (while (re-search-forward
6019 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6020 limit t)
6021 (if (and (not (org-in-indented-comment-line))
6022 (setq ee (org-entity-get (match-string 1)))
6023 (= (length (nth 6 ee)) 1))
6024 (let*
6025 ((end (if (equal (match-string 2) "{}")
6026 (match-end 2)
6027 (match-end 1))))
6028 (add-text-properties
6029 (match-beginning 0) end
6030 (list 'font-lock-fontified t))
6031 (compose-region (match-beginning 0) end
6032 (nth 6 ee) nil)
6033 (backward-char 1)
6034 (throw 'match t))))
6035 nil))))
6037 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6038 "Fontify string S like in Org-mode."
6039 (with-temp-buffer
6040 (insert s)
6041 (let ((org-odd-levels-only odd-levels))
6042 (org-mode)
6043 (font-lock-fontify-buffer)
6044 (buffer-string))))
6046 (defvar org-m nil)
6047 (defvar org-l nil)
6048 (defvar org-f nil)
6049 (defun org-get-level-face (n)
6050 "Get the right face for match N in font-lock matching of headlines."
6051 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6052 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6053 (if org-cycle-level-faces
6054 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6055 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6056 (cond
6057 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6058 ((eq n 2) org-f)
6059 (t (if org-level-color-stars-only nil org-f))))
6062 (defun org-get-todo-face (kwd)
6063 "Get the right face for a TODO keyword KWD.
6064 If KWD is a number, get the corresponding match group."
6065 (if (numberp kwd) (setq kwd (match-string kwd)))
6066 (or (org-face-from-face-or-color
6067 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6068 (and (member kwd org-done-keywords) 'org-done)
6069 'org-todo))
6071 (defun org-face-from-face-or-color (context inherit face-or-color)
6072 "Create a face list that inherits INHERIT, but sets the foreground color.
6073 When FACE-OR-COLOR is not a string, just return it."
6074 (if (stringp face-or-color)
6075 (list :inherit inherit
6076 (cdr (assoc context org-faces-easy-properties))
6077 face-or-color)
6078 face-or-color))
6080 (defun org-font-lock-add-tag-faces (limit)
6081 "Add the special tag faces."
6082 (when (and org-tag-faces org-tags-special-faces-re)
6083 (while (re-search-forward org-tags-special-faces-re limit t)
6084 (add-text-properties (match-beginning 1) (match-end 1)
6085 (list 'face (org-get-tag-face 1)
6086 'font-lock-fontified t))
6087 (backward-char 1))))
6089 (defun org-font-lock-add-priority-faces (limit)
6090 "Add the special priority faces."
6091 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6092 (when (save-match-data (org-at-heading-p))
6093 (add-text-properties
6094 (match-beginning 0) (match-end 0)
6095 (list 'face (or (org-face-from-face-or-color
6096 'priority 'org-special-keyword
6097 (cdr (assoc (char-after (match-beginning 1))
6098 org-priority-faces)))
6099 'org-special-keyword)
6100 'font-lock-fontified t)))))
6102 (defun org-get-tag-face (kwd)
6103 "Get the right face for a TODO keyword KWD.
6104 If KWD is a number, get the corresponding match group."
6105 (if (numberp kwd) (setq kwd (match-string kwd)))
6106 (or (org-face-from-face-or-color
6107 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6108 'org-tag))
6110 (defun org-unfontify-region (beg end &optional maybe_loudly)
6111 "Remove fontification and activation overlays from links."
6112 (font-lock-default-unfontify-region beg end)
6113 (let* ((buffer-undo-list t)
6114 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6115 (inhibit-modification-hooks t)
6116 deactivate-mark buffer-file-name buffer-file-truename)
6117 (org-decompose-region beg end)
6118 (remove-text-properties beg end
6119 '(mouse-face t keymap t org-linked-text t
6120 invisible t intangible t
6121 org-no-flyspell t org-emphasis t))
6122 (org-remove-font-lock-display-properties beg end)))
6124 (defconst org-script-display '(((raise -0.3) (height 0.7))
6125 ((raise 0.3) (height 0.7))
6126 ((raise -0.5))
6127 ((raise 0.5)))
6128 "Display properties for showing superscripts and subscripts.")
6130 (defun org-remove-font-lock-display-properties (beg end)
6131 "Remove specific display properties that have been added by font lock.
6132 The will remove the raise properties that are used to show superscripts
6133 and subscripts."
6134 (let (next prop)
6135 (while (< beg end)
6136 (setq next (next-single-property-change beg 'display nil end)
6137 prop (get-text-property beg 'display))
6138 (if (member prop org-script-display)
6139 (put-text-property beg next 'display nil))
6140 (setq beg next))))
6142 (defun org-raise-scripts (limit)
6143 "Add raise properties to sub/superscripts."
6144 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6145 (if (re-search-forward
6146 (if (eq org-use-sub-superscripts t)
6147 org-match-substring-regexp
6148 org-match-substring-with-braces-regexp)
6149 limit t)
6150 (let* ((pos (point)) table-p comment-p
6151 (mpos (match-beginning 3))
6152 (emph-p (get-text-property mpos 'org-emphasis))
6153 (link-p (get-text-property mpos 'mouse-face))
6154 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6155 (goto-char (point-at-bol))
6156 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6157 comment-p (org-looking-at-p "[ \t]*#"))
6158 (goto-char pos)
6159 ;; FIXME: Should we go back one character here, for a_b^c
6160 ;; (goto-char (1- pos)) ;????????????????????
6161 (if (or comment-p emph-p link-p keyw-p)
6163 (put-text-property (match-beginning 3) (match-end 0)
6164 'display
6165 (if (equal (char-after (match-beginning 2)) ?^)
6166 (nth (if table-p 3 1) org-script-display)
6167 (nth (if table-p 2 0) org-script-display)))
6168 (add-text-properties (match-beginning 2) (match-end 2)
6169 (list 'invisible t
6170 'org-dwidth t 'org-dwidth-n 1))
6171 (if (and (eq (char-after (match-beginning 3)) ?{)
6172 (eq (char-before (match-end 3)) ?}))
6173 (progn
6174 (add-text-properties
6175 (match-beginning 3) (1+ (match-beginning 3))
6176 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6177 (add-text-properties
6178 (1- (match-end 3)) (match-end 3)
6179 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6180 t)))))
6182 ;;;; Visibility cycling, including org-goto and indirect buffer
6184 ;;; Cycling
6186 (defvar org-cycle-global-status nil)
6187 (make-variable-buffer-local 'org-cycle-global-status)
6188 (defvar org-cycle-subtree-status nil)
6189 (make-variable-buffer-local 'org-cycle-subtree-status)
6191 ;;;###autoload
6193 (defvar org-inlinetask-min-level)
6195 (defun org-cycle (&optional arg)
6196 "TAB-action and visibility cycling for Org-mode.
6198 This is the command invoked in Org-mode by the TAB key. Its main purpose
6199 is outline visibility cycling, but it also invokes other actions
6200 in special contexts.
6202 - When this function is called with a prefix argument, rotate the entire
6203 buffer through 3 states (global cycling)
6204 1. OVERVIEW: Show only top-level headlines.
6205 2. CONTENTS: Show all headlines of all levels, but no body text.
6206 3. SHOW ALL: Show everything.
6207 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6208 determined by the variable `org-startup-folded', and by any VISIBILITY
6209 properties in the buffer.
6210 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6211 including any drawers.
6213 - When inside a table, re-align the table and move to the next field.
6215 - When point is at the beginning of a headline, rotate the subtree started
6216 by this line through 3 different states (local cycling)
6217 1. FOLDED: Only the main headline is shown.
6218 2. CHILDREN: The main headline and the direct children are shown.
6219 From this state, you can move to one of the children
6220 and zoom in further.
6221 3. SUBTREE: Show the entire subtree, including body text.
6222 If there is no subtree, switch directly from CHILDREN to FOLDED.
6224 - When point is at the beginning of an empty headline and the variable
6225 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6226 of the headline by demoting and promoting it to likely levels. This
6227 speeds up creation document structure by pressing TAB once or several
6228 times right after creating a new headline.
6230 - When there is a numeric prefix, go up to a heading with level ARG, do
6231 a `show-subtree' and return to the previous cursor position. If ARG
6232 is negative, go up that many levels.
6234 - When point is not at the beginning of a headline, execute the global
6235 binding for TAB, which is re-indenting the line. See the option
6236 `org-cycle-emulate-tab' for details.
6238 - Special case: if point is at the beginning of the buffer and there is
6239 no headline in line 1, this function will act as if called with prefix arg
6240 (C-u TAB, same as S-TAB) also when called without prefix arg.
6241 But only if also the variable `org-cycle-global-at-bob' is t."
6242 (interactive "P")
6243 (org-load-modules-maybe)
6244 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6245 (and org-cycle-level-after-item/entry-creation
6246 (or (org-cycle-level)
6247 (org-cycle-item-indentation))))
6248 (let* ((limit-level
6249 (or org-cycle-max-level
6250 (and (boundp 'org-inlinetask-min-level)
6251 org-inlinetask-min-level
6252 (1- org-inlinetask-min-level))))
6253 (nstars (and limit-level
6254 (if org-odd-levels-only
6255 (and limit-level (1- (* limit-level 2)))
6256 limit-level)))
6257 (org-outline-regexp
6258 (if (not (derived-mode-p 'org-mode))
6259 outline-regexp
6260 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6261 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6262 (not (looking-at org-outline-regexp))))
6263 (org-cycle-hook
6264 (if bob-special
6265 (delq 'org-optimize-window-after-visibility-change
6266 (copy-sequence org-cycle-hook))
6267 org-cycle-hook))
6268 (pos (point)))
6270 (if (or bob-special (equal arg '(4)))
6271 ;; special case: use global cycling
6272 (setq arg t))
6274 (cond
6276 ((equal arg '(16))
6277 (setq last-command 'dummy)
6278 (org-set-startup-visibility)
6279 (message "Startup visibility, plus VISIBILITY properties"))
6281 ((equal arg '(64))
6282 (show-all)
6283 (message "Entire buffer visible, including drawers"))
6285 ;; Table: enter it or move to the next field.
6286 ((org-at-table-p 'any)
6287 (if (org-at-table.el-p)
6288 (message "Use C-c ' to edit table.el tables")
6289 (if arg (org-table-edit-field t)
6290 (org-table-justify-field-maybe)
6291 (call-interactively 'org-table-next-field))))
6293 ((run-hook-with-args-until-success
6294 'org-tab-after-check-for-table-hook))
6296 ;; Global cycling: delegate to `org-cycle-internal-global'.
6297 ((eq arg t) (org-cycle-internal-global))
6299 ;; Drawers: delegate to `org-flag-drawer'.
6300 ((and org-drawers org-drawer-regexp
6301 (save-excursion
6302 (beginning-of-line 1)
6303 (looking-at org-drawer-regexp)))
6304 (org-flag-drawer ; toggle block visibility
6305 (not (get-char-property (match-end 0) 'invisible))))
6307 ;; Show-subtree, ARG levels up from here.
6308 ((integerp arg)
6309 (save-excursion
6310 (org-back-to-heading)
6311 (outline-up-heading (if (< arg 0) (- arg)
6312 (- (funcall outline-level) arg)))
6313 (org-show-subtree)))
6315 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6316 ((and (featurep 'org-inlinetask)
6317 (org-inlinetask-at-task-p)
6318 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6319 (org-inlinetask-toggle-visibility))
6321 ((org-try-cdlatex-tab))
6323 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6324 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6325 (save-excursion (beginning-of-line 1)
6326 (looking-at org-outline-regexp)))
6327 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6328 (org-cycle-internal-local))
6330 ;; From there: TAB emulation and template completion.
6331 (buffer-read-only (org-back-to-heading))
6333 ((run-hook-with-args-until-success
6334 'org-tab-after-check-for-cycling-hook))
6336 ((org-try-structure-completion))
6338 ((run-hook-with-args-until-success
6339 'org-tab-before-tab-emulation-hook))
6341 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6342 (or (not (bolp))
6343 (not (looking-at org-outline-regexp))))
6344 (call-interactively (global-key-binding "\t")))
6346 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6347 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6348 (or (and (eq org-cycle-emulate-tab 'white)
6349 (= (match-end 0) (point-at-eol)))
6350 (and (eq org-cycle-emulate-tab 'whitestart)
6351 (>= (match-end 0) pos))))
6353 (eq org-cycle-emulate-tab t))
6354 (call-interactively (global-key-binding "\t")))
6356 (t (save-excursion
6357 (org-back-to-heading)
6358 (org-cycle)))))))
6360 (defun org-cycle-internal-global ()
6361 "Do the global cycling action."
6362 ;; Hack to avoid display of messages for .org attachments in Gnus
6363 (let ((ga (string-match "\\*fontification" (buffer-name))))
6364 (cond
6365 ((and (eq last-command this-command)
6366 (eq org-cycle-global-status 'overview))
6367 ;; We just created the overview - now do table of contents
6368 ;; This can be slow in very large buffers, so indicate action
6369 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6370 (unless ga (message "CONTENTS..."))
6371 (org-content)
6372 (unless ga (message "CONTENTS...done"))
6373 (setq org-cycle-global-status 'contents)
6374 (run-hook-with-args 'org-cycle-hook 'contents))
6376 ((and (eq last-command this-command)
6377 (eq org-cycle-global-status 'contents))
6378 ;; We just showed the table of contents - now show everything
6379 (run-hook-with-args 'org-pre-cycle-hook 'all)
6380 (show-all)
6381 (unless ga (message "SHOW ALL"))
6382 (setq org-cycle-global-status 'all)
6383 (run-hook-with-args 'org-cycle-hook 'all))
6386 ;; Default action: go to overview
6387 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6388 (org-overview)
6389 (unless ga (message "OVERVIEW"))
6390 (setq org-cycle-global-status 'overview)
6391 (run-hook-with-args 'org-cycle-hook 'overview)))))
6393 (defun org-cycle-internal-local ()
6394 "Do the local cycling action."
6395 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6396 ;; First, determine end of headline (EOH), end of subtree or item
6397 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6398 (save-excursion
6399 (if (org-at-item-p)
6400 (progn
6401 (beginning-of-line)
6402 (setq struct (org-list-struct))
6403 (setq eoh (point-at-eol))
6404 (setq eos (org-list-get-item-end-before-blank (point) struct))
6405 (setq has-children (org-list-has-child-p (point) struct)))
6406 (org-back-to-heading)
6407 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6408 (setq eos (save-excursion
6409 (org-end-of-subtree t)
6410 (unless (eobp)
6411 (skip-chars-forward " \t\n"))
6412 (if (eobp) (point) (1- (point)))))
6413 (setq has-children
6414 (or (save-excursion
6415 (let ((level (funcall outline-level)))
6416 (outline-next-heading)
6417 (and (org-at-heading-p t)
6418 (> (funcall outline-level) level))))
6419 (save-excursion
6420 (org-list-search-forward (org-item-beginning-re) eos t)))))
6421 ;; Determine end invisible part of buffer (EOL)
6422 (beginning-of-line 2)
6423 ;; XEmacs doesn't have `next-single-char-property-change'
6424 (if (featurep 'xemacs)
6425 (while (and (not (eobp)) ;; this is like `next-line'
6426 (get-char-property (1- (point)) 'invisible))
6427 (beginning-of-line 2))
6428 (while (and (not (eobp)) ;; this is like `next-line'
6429 (get-char-property (1- (point)) 'invisible))
6430 (goto-char (next-single-char-property-change (point) 'invisible))
6431 (and (eolp) (beginning-of-line 2))))
6432 (setq eol (point)))
6433 ;; Find out what to do next and set `this-command'
6434 (cond
6435 ((= eos eoh)
6436 ;; Nothing is hidden behind this heading
6437 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6438 (message "EMPTY ENTRY")
6439 (setq org-cycle-subtree-status nil)
6440 (save-excursion
6441 (goto-char eos)
6442 (outline-next-heading)
6443 (if (outline-invisible-p) (org-flag-heading nil))))
6444 ((and (or (>= eol eos)
6445 (not (string-match "\\S-" (buffer-substring eol eos))))
6446 (or has-children
6447 (not (setq children-skipped
6448 org-cycle-skip-children-state-if-no-children))))
6449 ;; Entire subtree is hidden in one line: children view
6450 (run-hook-with-args 'org-pre-cycle-hook 'children)
6451 (if (org-at-item-p)
6452 (org-list-set-item-visibility (point-at-bol) struct 'children)
6453 (org-show-entry)
6454 (org-with-limited-levels (show-children))
6455 ;; FIXME: This slows down the func way too much.
6456 ;; How keep drawers hidden in subtree anyway?
6457 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6458 ;; (org-cycle-hide-drawers 'subtree))
6460 ;; Fold every list in subtree to top-level items.
6461 (when (eq org-cycle-include-plain-lists 'integrate)
6462 (save-excursion
6463 (org-back-to-heading)
6464 (while (org-list-search-forward (org-item-beginning-re) eos t)
6465 (beginning-of-line 1)
6466 (let* ((struct (org-list-struct))
6467 (prevs (org-list-prevs-alist struct))
6468 (end (org-list-get-bottom-point struct)))
6469 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6470 (org-list-get-all-items (point) struct prevs))
6471 (goto-char end))))))
6472 (message "CHILDREN")
6473 (save-excursion
6474 (goto-char eos)
6475 (outline-next-heading)
6476 (if (outline-invisible-p) (org-flag-heading nil)))
6477 (setq org-cycle-subtree-status 'children)
6478 (run-hook-with-args 'org-cycle-hook 'children))
6479 ((or children-skipped
6480 (and (eq last-command this-command)
6481 (eq org-cycle-subtree-status 'children)))
6482 ;; We just showed the children, or no children are there,
6483 ;; now show everything.
6484 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6485 (outline-flag-region eoh eos nil)
6486 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6487 (setq org-cycle-subtree-status 'subtree)
6488 (run-hook-with-args 'org-cycle-hook 'subtree))
6490 ;; Default action: hide the subtree.
6491 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6492 (outline-flag-region eoh eos t)
6493 (message "FOLDED")
6494 (setq org-cycle-subtree-status 'folded)
6495 (run-hook-with-args 'org-cycle-hook 'folded)))))
6497 ;;;###autoload
6498 (defun org-global-cycle (&optional arg)
6499 "Cycle the global visibility. For details see `org-cycle'.
6500 With \\[universal-argument] prefix arg, switch to startup visibility.
6501 With a numeric prefix, show all headlines up to that level."
6502 (interactive "P")
6503 (let ((org-cycle-include-plain-lists
6504 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6505 (cond
6506 ((integerp arg)
6507 (show-all)
6508 (hide-sublevels arg)
6509 (setq org-cycle-global-status 'contents))
6510 ((equal arg '(4))
6511 (org-set-startup-visibility)
6512 (message "Startup visibility, plus VISIBILITY properties."))
6514 (org-cycle '(4))))))
6516 (defun org-set-startup-visibility ()
6517 "Set the visibility required by startup options and properties."
6518 (cond
6519 ((eq org-startup-folded t)
6520 (org-cycle '(4)))
6521 ((eq org-startup-folded 'content)
6522 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6523 (org-cycle '(4)) (org-cycle '(4)))))
6524 (unless (eq org-startup-folded 'showeverything)
6525 (if org-hide-block-startup (org-hide-block-all))
6526 (org-set-visibility-according-to-property 'no-cleanup)
6527 (org-cycle-hide-archived-subtrees 'all)
6528 (org-cycle-hide-drawers 'all)
6529 (org-cycle-show-empty-lines t)))
6531 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6532 "Switch subtree visibilities according to :VISIBILITY: property."
6533 (interactive)
6534 (let (org-show-entry-below state)
6535 (save-excursion
6536 (goto-char (point-min))
6537 (while (re-search-forward
6538 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6539 nil t)
6540 (setq state (match-string 1))
6541 (save-excursion
6542 (org-back-to-heading t)
6543 (hide-subtree)
6544 (org-reveal)
6545 (cond
6546 ((equal state '("fold" "folded"))
6547 (hide-subtree))
6548 ((equal state "children")
6549 (org-show-hidden-entry)
6550 (show-children))
6551 ((equal state "content")
6552 (save-excursion
6553 (save-restriction
6554 (org-narrow-to-subtree)
6555 (org-content))))
6556 ((member state '("all" "showall"))
6557 (show-subtree)))))
6558 (unless no-cleanup
6559 (org-cycle-hide-archived-subtrees 'all)
6560 (org-cycle-hide-drawers 'all)
6561 (org-cycle-show-empty-lines 'all)))))
6563 ;; This function uses outline-regexp instead of the more fundamental
6564 ;; org-outline-regexp so that org-cycle-global works outside of Org
6565 ;; buffers, where outline-regexp is needed.
6566 (defun org-overview ()
6567 "Switch to overview mode, showing only top-level headlines.
6568 Really, this shows all headlines with level equal or greater than the level
6569 of the first headline in the buffer. This is important, because if the
6570 first headline is not level one, then (hide-sublevels 1) gives confusing
6571 results."
6572 (interactive)
6573 (let ((level (save-excursion
6574 (goto-char (point-min))
6575 (if (re-search-forward (concat "^" outline-regexp) nil t)
6576 (progn
6577 (goto-char (match-beginning 0))
6578 (funcall outline-level))))))
6579 (and level (hide-sublevels level))))
6581 (defun org-content (&optional arg)
6582 "Show all headlines in the buffer, like a table of contents.
6583 With numerical argument N, show content up to level N."
6584 (interactive "P")
6585 (save-excursion
6586 ;; Visit all headings and show their offspring
6587 (and (integerp arg) (org-overview))
6588 (goto-char (point-max))
6589 (catch 'exit
6590 (while (and (progn (condition-case nil
6591 (outline-previous-visible-heading 1)
6592 (error (goto-char (point-min))))
6594 (looking-at org-outline-regexp))
6595 (if (integerp arg)
6596 (show-children (1- arg))
6597 (show-branches))
6598 (if (bobp) (throw 'exit nil))))))
6601 (defun org-optimize-window-after-visibility-change (state)
6602 "Adjust the window after a change in outline visibility.
6603 This function is the default value of the hook `org-cycle-hook'."
6604 (when (get-buffer-window (current-buffer))
6605 (cond
6606 ((eq state 'content) nil)
6607 ((eq state 'all) nil)
6608 ((eq state 'folded) nil)
6609 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6610 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6612 (defun org-remove-empty-overlays-at (pos)
6613 "Remove outline overlays that do not contain non-white stuff."
6614 (mapc
6615 (lambda (o)
6616 (and (eq 'outline (overlay-get o 'invisible))
6617 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6618 (overlay-end o))))
6619 (delete-overlay o)))
6620 (overlays-at pos)))
6622 (defun org-clean-visibility-after-subtree-move ()
6623 "Fix visibility issues after moving a subtree."
6624 ;; First, find a reasonable region to look at:
6625 ;; Start two siblings above, end three below
6626 (let* ((beg (save-excursion
6627 (and (org-get-last-sibling)
6628 (org-get-last-sibling))
6629 (point)))
6630 (end (save-excursion
6631 (and (org-get-next-sibling)
6632 (org-get-next-sibling)
6633 (org-get-next-sibling))
6634 (if (org-at-heading-p)
6635 (point-at-eol)
6636 (point))))
6637 (level (looking-at "\\*+"))
6638 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6639 (save-excursion
6640 (save-restriction
6641 (narrow-to-region beg end)
6642 (when re
6643 ;; Properly fold already folded siblings
6644 (goto-char (point-min))
6645 (while (re-search-forward re nil t)
6646 (if (and (not (outline-invisible-p))
6647 (save-excursion
6648 (goto-char (point-at-eol)) (outline-invisible-p)))
6649 (hide-entry))))
6650 (org-cycle-show-empty-lines 'overview)
6651 (org-cycle-hide-drawers 'overview)))))
6653 (defun org-cycle-show-empty-lines (state)
6654 "Show empty lines above all visible headlines.
6655 The region to be covered depends on STATE when called through
6656 `org-cycle-hook'. Lisp program can use t for STATE to get the
6657 entire buffer covered. Note that an empty line is only shown if there
6658 are at least `org-cycle-separator-lines' empty lines before the headline."
6659 (when (not (= org-cycle-separator-lines 0))
6660 (save-excursion
6661 (let* ((n (abs org-cycle-separator-lines))
6662 (re (cond
6663 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6664 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6665 (t (let ((ns (number-to-string (- n 2))))
6666 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6667 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6668 beg end b e)
6669 (cond
6670 ((memq state '(overview contents t))
6671 (setq beg (point-min) end (point-max)))
6672 ((memq state '(children folded))
6673 (setq beg (point) end (progn (org-end-of-subtree t t)
6674 (beginning-of-line 2)
6675 (point)))))
6676 (when beg
6677 (goto-char beg)
6678 (while (re-search-forward re end t)
6679 (unless (get-char-property (match-end 1) 'invisible)
6680 (setq e (match-end 1))
6681 (if (< org-cycle-separator-lines 0)
6682 (setq b (save-excursion
6683 (goto-char (match-beginning 0))
6684 (org-back-over-empty-lines)
6685 (if (save-excursion
6686 (goto-char (max (point-min) (1- (point))))
6687 (org-at-heading-p))
6688 (1- (point))
6689 (point))))
6690 (setq b (match-beginning 1)))
6691 (outline-flag-region b e nil)))))))
6692 ;; Never hide empty lines at the end of the file.
6693 (save-excursion
6694 (goto-char (point-max))
6695 (outline-previous-heading)
6696 (outline-end-of-heading)
6697 (if (and (looking-at "[ \t\n]+")
6698 (= (match-end 0) (point-max)))
6699 (outline-flag-region (point) (match-end 0) nil))))
6701 (defun org-show-empty-lines-in-parent ()
6702 "Move to the parent and re-show empty lines before visible headlines."
6703 (save-excursion
6704 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6705 (org-cycle-show-empty-lines context))))
6707 (defun org-files-list ()
6708 "Return `org-agenda-files' list, plus all open org-mode files.
6709 This is useful for operations that need to scan all of a user's
6710 open and agenda-wise Org files."
6711 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6712 (dolist (buf (buffer-list))
6713 (with-current-buffer buf
6714 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6715 (let ((file (expand-file-name (buffer-file-name))))
6716 (unless (member file files)
6717 (push file files))))))
6718 files))
6720 (defsubst org-entry-beginning-position ()
6721 "Return the beginning position of the current entry."
6722 (save-excursion (outline-back-to-heading t) (point)))
6724 (defsubst org-entry-end-position ()
6725 "Return the end position of the current entry."
6726 (save-excursion (outline-next-heading) (point)))
6728 (defun org-cycle-hide-drawers (state)
6729 "Re-hide all drawers after a visibility state change."
6730 (when (and (derived-mode-p 'org-mode)
6731 (not (memq state '(overview folded contents))))
6732 (save-excursion
6733 (let* ((globalp (memq state '(contents all)))
6734 (beg (if globalp (point-min) (point)))
6735 (end (if globalp (point-max)
6736 (if (eq state 'children)
6737 (save-excursion (outline-next-heading) (point))
6738 (org-end-of-subtree t)))))
6739 (goto-char beg)
6740 (while (re-search-forward org-drawer-regexp end t)
6741 (org-flag-drawer t))))))
6743 (defun org-flag-drawer (flag)
6744 "When FLAG is non-nil, hide the drawer we are within.
6745 Otherwise make it visible."
6746 (save-excursion
6747 (beginning-of-line 1)
6748 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6749 (let ((b (match-end 0)))
6750 (if (re-search-forward
6751 "^[ \t]*:END:"
6752 (save-excursion (outline-next-heading) (point)) t)
6753 (outline-flag-region b (point-at-eol) flag)
6754 (error ":END: line missing at position %s" b))))))
6756 (defun org-subtree-end-visible-p ()
6757 "Is the end of the current subtree visible?"
6758 (pos-visible-in-window-p
6759 (save-excursion (org-end-of-subtree t) (point))))
6761 (defun org-first-headline-recenter (&optional N)
6762 "Move cursor to the first headline and recenter the headline.
6763 Optional argument N means put the headline into the Nth line of the window."
6764 (goto-char (point-min))
6765 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6766 (beginning-of-line)
6767 (recenter (prefix-numeric-value N))))
6769 ;;; Saving and restoring visibility
6771 (defun org-outline-overlay-data (&optional use-markers)
6772 "Return a list of the locations of all outline overlays.
6773 These are overlays with the `invisible' property value `outline'.
6774 The return value is a list of cons cells, with start and stop
6775 positions for each overlay.
6776 If USE-MARKERS is set, return the positions as markers."
6777 (let (beg end)
6778 (save-excursion
6779 (save-restriction
6780 (widen)
6781 (delq nil
6782 (mapcar (lambda (o)
6783 (when (eq (overlay-get o 'invisible) 'outline)
6784 (setq beg (overlay-start o)
6785 end (overlay-end o))
6786 (and beg end (> end beg)
6787 (if use-markers
6788 (cons (move-marker (make-marker) beg)
6789 (move-marker (make-marker) end))
6790 (cons beg end)))))
6791 (overlays-in (point-min) (point-max))))))))
6793 (defun org-set-outline-overlay-data (data)
6794 "Create visibility overlays for all positions in DATA.
6795 DATA should have been made by `org-outline-overlay-data'."
6796 (let (o)
6797 (save-excursion
6798 (save-restriction
6799 (widen)
6800 (show-all)
6801 (mapc (lambda (c)
6802 (outline-flag-region (car c) (cdr c) t))
6803 data)))))
6805 ;;; Folding of blocks
6807 (defvar org-hide-block-overlays nil
6808 "Overlays hiding blocks.")
6809 (make-variable-buffer-local 'org-hide-block-overlays)
6811 (defun org-block-map (function &optional start end)
6812 "Call FUNCTION at the head of all source blocks in the current buffer.
6813 Optional arguments START and END can be used to limit the range."
6814 (let ((start (or start (point-min)))
6815 (end (or end (point-max))))
6816 (save-excursion
6817 (goto-char start)
6818 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6819 (save-excursion
6820 (save-match-data
6821 (goto-char (match-beginning 0))
6822 (funcall function)))))))
6824 (defun org-hide-block-toggle-all ()
6825 "Toggle the visibility of all blocks in the current buffer."
6826 (org-block-map #'org-hide-block-toggle))
6828 (defun org-hide-block-all ()
6829 "Fold all blocks in the current buffer."
6830 (interactive)
6831 (org-show-block-all)
6832 (org-block-map #'org-hide-block-toggle-maybe))
6834 (defun org-show-block-all ()
6835 "Unfold all blocks in the current buffer."
6836 (interactive)
6837 (mapc 'delete-overlay org-hide-block-overlays)
6838 (setq org-hide-block-overlays nil))
6840 (defun org-hide-block-toggle-maybe ()
6841 "Toggle visibility of block at point."
6842 (interactive)
6843 (let ((case-fold-search t))
6844 (if (save-excursion
6845 (beginning-of-line 1)
6846 (looking-at org-block-regexp))
6847 (progn (org-hide-block-toggle)
6848 t) ;; to signal that we took action
6849 nil))) ;; to signal that we did not
6851 (defun org-hide-block-toggle (&optional force)
6852 "Toggle the visibility of the current block."
6853 (interactive)
6854 (save-excursion
6855 (beginning-of-line)
6856 (if (re-search-forward org-block-regexp nil t)
6857 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6858 (end (match-end 0)) ;; end of entire body
6860 (if (memq t (mapcar (lambda (overlay)
6861 (eq (overlay-get overlay 'invisible)
6862 'org-hide-block))
6863 (overlays-at start)))
6864 (if (or (not force) (eq force 'off))
6865 (mapc (lambda (ov)
6866 (when (member ov org-hide-block-overlays)
6867 (setq org-hide-block-overlays
6868 (delq ov org-hide-block-overlays)))
6869 (when (eq (overlay-get ov 'invisible)
6870 'org-hide-block)
6871 (delete-overlay ov)))
6872 (overlays-at start)))
6873 (setq ov (make-overlay start end))
6874 (overlay-put ov 'invisible 'org-hide-block)
6875 ;; make the block accessible to isearch
6876 (overlay-put
6877 ov 'isearch-open-invisible
6878 (lambda (ov)
6879 (when (member ov org-hide-block-overlays)
6880 (setq org-hide-block-overlays
6881 (delq ov org-hide-block-overlays)))
6882 (when (eq (overlay-get ov 'invisible)
6883 'org-hide-block)
6884 (delete-overlay ov))))
6885 (push ov org-hide-block-overlays)))
6886 (error "Not looking at a source block"))))
6888 ;; org-tab-after-check-for-cycling-hook
6889 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6890 ;; Remove overlays when changing major mode
6891 (add-hook 'org-mode-hook
6892 (lambda () (org-add-hook 'change-major-mode-hook
6893 'org-show-block-all 'append 'local)))
6895 ;;; Org-goto
6897 (defvar org-goto-window-configuration nil)
6898 (defvar org-goto-marker nil)
6899 (defvar org-goto-map
6900 (let ((map (make-sparse-keymap)))
6901 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6902 (while (setq cmd (pop cmds))
6903 (substitute-key-definition cmd cmd map global-map)))
6904 (suppress-keymap map)
6905 (org-defkey map "\C-m" 'org-goto-ret)
6906 (org-defkey map [(return)] 'org-goto-ret)
6907 (org-defkey map [(left)] 'org-goto-left)
6908 (org-defkey map [(right)] 'org-goto-right)
6909 (org-defkey map [(control ?g)] 'org-goto-quit)
6910 (org-defkey map "\C-i" 'org-cycle)
6911 (org-defkey map [(tab)] 'org-cycle)
6912 (org-defkey map [(down)] 'outline-next-visible-heading)
6913 (org-defkey map [(up)] 'outline-previous-visible-heading)
6914 (if org-goto-auto-isearch
6915 (if (fboundp 'define-key-after)
6916 (define-key-after map [t] 'org-goto-local-auto-isearch)
6917 nil)
6918 (org-defkey map "q" 'org-goto-quit)
6919 (org-defkey map "n" 'outline-next-visible-heading)
6920 (org-defkey map "p" 'outline-previous-visible-heading)
6921 (org-defkey map "f" 'outline-forward-same-level)
6922 (org-defkey map "b" 'outline-backward-same-level)
6923 (org-defkey map "u" 'outline-up-heading))
6924 (org-defkey map "/" 'org-occur)
6925 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6926 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6927 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6928 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6929 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6930 map))
6932 (defconst org-goto-help
6933 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6934 RET=jump to location [Q]uit and return to previous location
6935 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6937 (defvar org-goto-start-pos) ; dynamically scoped parameter
6939 ;; FIXME: Docstring does not mention both interfaces
6940 (defun org-goto (&optional alternative-interface)
6941 "Look up a different location in the current file, keeping current visibility.
6943 When you want look-up or go to a different location in a
6944 document, the fastest way is often to fold the entire buffer and
6945 then dive into the tree. This method has the disadvantage, that
6946 the previous location will be folded, which may not be what you
6947 want.
6949 This command works around this by showing a copy of the current
6950 buffer in an indirect buffer, in overview mode. You can dive
6951 into the tree in that copy, use org-occur and incremental search
6952 to find a location. When pressing RET or `Q', the command
6953 returns to the original buffer in which the visibility is still
6954 unchanged. After RET it will also jump to the location selected
6955 in the indirect buffer and expose the headline hierarchy above.
6957 With a prefix argument, use the alternative interface: e.g. if
6958 `org-goto-interface' is 'outline use 'outline-path-completion."
6959 (interactive "P")
6960 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6961 (org-refile-use-outline-path t)
6962 (org-refile-target-verify-function nil)
6963 (interface
6964 (if (not alternative-interface)
6965 org-goto-interface
6966 (if (eq org-goto-interface 'outline)
6967 'outline-path-completion
6968 'outline)))
6969 (org-goto-start-pos (point))
6970 (selected-point
6971 (if (eq interface 'outline)
6972 (car (org-get-location (current-buffer) org-goto-help))
6973 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6974 (org-refile-check-position pa)
6975 (nth 3 pa)))))
6976 (if selected-point
6977 (progn
6978 (org-mark-ring-push org-goto-start-pos)
6979 (goto-char selected-point)
6980 (if (or (outline-invisible-p) (org-invisible-p2))
6981 (org-show-context 'org-goto)))
6982 (message "Quit"))))
6984 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6985 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6986 (defvar org-goto-local-auto-isearch-map) ; defined below
6988 (defun org-get-location (buf help)
6989 "Let the user select a location in the Org-mode buffer BUF.
6990 This function uses a recursive edit. It returns the selected position
6991 or nil."
6992 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6993 (isearch-hide-immediately nil)
6994 (isearch-search-fun-function
6995 (lambda () 'org-goto-local-search-headings))
6996 (org-goto-selected-point org-goto-exit-command)
6997 (pop-up-frames nil)
6998 (special-display-buffer-names nil)
6999 (special-display-regexps nil)
7000 (special-display-function nil))
7001 (save-excursion
7002 (save-window-excursion
7003 (delete-other-windows)
7004 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7005 (org-pop-to-buffer-same-window
7006 (condition-case nil
7007 (make-indirect-buffer (current-buffer) "*org-goto*")
7008 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7009 (with-output-to-temp-buffer "*Help*"
7010 (princ help))
7011 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7012 (setq buffer-read-only nil)
7013 (let ((org-startup-truncated t)
7014 (org-startup-folded nil)
7015 (org-startup-align-all-tables nil))
7016 (org-mode)
7017 (org-overview))
7018 (setq buffer-read-only t)
7019 (if (and (boundp 'org-goto-start-pos)
7020 (integer-or-marker-p org-goto-start-pos))
7021 (let ((org-show-hierarchy-above t)
7022 (org-show-siblings t)
7023 (org-show-following-heading t))
7024 (goto-char org-goto-start-pos)
7025 (and (outline-invisible-p) (org-show-context)))
7026 (goto-char (point-min)))
7027 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7028 (message "Select location and press RET")
7029 (use-local-map org-goto-map)
7030 (recursive-edit)
7032 (kill-buffer "*org-goto*")
7033 (cons org-goto-selected-point org-goto-exit-command)))
7035 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7036 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7037 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7038 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7040 (defun org-goto-local-search-headings (string bound noerror)
7041 "Search and make sure that any matches are in headlines."
7042 (catch 'return
7043 (while (if isearch-forward
7044 (search-forward string bound noerror)
7045 (search-backward string bound noerror))
7046 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7047 (and (member :headline context)
7048 (not (member :tags context))))
7049 (throw 'return (point))))))
7051 (defun org-goto-local-auto-isearch ()
7052 "Start isearch."
7053 (interactive)
7054 (goto-char (point-min))
7055 (let ((keys (this-command-keys)))
7056 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7057 (isearch-mode t)
7058 (isearch-process-search-char (string-to-char keys)))))
7060 (defun org-goto-ret (&optional arg)
7061 "Finish `org-goto' by going to the new location."
7062 (interactive "P")
7063 (setq org-goto-selected-point (point)
7064 org-goto-exit-command 'return)
7065 (throw 'exit nil))
7067 (defun org-goto-left ()
7068 "Finish `org-goto' by going to the new location."
7069 (interactive)
7070 (if (org-at-heading-p)
7071 (progn
7072 (beginning-of-line 1)
7073 (setq org-goto-selected-point (point)
7074 org-goto-exit-command 'left)
7075 (throw 'exit nil))
7076 (error "Not on a heading")))
7078 (defun org-goto-right ()
7079 "Finish `org-goto' by going to the new location."
7080 (interactive)
7081 (if (org-at-heading-p)
7082 (progn
7083 (setq org-goto-selected-point (point)
7084 org-goto-exit-command 'right)
7085 (throw 'exit nil))
7086 (error "Not on a heading")))
7088 (defun org-goto-quit ()
7089 "Finish `org-goto' without cursor motion."
7090 (interactive)
7091 (setq org-goto-selected-point nil)
7092 (setq org-goto-exit-command 'quit)
7093 (throw 'exit nil))
7095 ;;; Indirect buffer display of subtrees
7097 (defvar org-indirect-dedicated-frame nil
7098 "This is the frame being used for indirect tree display.")
7099 (defvar org-last-indirect-buffer nil)
7101 (defun org-tree-to-indirect-buffer (&optional arg)
7102 "Create indirect buffer and narrow it to current subtree.
7103 With a numerical prefix ARG, go up to this level and then take that tree.
7104 If ARG is negative, go up that many levels.
7106 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7107 indirect buffer previously made with this command, to avoid proliferation of
7108 indirect buffers. However, when you call the command with a \
7109 \\[universal-argument] prefix, or
7110 when `org-indirect-buffer-display' is `new-frame', the last buffer
7111 is kept so that you can work with several indirect buffers at the same time.
7112 If `org-indirect-buffer-display' is `dedicated-frame', the \
7113 \\[universal-argument] prefix also
7114 requests that a new frame be made for the new buffer, so that the dedicated
7115 frame is not changed."
7116 (interactive "P")
7117 (let ((cbuf (current-buffer))
7118 (cwin (selected-window))
7119 (pos (point))
7120 beg end level heading ibuf)
7121 (save-excursion
7122 (org-back-to-heading t)
7123 (when (numberp arg)
7124 (setq level (org-outline-level))
7125 (if (< arg 0) (setq arg (+ level arg)))
7126 (while (> (setq level (org-outline-level)) arg)
7127 (org-up-heading-safe)))
7128 (setq beg (point)
7129 heading (org-get-heading))
7130 (org-end-of-subtree t t)
7131 (if (org-at-heading-p) (backward-char 1))
7132 (setq end (point)))
7133 (if (and (buffer-live-p org-last-indirect-buffer)
7134 (not (eq org-indirect-buffer-display 'new-frame))
7135 (not arg))
7136 (kill-buffer org-last-indirect-buffer))
7137 (setq ibuf (org-get-indirect-buffer cbuf)
7138 org-last-indirect-buffer ibuf)
7139 (cond
7140 ((or (eq org-indirect-buffer-display 'new-frame)
7141 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7142 (select-frame (make-frame))
7143 (delete-other-windows)
7144 (org-pop-to-buffer-same-window ibuf)
7145 (org-set-frame-title heading))
7146 ((eq org-indirect-buffer-display 'dedicated-frame)
7147 (raise-frame
7148 (select-frame (or (and org-indirect-dedicated-frame
7149 (frame-live-p org-indirect-dedicated-frame)
7150 org-indirect-dedicated-frame)
7151 (setq org-indirect-dedicated-frame (make-frame)))))
7152 (delete-other-windows)
7153 (org-pop-to-buffer-same-window ibuf)
7154 (org-set-frame-title (concat "Indirect: " heading)))
7155 ((eq org-indirect-buffer-display 'current-window)
7156 (org-pop-to-buffer-same-window ibuf))
7157 ((eq org-indirect-buffer-display 'other-window)
7158 (pop-to-buffer ibuf))
7159 (t (error "Invalid value")))
7160 (if (featurep 'xemacs)
7161 (save-excursion (org-mode) (turn-on-font-lock)))
7162 (narrow-to-region beg end)
7163 (show-all)
7164 (goto-char pos)
7165 (run-hook-with-args 'org-cycle-hook 'all)
7166 (and (window-live-p cwin) (select-window cwin))))
7168 (defun org-get-indirect-buffer (&optional buffer)
7169 (setq buffer (or buffer (current-buffer)))
7170 (let ((n 1) (base (buffer-name buffer)) bname)
7171 (while (buffer-live-p
7172 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7173 (setq n (1+ n)))
7174 (condition-case nil
7175 (make-indirect-buffer buffer bname 'clone)
7176 (error (make-indirect-buffer buffer bname)))))
7178 (defun org-set-frame-title (title)
7179 "Set the title of the current frame to the string TITLE."
7180 ;; FIXME: how to name a single frame in XEmacs???
7181 (unless (featurep 'xemacs)
7182 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7184 ;;;; Structure editing
7186 ;;; Inserting headlines
7188 (defun org-previous-line-empty-p ()
7189 (save-excursion
7190 (and (not (bobp))
7191 (or (beginning-of-line 0) t)
7192 (save-match-data
7193 (looking-at "[ \t]*$")))))
7195 (defun org-insert-heading (&optional force-heading invisible-ok)
7196 "Insert a new heading or item with same depth at point.
7197 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7198 If point is at the beginning of a headline, insert a sibling before the
7199 current headline. If point is not at the beginning, split the line,
7200 create the new headline with the text in the current line after point
7201 \(but see also the variable `org-M-RET-may-split-line').
7203 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7204 This is important for non-interactive uses of the command."
7205 (interactive "P")
7206 (if (or (= (buffer-size) 0)
7207 (and (not (save-excursion
7208 (and (ignore-errors (org-back-to-heading invisible-ok))
7209 (org-at-heading-p))))
7210 (or force-heading (not (org-in-item-p)))))
7211 (progn
7212 (insert "\n* ")
7213 (run-hooks 'org-insert-heading-hook))
7214 (when (or force-heading (not (org-insert-item)))
7215 (let* ((empty-line-p nil)
7216 (level nil)
7217 (on-heading (org-at-heading-p))
7218 (head (save-excursion
7219 (condition-case nil
7220 (progn
7221 (org-back-to-heading invisible-ok)
7222 (when (and (not on-heading)
7223 (featurep 'org-inlinetask)
7224 (integerp org-inlinetask-min-level)
7225 (>= (length (match-string 0))
7226 org-inlinetask-min-level))
7227 ;; Find a heading level before the inline task
7228 (while (and (setq level (org-up-heading-safe))
7229 (>= level org-inlinetask-min-level)))
7230 (if (org-at-heading-p)
7231 (org-back-to-heading invisible-ok)
7232 (error "This should not happen")))
7233 (setq empty-line-p (org-previous-line-empty-p))
7234 (match-string 0))
7235 (error "*"))))
7236 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7237 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7238 pos hide-previous previous-pos)
7239 (cond
7240 ((and (org-at-heading-p) (bolp)
7241 (or (bobp)
7242 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7243 ;; insert before the current line
7244 (open-line (if blank 2 1)))
7245 ((and (bolp)
7246 (not org-insert-heading-respect-content)
7247 (or (bobp)
7248 (save-excursion
7249 (backward-char 1) (not (outline-invisible-p)))))
7250 ;; insert right here
7251 nil)
7253 ;; somewhere in the line
7254 (save-excursion
7255 (setq previous-pos (point-at-bol))
7256 (end-of-line)
7257 (setq hide-previous (outline-invisible-p)))
7258 (and org-insert-heading-respect-content (org-show-subtree))
7259 (let ((split
7260 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7261 (save-excursion
7262 (let ((p (point)))
7263 (goto-char (point-at-bol))
7264 (and (looking-at org-complex-heading-regexp)
7265 (match-beginning 4)
7266 (> p (match-beginning 4)))))))
7267 tags pos)
7268 (cond
7269 (org-insert-heading-respect-content
7270 (org-end-of-subtree nil t)
7271 (when (featurep 'org-inlinetask)
7272 (while (and (not (eobp))
7273 (looking-at "\\(\\*+\\)[ \t]+")
7274 (>= (length (match-string 1))
7275 org-inlinetask-min-level))
7276 (org-end-of-subtree nil t)))
7277 (or (bolp) (newline))
7278 (or (org-previous-line-empty-p)
7279 (and blank (newline)))
7280 (open-line 1))
7281 ((org-at-heading-p)
7282 (when hide-previous
7283 (show-children)
7284 (org-show-entry))
7285 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7286 (setq tags (and (match-end 2) (match-string 2)))
7287 (and (match-end 1)
7288 (delete-region (match-beginning 1) (match-end 1)))
7289 (setq pos (point-at-bol))
7290 (or split (end-of-line 1))
7291 (delete-horizontal-space)
7292 (if (string-match "\\`\\*+\\'"
7293 (buffer-substring (point-at-bol) (point)))
7294 (insert " "))
7295 (newline (if blank 2 1))
7296 (when tags
7297 (save-excursion
7298 (goto-char pos)
7299 (end-of-line 1)
7300 (insert " " tags)
7301 (org-set-tags nil 'align))))
7303 (or split (end-of-line 1))
7304 (newline (if blank 2 1)))))))
7305 (insert head) (just-one-space)
7306 (setq pos (point))
7307 (end-of-line 1)
7308 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7309 (when (and org-insert-heading-respect-content hide-previous)
7310 (save-excursion
7311 (goto-char previous-pos)
7312 (hide-subtree)))
7313 (run-hooks 'org-insert-heading-hook)))))
7315 (defun org-get-heading (&optional no-tags no-todo)
7316 "Return the heading of the current entry, without the stars.
7317 When NO-TAGS is non-nil, don't include tags.
7318 When NO-TODO is non-nil, don't include TODO keywords."
7319 (save-excursion
7320 (org-back-to-heading t)
7321 (cond
7322 ((and no-tags no-todo)
7323 (looking-at org-complex-heading-regexp)
7324 (match-string 4))
7325 (no-tags
7326 (looking-at (concat org-outline-regexp
7327 "\\(.*?\\)"
7328 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7329 (match-string 1))
7330 (no-todo
7331 (looking-at org-todo-line-regexp)
7332 (match-string 3))
7333 (t (looking-at org-heading-regexp)
7334 (match-string 2)))))
7336 (defun org-heading-components ()
7337 "Return the components of the current heading.
7338 This is a list with the following elements:
7339 - the level as an integer
7340 - the reduced level, different if `org-odd-levels-only' is set.
7341 - the TODO keyword, or nil
7342 - the priority character, like ?A, or nil if no priority is given
7343 - the headline text itself, or the tags string if no headline text
7344 - the tags string, or nil."
7345 (save-excursion
7346 (org-back-to-heading t)
7347 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7348 (list (length (match-string 1))
7349 (org-reduced-level (length (match-string 1)))
7350 (org-match-string-no-properties 2)
7351 (and (match-end 3) (aref (match-string 3) 2))
7352 (org-match-string-no-properties 4)
7353 (org-match-string-no-properties 5)))))
7355 (defun org-get-entry ()
7356 "Get the entry text, after heading, entire subtree."
7357 (save-excursion
7358 (org-back-to-heading t)
7359 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7361 (defun org-insert-heading-after-current ()
7362 "Insert a new heading with same level as current, after current subtree."
7363 (interactive)
7364 (org-back-to-heading)
7365 (org-insert-heading)
7366 (org-move-subtree-down)
7367 (end-of-line 1))
7369 (defun org-insert-heading-respect-content ()
7370 (interactive)
7371 (let ((org-insert-heading-respect-content t))
7372 (org-insert-heading t)))
7374 (defun org-insert-todo-heading-respect-content (&optional force-state)
7375 (interactive "P")
7376 (let ((org-insert-heading-respect-content t))
7377 (org-insert-todo-heading force-state t)))
7379 (defun org-insert-todo-heading (arg &optional force-heading)
7380 "Insert a new heading with the same level and TODO state as current heading.
7381 If the heading has no TODO state, or if the state is DONE, use the first
7382 state (TODO by default). Also with prefix arg, force first state."
7383 (interactive "P")
7384 (when (or force-heading (not (org-insert-item 'checkbox)))
7385 (org-insert-heading force-heading)
7386 (save-excursion
7387 (org-back-to-heading)
7388 (outline-previous-heading)
7389 (looking-at org-todo-line-regexp))
7390 (let*
7391 ((new-mark-x
7392 (if (or arg
7393 (not (match-beginning 2))
7394 (member (match-string 2) org-done-keywords))
7395 (car org-todo-keywords-1)
7396 (match-string 2)))
7397 (new-mark
7399 (run-hook-with-args-until-success
7400 'org-todo-get-default-hook new-mark-x nil)
7401 new-mark-x)))
7402 (beginning-of-line 1)
7403 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7404 (if org-treat-insert-todo-heading-as-state-change
7405 (org-todo new-mark)
7406 (insert new-mark " "))))
7407 (when org-provide-todo-statistics
7408 (org-update-parent-todo-statistics))))
7410 (defun org-insert-subheading (arg)
7411 "Insert a new subheading and demote it.
7412 Works for outline headings and for plain lists alike."
7413 (interactive "P")
7414 (org-insert-heading arg)
7415 (cond
7416 ((org-at-heading-p) (org-do-demote))
7417 ((org-at-item-p) (org-indent-item))))
7419 (defun org-insert-todo-subheading (arg)
7420 "Insert a new subheading with TODO keyword or checkbox and demote it.
7421 Works for outline headings and for plain lists alike."
7422 (interactive "P")
7423 (org-insert-todo-heading arg)
7424 (cond
7425 ((org-at-heading-p) (org-do-demote))
7426 ((org-at-item-p) (org-indent-item))))
7428 ;;; Promotion and Demotion
7430 (defvar org-after-demote-entry-hook nil
7431 "Hook run after an entry has been demoted.
7432 The cursor will be at the beginning of the entry.
7433 When a subtree is being demoted, the hook will be called for each node.")
7435 (defvar org-after-promote-entry-hook nil
7436 "Hook run after an entry has been promoted.
7437 The cursor will be at the beginning of the entry.
7438 When a subtree is being promoted, the hook will be called for each node.")
7440 (defun org-promote-subtree ()
7441 "Promote the entire subtree.
7442 See also `org-promote'."
7443 (interactive)
7444 (save-excursion
7445 (org-with-limited-levels (org-map-tree 'org-promote)))
7446 (org-fix-position-after-promote))
7448 (defun org-demote-subtree ()
7449 "Demote the entire subtree. See `org-demote'.
7450 See also `org-promote'."
7451 (interactive)
7452 (save-excursion
7453 (org-with-limited-levels (org-map-tree 'org-demote)))
7454 (org-fix-position-after-promote))
7457 (defun org-do-promote ()
7458 "Promote the current heading higher up the tree.
7459 If the region is active in `transient-mark-mode', promote all headings
7460 in the region."
7461 (interactive)
7462 (save-excursion
7463 (if (org-region-active-p)
7464 (org-map-region 'org-promote (region-beginning) (region-end))
7465 (org-promote)))
7466 (org-fix-position-after-promote))
7468 (defun org-do-demote ()
7469 "Demote the current heading lower down the tree.
7470 If the region is active in `transient-mark-mode', demote all headings
7471 in the region."
7472 (interactive)
7473 (save-excursion
7474 (if (org-region-active-p)
7475 (org-map-region 'org-demote (region-beginning) (region-end))
7476 (org-demote)))
7477 (org-fix-position-after-promote))
7479 (defun org-fix-position-after-promote ()
7480 "Make sure that after pro/demotion cursor position is right."
7481 (let ((pos (point)))
7482 (when (save-excursion
7483 (beginning-of-line 1)
7484 (looking-at org-todo-line-regexp)
7485 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7486 (cond ((eobp) (insert " "))
7487 ((eolp) (insert " "))
7488 ((equal (char-after) ?\ ) (forward-char 1))))))
7490 (defun org-current-level ()
7491 "Return the level of the current entry, or nil if before the first headline.
7492 The level is the number of stars at the beginning of the headline."
7493 (save-excursion
7494 (org-with-limited-levels
7495 (if (ignore-errors (org-back-to-heading t))
7496 (funcall outline-level)))))
7498 (defun org-get-previous-line-level ()
7499 "Return the outline depth of the last headline before the current line.
7500 Returns 0 for the first headline in the buffer, and nil if before the
7501 first headline."
7502 (let ((current-level (org-current-level))
7503 (prev-level (when (> (line-number-at-pos) 1)
7504 (save-excursion
7505 (beginning-of-line 0)
7506 (org-current-level)))))
7507 (cond ((null current-level) nil) ; Before first headline
7508 ((null prev-level) 0) ; At first headline
7509 (prev-level))))
7511 (defun org-reduced-level (l)
7512 "Compute the effective level of a heading.
7513 This takes into account the setting of `org-odd-levels-only'."
7514 (cond
7515 ((zerop l) 0)
7516 (org-odd-levels-only (1+ (floor (/ l 2))))
7517 (t l)))
7519 (defun org-level-increment ()
7520 "Return the number of stars that will be added or removed at a
7521 time to headlines when structure editing, based on the value of
7522 `org-odd-levels-only'."
7523 (if org-odd-levels-only 2 1))
7525 (defun org-get-valid-level (level &optional change)
7526 "Rectify a level change under the influence of `org-odd-levels-only'
7527 LEVEL is a current level, CHANGE is by how much the level should be
7528 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7529 even level numbers will become the next higher odd number."
7530 (if org-odd-levels-only
7531 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7532 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7533 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7534 (max 1 (+ level (or change 0)))))
7536 (if (boundp 'define-obsolete-function-alias)
7537 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7538 (define-obsolete-function-alias 'org-get-legal-level
7539 'org-get-valid-level)
7540 (define-obsolete-function-alias 'org-get-legal-level
7541 'org-get-valid-level "23.1")))
7543 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7544 ;; ̀org-with-limited-levels'
7545 (defun org-promote ()
7546 "Promote the current heading higher up the tree.
7547 If the region is active in `transient-mark-mode', promote all headings
7548 in the region."
7549 (org-back-to-heading t)
7550 (let* ((level (save-match-data (funcall outline-level)))
7551 (after-change-functions (remove 'flyspell-after-change-function
7552 after-change-functions))
7553 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7554 (diff (abs (- level (length up-head) -1))))
7555 (cond ((and (= level 1) org-called-with-limited-levels
7556 org-allow-promoting-top-level-subtree)
7557 (replace-match "# " nil t))
7558 ((= level 1)
7559 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7560 (t (replace-match up-head nil t)))
7561 ;; Fixup tag positioning
7562 (unless (= level 1)
7563 (and org-auto-align-tags (org-set-tags nil t))
7564 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7565 (run-hooks 'org-after-promote-entry-hook)))
7567 (defun org-demote ()
7568 "Demote the current heading lower down the tree.
7569 If the region is active in `transient-mark-mode', demote all headings
7570 in the region."
7571 (org-back-to-heading t)
7572 (let* ((level (save-match-data (funcall outline-level)))
7573 (after-change-functions (remove 'flyspell-after-change-function
7574 after-change-functions))
7575 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7576 (diff (abs (- level (length down-head) -1))))
7577 (replace-match down-head nil t)
7578 ;; Fixup tag positioning
7579 (and org-auto-align-tags (org-set-tags nil t))
7580 (if org-adapt-indentation (org-fixup-indentation diff))
7581 (run-hooks 'org-after-demote-entry-hook)))
7583 (defun org-cycle-level ()
7584 "Cycle the level of an empty headline through possible states.
7585 This goes first to child, then to parent, level, then up the hierarchy.
7586 After top level, it switches back to sibling level."
7587 (interactive)
7588 (let ((org-adapt-indentation nil))
7589 (when (org-point-at-end-of-empty-headline)
7590 (setq this-command 'org-cycle-level) ; Only needed for caching
7591 (let ((cur-level (org-current-level))
7592 (prev-level (org-get-previous-line-level)))
7593 (cond
7594 ;; If first headline in file, promote to top-level.
7595 ((= prev-level 0)
7596 (loop repeat (/ (- cur-level 1) (org-level-increment))
7597 do (org-do-promote)))
7598 ;; If same level as prev, demote one.
7599 ((= prev-level cur-level)
7600 (org-do-demote))
7601 ;; If parent is top-level, promote to top level if not already.
7602 ((= prev-level 1)
7603 (loop repeat (/ (- cur-level 1) (org-level-increment))
7604 do (org-do-promote)))
7605 ;; If top-level, return to prev-level.
7606 ((= cur-level 1)
7607 (loop repeat (/ (- prev-level 1) (org-level-increment))
7608 do (org-do-demote)))
7609 ;; If less than prev-level, promote one.
7610 ((< cur-level prev-level)
7611 (org-do-promote))
7612 ;; If deeper than prev-level, promote until higher than
7613 ;; prev-level.
7614 ((> cur-level prev-level)
7615 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7616 do (org-do-promote))))
7617 t))))
7619 (defun org-map-tree (fun)
7620 "Call FUN for every heading underneath the current one."
7621 (org-back-to-heading)
7622 (let ((level (funcall outline-level)))
7623 (save-excursion
7624 (funcall fun)
7625 (while (and (progn
7626 (outline-next-heading)
7627 (> (funcall outline-level) level))
7628 (not (eobp)))
7629 (funcall fun)))))
7631 (defun org-map-region (fun beg end)
7632 "Call FUN for every heading between BEG and END."
7633 (let ((org-ignore-region t))
7634 (save-excursion
7635 (setq end (copy-marker end))
7636 (goto-char beg)
7637 (if (and (re-search-forward org-outline-regexp-bol nil t)
7638 (< (point) end))
7639 (funcall fun))
7640 (while (and (progn
7641 (outline-next-heading)
7642 (< (point) end))
7643 (not (eobp)))
7644 (funcall fun)))))
7646 (defvar org-property-end-re) ; silence byte-compiler
7647 (defun org-fixup-indentation (diff)
7648 "Change the indentation in the current entry by DIFF.
7649 However, if any line in the current entry has no indentation, or if it
7650 would end up with no indentation after the change, nothing at all is done."
7651 (save-excursion
7652 (let ((end (save-excursion (outline-next-heading)
7653 (point-marker)))
7654 (prohibit (if (> diff 0)
7655 "^\\S-"
7656 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7657 col)
7658 (unless (save-excursion (end-of-line 1)
7659 (re-search-forward prohibit end t))
7660 (while (and (< (point) end)
7661 (re-search-forward "^[ \t]+" end t))
7662 (goto-char (match-end 0))
7663 (setq col (current-column))
7664 (if (< diff 0) (replace-match ""))
7665 (org-indent-to-column (+ diff col))))
7666 (move-marker end nil))))
7668 (defun org-convert-to-odd-levels ()
7669 "Convert an org-mode file with all levels allowed to one with odd levels.
7670 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7671 level 5 etc."
7672 (interactive)
7673 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7674 (let ((outline-level 'org-outline-level)
7675 (org-odd-levels-only nil) n)
7676 (save-excursion
7677 (goto-char (point-min))
7678 (while (re-search-forward "^\\*\\*+ " nil t)
7679 (setq n (- (length (match-string 0)) 2))
7680 (while (>= (setq n (1- n)) 0)
7681 (org-demote))
7682 (end-of-line 1))))))
7684 (defun org-convert-to-oddeven-levels ()
7685 "Convert an org-mode file with only odd levels to one with odd/even levels.
7686 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7687 file contains a section with an even level, conversion would
7688 destroy the structure of the file. An error is signaled in this
7689 case."
7690 (interactive)
7691 (goto-char (point-min))
7692 ;; First check if there are no even levels
7693 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7694 (org-show-context t)
7695 (error "Not all levels are odd in this file. Conversion not possible"))
7696 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7697 (let ((outline-regexp org-outline-regexp)
7698 (outline-level 'org-outline-level)
7699 (org-odd-levels-only nil) n)
7700 (save-excursion
7701 (goto-char (point-min))
7702 (while (re-search-forward "^\\*\\*+ " nil t)
7703 (setq n (/ (1- (length (match-string 0))) 2))
7704 (while (>= (setq n (1- n)) 0)
7705 (org-promote))
7706 (end-of-line 1))))))
7708 (defun org-tr-level (n)
7709 "Make N odd if required."
7710 (if org-odd-levels-only (1+ (/ n 2)) n))
7712 ;;; Vertical tree motion, cutting and pasting of subtrees
7714 (defun org-move-subtree-up (&optional arg)
7715 "Move the current subtree up past ARG headlines of the same level."
7716 (interactive "p")
7717 (org-move-subtree-down (- (prefix-numeric-value arg))))
7719 (defun org-move-subtree-down (&optional arg)
7720 "Move the current subtree down past ARG headlines of the same level."
7721 (interactive "p")
7722 (setq arg (prefix-numeric-value arg))
7723 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7724 'org-get-last-sibling))
7725 (ins-point (make-marker))
7726 (cnt (abs arg))
7727 (col (current-column))
7728 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7729 ;; Select the tree
7730 (org-back-to-heading)
7731 (setq beg0 (point))
7732 (save-excursion
7733 (setq ne-beg (org-back-over-empty-lines))
7734 (setq beg (point)))
7735 (save-match-data
7736 (save-excursion (outline-end-of-heading)
7737 (setq folded (outline-invisible-p)))
7738 (outline-end-of-subtree))
7739 (outline-next-heading)
7740 (setq ne-end (org-back-over-empty-lines))
7741 (setq end (point))
7742 (goto-char beg0)
7743 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7744 ;; include less whitespace
7745 (save-excursion
7746 (goto-char beg)
7747 (forward-line (- ne-beg ne-end))
7748 (setq beg (point))))
7749 ;; Find insertion point, with error handling
7750 (while (> cnt 0)
7751 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7752 (progn (goto-char beg0)
7753 (error "Cannot move past superior level or buffer limit")))
7754 (setq cnt (1- cnt)))
7755 (if (> arg 0)
7756 ;; Moving forward - still need to move over subtree
7757 (progn (org-end-of-subtree t t)
7758 (save-excursion
7759 (org-back-over-empty-lines)
7760 (or (bolp) (newline)))))
7761 (setq ne-ins (org-back-over-empty-lines))
7762 (move-marker ins-point (point))
7763 (setq txt (buffer-substring beg end))
7764 (org-save-markers-in-region beg end)
7765 (delete-region beg end)
7766 (org-remove-empty-overlays-at beg)
7767 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7768 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7769 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7770 (let ((bbb (point)))
7771 (insert-before-markers txt)
7772 (org-reinstall-markers-in-region bbb)
7773 (move-marker ins-point bbb))
7774 (or (bolp) (insert "\n"))
7775 (setq ins-end (point))
7776 (goto-char ins-point)
7777 (org-skip-whitespace)
7778 (when (and (< arg 0)
7779 (org-first-sibling-p)
7780 (> ne-ins ne-beg))
7781 ;; Move whitespace back to beginning
7782 (save-excursion
7783 (goto-char ins-end)
7784 (let ((kill-whole-line t))
7785 (kill-line (- ne-ins ne-beg)) (point)))
7786 (insert (make-string (- ne-ins ne-beg) ?\n)))
7787 (move-marker ins-point nil)
7788 (if folded
7789 (hide-subtree)
7790 (org-show-entry)
7791 (show-children)
7792 (org-cycle-hide-drawers 'children))
7793 (org-clean-visibility-after-subtree-move)
7794 ;; move back to the initial column we were at
7795 (move-to-column col)))
7797 (defvar org-subtree-clip ""
7798 "Clipboard for cut and paste of subtrees.
7799 This is actually only a copy of the kill, because we use the normal kill
7800 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7802 (defvar org-subtree-clip-folded nil
7803 "Was the last copied subtree folded?
7804 This is used to fold the tree back after pasting.")
7806 (defun org-cut-subtree (&optional n)
7807 "Cut the current subtree into the clipboard.
7808 With prefix arg N, cut this many sequential subtrees.
7809 This is a short-hand for marking the subtree and then cutting it."
7810 (interactive "p")
7811 (org-copy-subtree n 'cut))
7813 (defun org-copy-subtree (&optional n cut force-store-markers)
7814 "Cut the current subtree into the clipboard.
7815 With prefix arg N, cut this many sequential subtrees.
7816 This is a short-hand for marking the subtree and then copying it.
7817 If CUT is non-nil, actually cut the subtree.
7818 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7819 of some markers in the region, even if CUT is non-nil. This is
7820 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7821 (interactive "p")
7822 (let (beg end folded (beg0 (point)))
7823 (if (org-called-interactively-p 'any)
7824 (org-back-to-heading nil) ; take what looks like a subtree
7825 (org-back-to-heading t)) ; take what is really there
7826 (org-back-over-empty-lines)
7827 (setq beg (point))
7828 (skip-chars-forward " \t\r\n")
7829 (save-match-data
7830 (save-excursion (outline-end-of-heading)
7831 (setq folded (outline-invisible-p)))
7832 (condition-case nil
7833 (org-forward-heading-same-level (1- n) t)
7834 (error nil))
7835 (org-end-of-subtree t t))
7836 (org-back-over-empty-lines)
7837 (setq end (point))
7838 (goto-char beg0)
7839 (when (> end beg)
7840 (setq org-subtree-clip-folded folded)
7841 (when (or cut force-store-markers)
7842 (org-save-markers-in-region beg end))
7843 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7844 (setq org-subtree-clip (current-kill 0))
7845 (message "%s: Subtree(s) with %d characters"
7846 (if cut "Cut" "Copied")
7847 (length org-subtree-clip)))))
7849 (defun org-paste-subtree (&optional level tree for-yank)
7850 "Paste the clipboard as a subtree, with modification of headline level.
7851 The entire subtree is promoted or demoted in order to match a new headline
7852 level.
7854 If the cursor is at the beginning of a headline, the same level as
7855 that headline is used to paste the tree
7857 If not, the new level is derived from the *visible* headings
7858 before and after the insertion point, and taken to be the inferior headline
7859 level of the two. So if the previous visible heading is level 3 and the
7860 next is level 4 (or vice versa), level 4 will be used for insertion.
7861 This makes sure that the subtree remains an independent subtree and does
7862 not swallow low level entries.
7864 You can also force a different level, either by using a numeric prefix
7865 argument, or by inserting the heading marker by hand. For example, if the
7866 cursor is after \"*****\", then the tree will be shifted to level 5.
7868 If optional TREE is given, use this text instead of the kill ring.
7870 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7871 move back over whitespace before inserting, and move point to the end of
7872 the inserted text when done."
7873 (interactive "P")
7874 (setq tree (or tree (and kill-ring (current-kill 0))))
7875 (unless (org-kill-is-subtree-p tree)
7876 (error "%s"
7877 (substitute-command-keys
7878 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7879 (org-with-limited-levels
7880 (let* ((visp (not (outline-invisible-p)))
7881 (txt tree)
7882 (^re_ "\\(\\*+\\)[ \t]*")
7883 (old-level (if (string-match org-outline-regexp-bol txt)
7884 (- (match-end 0) (match-beginning 0) 1)
7885 -1))
7886 (force-level (cond (level (prefix-numeric-value level))
7887 ((and (looking-at "[ \t]*$")
7888 (string-match
7889 "^\\*+$" (buffer-substring
7890 (point-at-bol) (point))))
7891 (- (match-end 1) (match-beginning 1)))
7892 ((and (bolp)
7893 (looking-at org-outline-regexp))
7894 (- (match-end 0) (point) 1))))
7895 (previous-level (save-excursion
7896 (condition-case nil
7897 (progn
7898 (outline-previous-visible-heading 1)
7899 (if (looking-at ^re_)
7900 (- (match-end 0) (match-beginning 0) 1)
7902 (error 1))))
7903 (next-level (save-excursion
7904 (condition-case nil
7905 (progn
7906 (or (looking-at org-outline-regexp)
7907 (outline-next-visible-heading 1))
7908 (if (looking-at ^re_)
7909 (- (match-end 0) (match-beginning 0) 1)
7911 (error 1))))
7912 (new-level (or force-level (max previous-level next-level)))
7913 (shift (if (or (= old-level -1)
7914 (= new-level -1)
7915 (= old-level new-level))
7917 (- new-level old-level)))
7918 (delta (if (> shift 0) -1 1))
7919 (func (if (> shift 0) 'org-demote 'org-promote))
7920 (org-odd-levels-only nil)
7921 beg end newend)
7922 ;; Remove the forced level indicator
7923 (if force-level
7924 (delete-region (point-at-bol) (point)))
7925 ;; Paste
7926 (beginning-of-line (if (bolp) 1 2))
7927 (unless for-yank (org-back-over-empty-lines))
7928 (setq beg (point))
7929 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7930 (insert-before-markers txt)
7931 (unless (string-match "\n\\'" txt) (insert "\n"))
7932 (setq newend (point))
7933 (org-reinstall-markers-in-region beg)
7934 (setq end (point))
7935 (goto-char beg)
7936 (skip-chars-forward " \t\n\r")
7937 (setq beg (point))
7938 (if (and (outline-invisible-p) visp)
7939 (save-excursion (outline-show-heading)))
7940 ;; Shift if necessary
7941 (unless (= shift 0)
7942 (save-restriction
7943 (narrow-to-region beg end)
7944 (while (not (= shift 0))
7945 (org-map-region func (point-min) (point-max))
7946 (setq shift (+ delta shift)))
7947 (goto-char (point-min))
7948 (setq newend (point-max))))
7949 (when (or (org-called-interactively-p 'interactive) for-yank)
7950 (message "Clipboard pasted as level %d subtree" new-level))
7951 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7952 kill-ring
7953 (eq org-subtree-clip (current-kill 0))
7954 org-subtree-clip-folded)
7955 ;; The tree was folded before it was killed/copied
7956 (hide-subtree))
7957 (and for-yank (goto-char newend)))))
7959 (defun org-kill-is-subtree-p (&optional txt)
7960 "Check if the current kill is an outline subtree, or a set of trees.
7961 Returns nil if kill does not start with a headline, or if the first
7962 headline level is not the largest headline level in the tree.
7963 So this will actually accept several entries of equal levels as well,
7964 which is OK for `org-paste-subtree'.
7965 If optional TXT is given, check this string instead of the current kill."
7966 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7967 (re (org-get-limited-outline-regexp))
7968 (^re (concat "^" re))
7969 (start-level (and kill
7970 (string-match
7971 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7972 kill)
7973 (- (match-end 2) (match-beginning 2) 1)))
7974 (start (1+ (or (match-beginning 2) -1))))
7975 (if (not start-level)
7976 (progn
7977 nil) ;; does not even start with a heading
7978 (catch 'exit
7979 (while (setq start (string-match ^re kill (1+ start)))
7980 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7981 (throw 'exit nil)))
7982 t))))
7984 (defvar org-markers-to-move nil
7985 "Markers that should be moved with a cut-and-paste operation.
7986 Those markers are stored together with their positions relative to
7987 the start of the region.")
7989 (defun org-save-markers-in-region (beg end)
7990 "Check markers in region.
7991 If these markers are between BEG and END, record their position relative
7992 to BEG, so that after moving the block of text, we can put the markers back
7993 into place.
7994 This function gets called just before an entry or tree gets cut from the
7995 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7996 called immediately, to move the markers with the entries."
7997 (setq org-markers-to-move nil)
7998 (when (featurep 'org-clock)
7999 (org-clock-save-markers-for-cut-and-paste beg end))
8000 (when (featurep 'org-agenda)
8001 (org-agenda-save-markers-for-cut-and-paste beg end)))
8003 (defun org-check-and-save-marker (marker beg end)
8004 "Check if MARKER is between BEG and END.
8005 If yes, remember the marker and the distance to BEG."
8006 (when (and (marker-buffer marker)
8007 (equal (marker-buffer marker) (current-buffer)))
8008 (if (and (>= marker beg) (< marker end))
8009 (push (cons marker (- marker beg)) org-markers-to-move))))
8011 (defun org-reinstall-markers-in-region (beg)
8012 "Move all remembered markers to their position relative to BEG."
8013 (mapc (lambda (x)
8014 (move-marker (car x) (+ beg (cdr x))))
8015 org-markers-to-move)
8016 (setq org-markers-to-move nil))
8018 (defun org-narrow-to-subtree ()
8019 "Narrow buffer to the current subtree."
8020 (interactive)
8021 (save-excursion
8022 (save-match-data
8023 (org-with-limited-levels
8024 (narrow-to-region
8025 (progn (org-back-to-heading t) (point))
8026 (progn (org-end-of-subtree t t)
8027 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8028 (point)))))))
8030 (defun org-narrow-to-block ()
8031 "Narrow buffer to the current block."
8032 (interactive)
8033 (let* ((case-fold-search t)
8034 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8035 "^[ \t]*#\\+end_.*")))
8036 (if blockp
8037 (narrow-to-region (car blockp) (cdr blockp))
8038 (error "Not in a block"))))
8040 (eval-when-compile
8041 (defvar org-property-drawer-re))
8043 (defvar org-property-start-re) ;; defined below
8044 (defun org-clone-subtree-with-time-shift (n &optional shift)
8045 "Clone the task (subtree) at point N times.
8046 The clones will be inserted as siblings.
8048 In interactive use, the user will be prompted for the number of
8049 clones to be produced, and for a time SHIFT, which may be a
8050 repeater as used in time stamps, for example `+3d'.
8052 When a valid repeater is given and the entry contains any time
8053 stamps, the clones will become a sequence in time, with time
8054 stamps in the subtree shifted for each clone produced. If SHIFT
8055 is nil or the empty string, time stamps will be left alone. The
8056 ID property of the original subtree is removed.
8058 If the original subtree did contain time stamps with a repeater,
8059 the following will happen:
8060 - the repeater will be removed in each clone
8061 - an additional clone will be produced, with the current, unshifted
8062 date(s) in the entry.
8063 - the original entry will be placed *after* all the clones, with
8064 repeater intact.
8065 - the start days in the repeater in the original entry will be shifted
8066 to past the last clone.
8067 In this way you can spell out a number of instances of a repeating task,
8068 and still retain the repeater to cover future instances of the task."
8069 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8070 (let (beg end template task idprop
8071 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8072 (drawer-re org-drawer-regexp))
8073 (if (not (and (integerp n) (> n 0)))
8074 (error "Invalid number of replications %s" n))
8075 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8076 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8077 shift)))
8078 (error "Invalid shift specification %s" shift))
8079 (when doshift
8080 (setq shift-n (string-to-number (match-string 1 shift))
8081 shift-what (cdr (assoc (match-string 2 shift)
8082 '(("d" . day) ("w" . week)
8083 ("m" . month) ("y" . year))))))
8084 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8085 (setq nmin 1 nmax n)
8086 (org-back-to-heading t)
8087 (setq beg (point))
8088 (setq idprop (org-entry-get nil "ID"))
8089 (org-end-of-subtree t t)
8090 (or (bolp) (insert "\n"))
8091 (setq end (point))
8092 (setq template (buffer-substring beg end))
8093 (when (and doshift
8094 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8095 (delete-region beg end)
8096 (setq end beg)
8097 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8098 (goto-char end)
8099 (loop for n from nmin to nmax do
8100 ;; prepare clone
8101 (with-temp-buffer
8102 (insert template)
8103 (org-mode)
8104 (goto-char (point-min))
8105 (org-show-subtree)
8106 (and idprop (if org-clone-delete-id
8107 (org-entry-delete nil "ID")
8108 (org-id-get-create t)))
8109 (unless (= n 0)
8110 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8111 (kill-whole-line))
8112 (goto-char (point-min))
8113 (while (re-search-forward drawer-re nil t)
8114 (mapc (lambda (d)
8115 (org-remove-empty-drawer-at d (point))) org-drawers)))
8116 (goto-char (point-min))
8117 (when doshift
8118 (while (re-search-forward org-ts-regexp-both nil t)
8119 (org-timestamp-change (* n shift-n) shift-what))
8120 (unless (= n n-no-remove)
8121 (goto-char (point-min))
8122 (while (re-search-forward org-ts-regexp nil t)
8123 (save-excursion
8124 (goto-char (match-beginning 0))
8125 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8126 (delete-region (match-beginning 1) (match-end 1)))))))
8127 (setq task (buffer-string)))
8128 (insert task))
8129 (goto-char beg)))
8131 ;;; Outline Sorting
8133 (defun org-sort (with-case)
8134 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8135 Optional argument WITH-CASE means sort case-sensitively."
8136 (interactive "P")
8137 (cond
8138 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8139 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8141 (org-call-with-arg 'org-sort-entries with-case))))
8143 (defun org-sort-remove-invisible (s)
8144 (remove-text-properties 0 (length s) org-rm-props s)
8145 (while (string-match org-bracket-link-regexp s)
8146 (setq s (replace-match (if (match-end 2)
8147 (match-string 3 s)
8148 (match-string 1 s)) t t s)))
8151 (defvar org-priority-regexp) ; defined later in the file
8153 (defvar org-after-sorting-entries-or-items-hook nil
8154 "Hook that is run after a bunch of entries or items have been sorted.
8155 When children are sorted, the cursor is in the parent line when this
8156 hook gets called. When a region or a plain list is sorted, the cursor
8157 will be in the first entry of the sorted region/list.")
8159 (defun org-sort-entries
8160 (&optional with-case sorting-type getkey-func compare-func property)
8161 "Sort entries on a certain level of an outline tree.
8162 If there is an active region, the entries in the region are sorted.
8163 Else, if the cursor is before the first entry, sort the top-level items.
8164 Else, the children of the entry at point are sorted.
8166 Sorting can be alphabetically, numerically, by date/time as given by
8167 a time stamp, by a property or by priority.
8169 The command prompts for the sorting type unless it has been given to the
8170 function through the SORTING-TYPE argument, which needs to be a character,
8171 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8172 precise meaning of each character:
8174 n Numerically, by converting the beginning of the entry/item to a number.
8175 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8176 t By date/time, either the first active time stamp in the entry, or, if
8177 none exist, by the first inactive one.
8178 s By the scheduled date/time.
8179 d By deadline date/time.
8180 c By creation time, which is assumed to be the first inactive time stamp
8181 at the beginning of a line.
8182 p By priority according to the cookie.
8183 r By the value of a property.
8185 Capital letters will reverse the sort order.
8187 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8188 called with point at the beginning of the record. It must return either
8189 a string or a number that should serve as the sorting key for that record.
8191 Comparing entries ignores case by default. However, with an optional argument
8192 WITH-CASE, the sorting considers case as well."
8193 (interactive "P")
8194 (let ((case-func (if with-case 'identity 'downcase))
8195 start beg end stars re re2
8196 txt what tmp)
8197 ;; Find beginning and end of region to sort
8198 (cond
8199 ((org-region-active-p)
8200 ;; we will sort the region
8201 (setq end (region-end)
8202 what "region")
8203 (goto-char (region-beginning))
8204 (if (not (org-at-heading-p)) (outline-next-heading))
8205 (setq start (point)))
8206 ((or (org-at-heading-p)
8207 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8208 ;; we will sort the children of the current headline
8209 (org-back-to-heading)
8210 (setq start (point)
8211 end (progn (org-end-of-subtree t t)
8212 (or (bolp) (insert "\n"))
8213 (org-back-over-empty-lines)
8214 (point))
8215 what "children")
8216 (goto-char start)
8217 (show-subtree)
8218 (outline-next-heading))
8220 ;; we will sort the top-level entries in this file
8221 (goto-char (point-min))
8222 (or (org-at-heading-p) (outline-next-heading))
8223 (setq start (point))
8224 (goto-char (point-max))
8225 (beginning-of-line 1)
8226 (when (looking-at ".*?\\S-")
8227 ;; File ends in a non-white line
8228 (end-of-line 1)
8229 (insert "\n"))
8230 (setq end (point-max))
8231 (setq what "top-level")
8232 (goto-char start)
8233 (show-all)))
8235 (setq beg (point))
8236 (if (>= beg end) (error "Nothing to sort"))
8238 (looking-at "\\(\\*+\\)")
8239 (setq stars (match-string 1)
8240 re (concat "^" (regexp-quote stars) " +")
8241 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8242 txt (buffer-substring beg end))
8243 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8244 (if (and (not (equal stars "*")) (string-match re2 txt))
8245 (error "Region to sort contains a level above the first entry"))
8247 (unless sorting-type
8248 (message
8249 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8250 [t]ime [s]cheduled [d]eadline [c]reated
8251 A/N/T/S/D/C/P/O/F means reversed:"
8252 what)
8253 (setq sorting-type (read-char-exclusive))
8255 (and (= (downcase sorting-type) ?f)
8256 (setq getkey-func
8257 (org-icompleting-read "Sort using function: "
8258 obarray 'fboundp t nil nil))
8259 (setq getkey-func (intern getkey-func)))
8261 (and (= (downcase sorting-type) ?r)
8262 (setq property
8263 (org-icompleting-read "Property: "
8264 (mapcar 'list (org-buffer-property-keys t))
8265 nil t))))
8267 (message "Sorting entries...")
8269 (save-restriction
8270 (narrow-to-region start end)
8271 (let ((dcst (downcase sorting-type))
8272 (case-fold-search nil)
8273 (now (current-time)))
8274 (sort-subr
8275 (/= dcst sorting-type)
8276 ;; This function moves to the beginning character of the "record" to
8277 ;; be sorted.
8278 (lambda nil
8279 (if (re-search-forward re nil t)
8280 (goto-char (match-beginning 0))
8281 (goto-char (point-max))))
8282 ;; This function moves to the last character of the "record" being
8283 ;; sorted.
8284 (lambda nil
8285 (save-match-data
8286 (condition-case nil
8287 (outline-forward-same-level 1)
8288 (error
8289 (goto-char (point-max))))))
8290 ;; This function returns the value that gets sorted against.
8291 (lambda nil
8292 (cond
8293 ((= dcst ?n)
8294 (if (looking-at org-complex-heading-regexp)
8295 (string-to-number (match-string 4))
8296 nil))
8297 ((= dcst ?a)
8298 (if (looking-at org-complex-heading-regexp)
8299 (funcall case-func (match-string 4))
8300 nil))
8301 ((= dcst ?t)
8302 (let ((end (save-excursion (outline-next-heading) (point))))
8303 (if (or (re-search-forward org-ts-regexp end t)
8304 (re-search-forward org-ts-regexp-both end t))
8305 (org-time-string-to-seconds (match-string 0))
8306 (org-float-time now))))
8307 ((= dcst ?c)
8308 (let ((end (save-excursion (outline-next-heading) (point))))
8309 (if (re-search-forward
8310 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8311 end t)
8312 (org-time-string-to-seconds (match-string 0))
8313 (org-float-time now))))
8314 ((= dcst ?s)
8315 (let ((end (save-excursion (outline-next-heading) (point))))
8316 (if (re-search-forward org-scheduled-time-regexp end t)
8317 (org-time-string-to-seconds (match-string 1))
8318 (org-float-time now))))
8319 ((= dcst ?d)
8320 (let ((end (save-excursion (outline-next-heading) (point))))
8321 (if (re-search-forward org-deadline-time-regexp end t)
8322 (org-time-string-to-seconds (match-string 1))
8323 (org-float-time now))))
8324 ((= dcst ?p)
8325 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8326 (string-to-char (match-string 2))
8327 org-default-priority))
8328 ((= dcst ?r)
8329 (or (org-entry-get nil property) ""))
8330 ((= dcst ?o)
8331 (if (looking-at org-complex-heading-regexp)
8332 (- 9999 (length (member (match-string 2)
8333 org-todo-keywords-1)))))
8334 ((= dcst ?f)
8335 (if getkey-func
8336 (progn
8337 (setq tmp (funcall getkey-func))
8338 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8339 tmp)
8340 (error "Invalid key function `%s'" getkey-func)))
8341 (t (error "Invalid sorting type `%c'" sorting-type))))
8343 (cond
8344 ((= dcst ?a) 'string<)
8345 ((= dcst ?f) compare-func)
8346 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8347 (run-hooks 'org-after-sorting-entries-or-items-hook)
8348 (message "Sorting entries...done")))
8350 (defun org-do-sort (table what &optional with-case sorting-type)
8351 "Sort TABLE of WHAT according to SORTING-TYPE.
8352 The user will be prompted for the SORTING-TYPE if the call to this
8353 function does not specify it. WHAT is only for the prompt, to indicate
8354 what is being sorted. The sorting key will be extracted from
8355 the car of the elements of the table.
8356 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8357 (unless sorting-type
8358 (message
8359 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8360 what)
8361 (setq sorting-type (read-char-exclusive)))
8362 (let ((dcst (downcase sorting-type))
8363 extractfun comparefun)
8364 ;; Define the appropriate functions
8365 (cond
8366 ((= dcst ?n)
8367 (setq extractfun 'string-to-number
8368 comparefun (if (= dcst sorting-type) '< '>)))
8369 ((= dcst ?a)
8370 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8371 (lambda(x) (downcase (org-sort-remove-invisible x))))
8372 comparefun (if (= dcst sorting-type)
8373 'string<
8374 (lambda (a b) (and (not (string< a b))
8375 (not (string= a b)))))))
8376 ((= dcst ?t)
8377 (setq extractfun
8378 (lambda (x)
8379 (if (or (string-match org-ts-regexp x)
8380 (string-match org-ts-regexp-both x))
8381 (org-float-time
8382 (org-time-string-to-time (match-string 0 x)))
8384 comparefun (if (= dcst sorting-type) '< '>)))
8385 (t (error "Invalid sorting type `%c'" sorting-type)))
8387 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8388 table)
8389 (lambda (a b) (funcall comparefun (car a) (car b))))))
8392 ;;; The orgstruct minor mode
8394 ;; Define a minor mode which can be used in other modes in order to
8395 ;; integrate the org-mode structure editing commands.
8397 ;; This is really a hack, because the org-mode structure commands use
8398 ;; keys which normally belong to the major mode. Here is how it
8399 ;; works: The minor mode defines all the keys necessary to operate the
8400 ;; structure commands, but wraps the commands into a function which
8401 ;; tests if the cursor is currently at a headline or a plain list
8402 ;; item. If that is the case, the structure command is used,
8403 ;; temporarily setting many Org-mode variables like regular
8404 ;; expressions for filling etc. However, when any of those keys is
8405 ;; used at a different location, function uses `key-binding' to look
8406 ;; up if the key has an associated command in another currently active
8407 ;; keymap (minor modes, major mode, global), and executes that
8408 ;; command. There might be problems if any of the keys is otherwise
8409 ;; used as a prefix key.
8411 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8412 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8413 ;; addresses this by checking explicitly for both bindings.
8415 (defvar orgstruct-mode-map (make-sparse-keymap)
8416 "Keymap for the minor `orgstruct-mode'.")
8418 (defvar org-local-vars nil
8419 "List of local variables, for use by `orgstruct-mode'.")
8421 ;;;###autoload
8422 (define-minor-mode orgstruct-mode
8423 "Toggle the minor mode `orgstruct-mode'.
8424 This mode is for using Org-mode structure commands in other
8425 modes. The following keys behave as if Org-mode were active, if
8426 the cursor is on a headline, or on a plain list item (both as
8427 defined by Org-mode).
8429 M-up Move entry/item up
8430 M-down Move entry/item down
8431 M-left Promote
8432 M-right Demote
8433 M-S-up Move entry/item up
8434 M-S-down Move entry/item down
8435 M-S-left Promote subtree
8436 M-S-right Demote subtree
8437 M-q Fill paragraph and items like in Org-mode
8438 C-c ^ Sort entries
8439 C-c - Cycle list bullet
8440 TAB Cycle item visibility
8441 M-RET Insert new heading/item
8442 S-M-RET Insert new TODO heading / Checkbox item
8443 C-c C-c Set tags / toggle checkbox"
8444 nil " OrgStruct" nil
8445 (org-load-modules-maybe)
8446 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8448 ;;;###autoload
8449 (defun turn-on-orgstruct ()
8450 "Unconditionally turn on `orgstruct-mode'."
8451 (orgstruct-mode 1))
8453 (defvar org-fb-vars nil)
8454 (make-variable-buffer-local 'org-fb-vars)
8455 (defun orgstruct++-mode (&optional arg)
8456 "Toggle `orgstruct-mode', the enhanced version of it.
8457 In addition to setting orgstruct-mode, this also exports all
8458 indentation and autofilling variables from org-mode into the
8459 buffer. It will also recognize item context in multiline items."
8460 (interactive "P")
8461 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8462 (if (< arg 1)
8463 (progn (orgstruct-mode -1)
8464 (mapc (lambda(v)
8465 (org-set-local (car v)
8466 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8467 org-fb-vars))
8468 (orgstruct-mode 1)
8469 (setq org-fb-vars nil)
8470 (let (var val)
8471 (mapc
8472 (lambda (x)
8473 (when (string-match
8474 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8475 (symbol-name (car x)))
8476 (setq var (car x) val (nth 1 x))
8477 (push (list var `(quote ,(eval var))) org-fb-vars)
8478 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8479 org-local-vars)
8480 (org-set-local 'orgstruct-is-++ t))))
8482 (defvar orgstruct-is-++ nil
8483 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8484 (make-variable-buffer-local 'orgstruct-is-++)
8486 ;;;###autoload
8487 (defun turn-on-orgstruct++ ()
8488 "Unconditionally turn on `orgstruct++-mode'."
8489 (orgstruct++-mode 1))
8491 (defun orgstruct-error ()
8492 "Error when there is no default binding for a structure key."
8493 (interactive)
8494 (error "This key has no function outside structure elements"))
8496 (defun orgstruct-setup ()
8497 "Setup orgstruct keymaps."
8498 (let ((nfunc 0)
8499 (bindings
8500 (list
8501 '([(meta up)] org-metaup)
8502 '([(meta down)] org-metadown)
8503 '([(meta left)] org-metaleft)
8504 '([(meta right)] org-metaright)
8505 '([(meta shift up)] org-shiftmetaup)
8506 '([(meta shift down)] org-shiftmetadown)
8507 '([(meta shift left)] org-shiftmetaleft)
8508 '([(meta shift right)] org-shiftmetaright)
8509 '([?\e (up)] org-metaup)
8510 '([?\e (down)] org-metadown)
8511 '([?\e (left)] org-metaleft)
8512 '([?\e (right)] org-metaright)
8513 '([?\e (shift up)] org-shiftmetaup)
8514 '([?\e (shift down)] org-shiftmetadown)
8515 '([?\e (shift left)] org-shiftmetaleft)
8516 '([?\e (shift right)] org-shiftmetaright)
8517 '([(shift up)] org-shiftup)
8518 '([(shift down)] org-shiftdown)
8519 '([(shift left)] org-shiftleft)
8520 '([(shift right)] org-shiftright)
8521 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8522 '("\M-q" fill-paragraph)
8523 '("\C-c^" org-sort)
8524 '("\C-c-" org-cycle-list-bullet)))
8525 elt key fun cmd)
8526 (while (setq elt (pop bindings))
8527 (setq nfunc (1+ nfunc))
8528 (setq key (org-key (car elt))
8529 fun (nth 1 elt)
8530 cmd (orgstruct-make-binding fun nfunc key))
8531 (org-defkey orgstruct-mode-map key cmd))
8533 ;; Prevent an error for users who forgot to make autoloads
8534 (require 'org-element)
8536 ;; Special treatment needed for TAB and RET
8537 (org-defkey orgstruct-mode-map [(tab)]
8538 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8539 (org-defkey orgstruct-mode-map "\C-i"
8540 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8542 (org-defkey orgstruct-mode-map "\M-\C-m"
8543 (orgstruct-make-binding 'org-insert-heading 105
8544 "\M-\C-m" [(meta return)]))
8545 (org-defkey orgstruct-mode-map [(meta return)]
8546 (orgstruct-make-binding 'org-insert-heading 106
8547 [(meta return)] "\M-\C-m"))
8549 (org-defkey orgstruct-mode-map [(shift meta return)]
8550 (orgstruct-make-binding 'org-insert-todo-heading 107
8551 [(meta return)] "\M-\C-m"))
8553 (org-defkey orgstruct-mode-map "\e\C-m"
8554 (orgstruct-make-binding 'org-insert-heading 108
8555 "\e\C-m" [?\e (return)]))
8556 (org-defkey orgstruct-mode-map [?\e (return)]
8557 (orgstruct-make-binding 'org-insert-heading 109
8558 [?\e (return)] "\e\C-m"))
8559 (org-defkey orgstruct-mode-map [?\e (shift return)]
8560 (orgstruct-make-binding 'org-insert-todo-heading 110
8561 [?\e (return)] "\e\C-m"))
8563 (unless org-local-vars
8564 (setq org-local-vars (org-get-local-variables)))
8568 (defun orgstruct-make-binding (fun n &rest keys)
8569 "Create a function for binding in the structure minor mode.
8570 FUN is the command to call inside a table. N is used to create a unique
8571 command name. KEYS are keys that should be checked in for a command
8572 to execute outside of tables."
8573 (eval
8574 (list 'defun
8575 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8576 '(arg)
8577 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8578 "Outside of structure, run the binding of `"
8579 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8580 "'.")
8581 '(interactive "p")
8582 (list 'if
8583 `(org-context-p 'headline 'item
8584 (and orgstruct-is-++
8585 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8586 'item-body))
8587 (list 'org-run-like-in-org-mode (list 'quote fun))
8588 (list 'let '(orgstruct-mode)
8589 (list 'call-interactively
8590 (append '(or)
8591 (mapcar (lambda (k)
8592 (list 'key-binding k))
8593 keys)
8594 '('orgstruct-error))))))))
8596 (defun org-contextualize-keys (alist contexts)
8597 "Return valid elements in ALIST depending on CONTEXTS.
8599 `org-agenda-custom-commands' or `org-capture-templates' are the
8600 values used for ALIST, and `org-agenda-custom-commands-contexts'
8601 or `org-capture-templates-contexts' are the associated contexts
8602 definitions."
8603 (let ((contexts
8604 ;; normalize contexts
8605 (mapcar
8606 (lambda(c) (cond ((listp (cadr c))
8607 (list (car c) (car c) (cadr c)))
8608 ((string= "" (cadr c))
8609 (list (car c) (car c) (caddr c)))
8610 (t c))) contexts))
8611 (a alist) c r s)
8612 ;; loop over all commands or templates
8613 (while (setq c (pop a))
8614 (let (vrules repl)
8615 (cond
8616 ((not (assoc (car c) contexts))
8617 (push c r))
8618 ((and (assoc (car c) contexts)
8619 (setq vrules (org-contextualize-validate-key
8620 (car c) contexts)))
8621 (mapc (lambda (vr)
8622 (when (not (equal (car vr) (cadr vr)))
8623 (setq repl vr))) vrules)
8624 (if (not repl) (push c r)
8625 (push (cadr repl) s)
8626 (push
8627 (cons (car c)
8628 (cdr (or (assoc (cadr repl) alist)
8629 (error "Undefined key `%s' as contextual replacement for `%s'"
8630 (cadr repl) (car c)))))
8631 r))))))
8632 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8633 (delq
8635 (delete-dups
8636 (mapcar (lambda (x)
8637 (let ((tpl (car x)))
8638 (when (not (delq
8640 (mapcar (lambda(y)
8641 (equal y tpl)) s))) x)))
8642 (reverse r))))))
8644 (defun org-contextualize-validate-key (key contexts)
8645 "Check CONTEXTS for agenda or capture KEY."
8646 (let (r rr res)
8647 (while (setq r (pop contexts))
8648 (mapc
8649 (lambda (rr)
8650 (when
8651 (and (equal key (car r))
8652 (if (functionp rr) (funcall rr)
8653 (or (and (eq (car rr) 'in-file)
8654 (buffer-file-name)
8655 (string-match (cdr rr) (buffer-file-name)))
8656 (and (eq (car rr) 'in-mode)
8657 (string-match (cdr rr) (symbol-name major-mode)))
8658 (when (and (eq (car rr) 'not-in-file)
8659 (buffer-file-name))
8660 (not (string-match (cdr rr) (buffer-file-name))))
8661 (when (eq (car rr) 'not-in-mode)
8662 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8663 (push r res)))
8664 (car (last r))))
8665 (delete-dups (delq nil res))))
8667 (defun org-context-p (&rest contexts)
8668 "Check if local context is any of CONTEXTS.
8669 Possible values in the list of contexts are `table', `headline', and `item'."
8670 (let ((pos (point)))
8671 (goto-char (point-at-bol))
8672 (prog1 (or (and (memq 'table contexts)
8673 (looking-at "[ \t]*|"))
8674 (and (memq 'headline contexts)
8675 (looking-at org-outline-regexp))
8676 (and (memq 'item contexts)
8677 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8678 (and (memq 'item-body contexts)
8679 (org-in-item-p)))
8680 (goto-char pos))))
8682 (defun org-get-local-variables ()
8683 "Return a list of all local variables in an Org mode buffer."
8684 (let (varlist)
8685 (with-current-buffer (get-buffer-create "*Org tmp*")
8686 (erase-buffer)
8687 (org-mode)
8688 (setq varlist (buffer-local-variables)))
8689 (kill-buffer "*Org tmp*")
8690 (delq nil
8691 (mapcar
8692 (lambda (x)
8693 (setq x
8694 (if (symbolp x)
8695 (list x)
8696 (list (car x) (list 'quote (cdr x)))))
8697 (if (string-match
8698 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8699 (symbol-name (car x)))
8700 x nil))
8701 varlist))))
8703 (defun org-clone-local-variables (from-buffer &optional regexp)
8704 "Clone local variables from FROM-BUFFER.
8705 Optional argument REGEXP selects variables to clone."
8706 (mapc
8707 (lambda (pair)
8708 (and (symbolp (car pair))
8709 (or (null regexp)
8710 (string-match regexp (symbol-name (car pair))))
8711 (set (make-local-variable (car pair))
8712 (cdr pair))))
8713 (buffer-local-variables from-buffer)))
8715 ;;;###autoload
8716 (defun org-run-like-in-org-mode (cmd)
8717 "Run a command, pretending that the current buffer is in Org-mode.
8718 This will temporarily bind local variables that are typically bound in
8719 Org-mode to the values they have in Org-mode, and then interactively
8720 call CMD."
8721 (org-load-modules-maybe)
8722 (unless org-local-vars
8723 (setq org-local-vars (org-get-local-variables)))
8724 (eval (list 'let org-local-vars
8725 (list 'call-interactively (list 'quote cmd)))))
8727 ;;;; Archiving
8729 (defun org-get-category (&optional pos force-refresh)
8730 "Get the category applying to position POS."
8731 (save-match-data
8732 (if force-refresh (org-refresh-category-properties))
8733 (let ((pos (or pos (point))))
8734 (or (get-text-property pos 'org-category)
8735 (progn (org-refresh-category-properties)
8736 (get-text-property pos 'org-category))))))
8738 (defun org-refresh-category-properties ()
8739 "Refresh category text properties in the buffer."
8740 (let ((case-fold-search t)
8741 (inhibit-read-only t)
8742 (def-cat (cond
8743 ((null org-category)
8744 (if buffer-file-name
8745 (file-name-sans-extension
8746 (file-name-nondirectory buffer-file-name))
8747 "???"))
8748 ((symbolp org-category) (symbol-name org-category))
8749 (t org-category)))
8750 beg end cat pos optionp)
8751 (org-unmodified
8752 (save-excursion
8753 (save-restriction
8754 (widen)
8755 (goto-char (point-min))
8756 (put-text-property (point) (point-max) 'org-category def-cat)
8757 (while (re-search-forward
8758 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8759 (setq pos (match-end 0)
8760 optionp (equal (char-after (match-beginning 0)) ?#)
8761 cat (org-trim (match-string 2)))
8762 (if optionp
8763 (setq beg (point-at-bol) end (point-max))
8764 (org-back-to-heading t)
8765 (setq beg (point) end (org-end-of-subtree t t)))
8766 (put-text-property beg end 'org-category cat)
8767 (put-text-property beg end 'org-category-position beg)
8768 (goto-char pos)))))))
8771 ;;;; Link Stuff
8773 ;;; Link abbreviations
8775 (defun org-link-expand-abbrev (link)
8776 "Apply replacements as defined in `org-link-abbrev-alist'."
8777 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8778 (let* ((key (match-string 1 link))
8779 (as (or (assoc key org-link-abbrev-alist-local)
8780 (assoc key org-link-abbrev-alist)))
8781 (tag (and (match-end 2) (match-string 3 link)))
8782 rpl)
8783 (if (not as)
8784 link
8785 (setq rpl (cdr as))
8786 (cond
8787 ((symbolp rpl) (funcall rpl tag))
8788 ((string-match "%(\\([^)]+\\))" rpl)
8789 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8790 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8791 ((string-match "%h" rpl)
8792 (replace-match (url-hexify-string (or tag "")) t t rpl))
8793 (t (concat rpl tag)))))
8794 link))
8796 ;;; Storing and inserting links
8798 (defvar org-insert-link-history nil
8799 "Minibuffer history for links inserted with `org-insert-link'.")
8801 (defvar org-stored-links nil
8802 "Contains the links stored with `org-store-link'.")
8804 (defvar org-store-link-plist nil
8805 "Plist with info about the most recently link created with `org-store-link'.")
8807 (defvar org-link-protocols nil
8808 "Link protocols added to Org-mode using `org-add-link-type'.")
8810 (defvar org-store-link-functions nil
8811 "List of functions that are called to create and store a link.
8812 Each function will be called in turn until one returns a non-nil
8813 value. Each function should check if it is responsible for creating
8814 this link (for example by looking at the major mode).
8815 If not, it must exit and return nil.
8816 If yes, it should return a non-nil value after a calling
8817 `org-store-link-props' with a list of properties and values.
8818 Special properties are:
8820 :type The link prefix, like \"http\". This must be given.
8821 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8822 This is obligatory as well.
8823 :description Optional default description for the second pair
8824 of brackets in an Org-mode link. The user can still change
8825 this when inserting this link into an Org-mode buffer.
8827 In addition to these, any additional properties can be specified
8828 and then used in capture templates.")
8830 (defun org-add-link-type (type &optional follow export)
8831 "Add TYPE to the list of `org-link-types'.
8832 Re-compute all regular expressions depending on `org-link-types'
8834 FOLLOW and EXPORT are two functions.
8836 FOLLOW should take the link path as the single argument and do whatever
8837 is necessary to follow the link, for example find a file or display
8838 a mail message.
8840 EXPORT should format the link path for export to one of the export formats.
8841 It should be a function accepting three arguments:
8843 path the path of the link, the text after the prefix (like \"http:\")
8844 desc the description of the link, if any, or a description added by
8845 org-export-normalize-links if there is none
8846 format the export format, a symbol like `html' or `latex' or `ascii'..
8848 The function may use the FORMAT information to return different values
8849 depending on the format. The return value will be put literally into
8850 the exported file. If the return value is nil, this means Org should
8851 do what it normally does with links which do not have EXPORT defined.
8853 Org-mode has a built-in default for exporting links. If you are happy with
8854 this default, there is no need to define an export function for the link
8855 type. For a simple example of an export function, see `org-bbdb.el'."
8856 (add-to-list 'org-link-types type t)
8857 (org-make-link-regexps)
8858 (if (assoc type org-link-protocols)
8859 (setcdr (assoc type org-link-protocols) (list follow export))
8860 (push (list type follow export) org-link-protocols)))
8862 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8863 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8865 ;;;###autoload
8866 (defun org-store-link (arg)
8867 "\\<org-mode-map>Store an org-link to the current location.
8868 This link is added to `org-stored-links' and can later be inserted
8869 into an org-buffer with \\[org-insert-link].
8871 For some link types, a prefix arg is interpreted:
8872 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8873 For file links, arg negates `org-context-in-file-links'."
8874 (interactive "P")
8875 (org-load-modules-maybe)
8876 (setq org-store-link-plist nil) ; reset
8877 (org-with-limited-levels
8878 (let (link cpltxt desc description search txt custom-id agenda-link)
8879 (cond
8881 ((run-hook-with-args-until-success 'org-store-link-functions)
8882 (setq link (plist-get org-store-link-plist :link)
8883 desc (or (plist-get org-store-link-plist :description) link)))
8885 ((org-src-edit-buffer-p)
8886 (let (label gc)
8887 (while (or (not label)
8888 (save-excursion
8889 (save-restriction
8890 (widen)
8891 (goto-char (point-min))
8892 (re-search-forward
8893 (regexp-quote (format org-coderef-label-format label))
8894 nil t))))
8895 (when label (message "Label exists already") (sit-for 2))
8896 (setq label (read-string "Code line label: " label)))
8897 (end-of-line 1)
8898 (setq link (format org-coderef-label-format label))
8899 (setq gc (- 79 (length link)))
8900 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8901 (insert link)
8902 (setq link (concat "(" label ")") desc nil)))
8904 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8905 ;; We are in the agenda, link to referenced location
8906 (let ((m (or (get-text-property (point) 'org-hd-marker)
8907 (get-text-property (point) 'org-marker))))
8908 (when m
8909 (org-with-point-at m
8910 (setq agenda-link
8911 (if (org-called-interactively-p 'any)
8912 (call-interactively 'org-store-link)
8913 (org-store-link nil)))))))
8915 ((eq major-mode 'calendar-mode)
8916 (let ((cd (calendar-cursor-to-date)))
8917 (setq link
8918 (format-time-string
8919 (car org-time-stamp-formats)
8920 (apply 'encode-time
8921 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8922 nil nil nil))))
8923 (org-store-link-props :type "calendar" :date cd)))
8925 ((eq major-mode 'help-mode)
8926 (setq link (concat "help:" (save-excursion
8927 (goto-char (point-min))
8928 (looking-at "^[^ ]+")
8929 (match-string 0))))
8930 (org-store-link-props :type "help"))
8932 ((eq major-mode 'w3-mode)
8933 (setq cpltxt (if (and (buffer-name)
8934 (not (string-match "Untitled" (buffer-name))))
8935 (buffer-name)
8936 (url-view-url t))
8937 link (url-view-url t))
8938 (org-store-link-props :type "w3" :url (url-view-url t)))
8940 ((eq major-mode 'w3m-mode)
8941 (setq cpltxt (or w3m-current-title w3m-current-url)
8942 link w3m-current-url)
8943 (org-store-link-props :type "w3m" :url (url-view-url t)))
8945 ((setq search (run-hook-with-args-until-success
8946 'org-create-file-search-functions))
8947 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8948 "::" search))
8949 (setq cpltxt (or description link)))
8951 ((eq major-mode 'image-mode)
8952 (setq cpltxt (concat "file:"
8953 (abbreviate-file-name buffer-file-name))
8954 link cpltxt)
8955 (org-store-link-props :type "image" :file buffer-file-name))
8957 ((eq major-mode 'dired-mode)
8958 ;; link to the file in the current line
8959 (let ((file (dired-get-filename nil t)))
8960 (setq file (if file
8961 (abbreviate-file-name
8962 (expand-file-name (dired-get-filename nil t)))
8963 ;; otherwise, no file so use current directory.
8964 default-directory))
8965 (setq cpltxt (concat "file:" file)
8966 link cpltxt)))
8968 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8969 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8970 (cond
8971 ((org-in-regexp "<<\\(.*?\\)>>")
8972 (setq cpltxt
8973 (concat "file:"
8974 (abbreviate-file-name
8975 (buffer-file-name (buffer-base-buffer)))
8976 "::" (match-string 1))
8977 link cpltxt))
8978 ((and (featurep 'org-id)
8979 (or (eq org-link-to-org-use-id t)
8980 (and (org-called-interactively-p 'any)
8981 (or (eq org-link-to-org-use-id 'create-if-interactive)
8982 (and (eq org-link-to-org-use-id
8983 'create-if-interactive-and-no-custom-id)
8984 (not custom-id))))
8985 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8986 ;; We can make a link using the ID.
8987 (setq link (condition-case nil
8988 (prog1 (org-id-store-link)
8989 (setq desc (plist-get org-store-link-plist :description)))
8990 (error
8991 ;; probably before first headline, link to file only
8992 (concat "file:"
8993 (abbreviate-file-name
8994 (buffer-file-name (buffer-base-buffer))))))))
8996 ;; Just link to current headline
8997 (setq cpltxt (concat "file:"
8998 (abbreviate-file-name
8999 (buffer-file-name (buffer-base-buffer)))))
9000 ;; Add a context search string
9001 (when (org-xor org-context-in-file-links arg)
9002 (setq txt (cond
9003 ((org-at-heading-p) nil)
9004 ((org-region-active-p)
9005 (buffer-substring (region-beginning) (region-end)))))
9006 (when (or (null txt) (string-match "\\S-" txt))
9007 (setq cpltxt
9008 (concat cpltxt "::"
9009 (condition-case nil
9010 (org-make-org-heading-search-string txt)
9011 (error "")))
9012 desc (or (nth 4 (ignore-errors
9013 (org-heading-components))) "NONE"))))
9014 (if (string-match "::\\'" cpltxt)
9015 (setq cpltxt (substring cpltxt 0 -2)))
9016 (setq link cpltxt))))
9018 ((buffer-file-name (buffer-base-buffer))
9019 ;; Just link to this file here.
9020 (setq cpltxt (concat "file:"
9021 (abbreviate-file-name
9022 (buffer-file-name (buffer-base-buffer)))))
9023 ;; Add a context string
9024 (when (org-xor org-context-in-file-links arg)
9025 (setq txt (if (org-region-active-p)
9026 (buffer-substring (region-beginning) (region-end))
9027 (buffer-substring (point-at-bol) (point-at-eol))))
9028 ;; Only use search option if there is some text.
9029 (when (string-match "\\S-" txt)
9030 (setq cpltxt
9031 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9032 desc "NONE")))
9033 (setq link cpltxt))
9035 ((org-called-interactively-p 'interactive)
9036 (error "Cannot link to a buffer which is not visiting a file"))
9038 (t (setq link nil)))
9040 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9041 (setq link (or link cpltxt)
9042 desc (or desc cpltxt))
9043 (if (equal desc "NONE") (setq desc nil))
9045 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9046 (progn
9047 (setq org-stored-links
9048 (cons (list link desc) org-stored-links))
9049 (message "Stored: %s" (or desc link))
9050 (when custom-id
9051 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9052 "::#" custom-id))
9053 (setq org-stored-links
9054 (cons (list link desc) org-stored-links))))
9055 (or agenda-link (and link (org-make-link-string link desc)))))))
9057 (defun org-store-link-props (&rest plist)
9058 "Store link properties, extract names and addresses."
9059 (let (x adr)
9060 (when (setq x (plist-get plist :from))
9061 (setq adr (mail-extract-address-components x))
9062 (setq plist (plist-put plist :fromname (car adr)))
9063 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9064 (when (setq x (plist-get plist :to))
9065 (setq adr (mail-extract-address-components x))
9066 (setq plist (plist-put plist :toname (car adr)))
9067 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9068 (let ((from (plist-get plist :from))
9069 (to (plist-get plist :to)))
9070 (when (and from to org-from-is-user-regexp)
9071 (setq plist
9072 (plist-put plist :fromto
9073 (if (string-match org-from-is-user-regexp from)
9074 (concat "to %t")
9075 (concat "from %f"))))))
9076 (setq org-store-link-plist plist))
9078 (defun org-add-link-props (&rest plist)
9079 "Add these properties to the link property list."
9080 (let (key value)
9081 (while plist
9082 (setq key (pop plist) value (pop plist))
9083 (setq org-store-link-plist
9084 (plist-put org-store-link-plist key value)))))
9086 (defun org-email-link-description (&optional fmt)
9087 "Return the description part of an email link.
9088 This takes information from `org-store-link-plist' and formats it
9089 according to FMT (default from `org-email-link-description-format')."
9090 (setq fmt (or fmt org-email-link-description-format))
9091 (let* ((p org-store-link-plist)
9092 (to (plist-get p :toaddress))
9093 (from (plist-get p :fromaddress))
9094 (table
9095 (list
9096 (cons "%c" (plist-get p :fromto))
9097 (cons "%F" (plist-get p :from))
9098 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9099 (cons "%T" (plist-get p :to))
9100 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9101 (cons "%s" (plist-get p :subject))
9102 (cons "%d" (plist-get p :date))
9103 (cons "%m" (plist-get p :message-id)))))
9104 (when (string-match "%c" fmt)
9105 ;; Check if the user wrote this message
9106 (if (and org-from-is-user-regexp from to
9107 (save-match-data (string-match org-from-is-user-regexp from)))
9108 (setq fmt (replace-match "to %t" t t fmt))
9109 (setq fmt (replace-match "from %f" t t fmt))))
9110 (org-replace-escapes fmt table)))
9112 (defun org-make-org-heading-search-string (&optional string heading)
9113 "Make search string for STRING or current headline."
9114 (interactive)
9115 (let ((s (or string (org-get-heading)))
9116 (lines org-context-in-file-links))
9117 (unless (and string (not heading))
9118 ;; We are using a headline, clean up garbage in there.
9119 (if (string-match org-todo-regexp s)
9120 (setq s (replace-match "" t t s)))
9121 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9122 (setq s (replace-match "" t t s)))
9123 (setq s (org-trim s))
9124 (if (string-match (concat "^\\(" org-quote-string "\\|"
9125 org-comment-string "\\)") s)
9126 (setq s (replace-match "" t t s)))
9127 (while (string-match org-ts-regexp s)
9128 (setq s (replace-match "" t t s))))
9129 (or string (setq s (concat "*" s))) ; Add * for headlines
9130 (when (and string (integerp lines) (> lines 0))
9131 (let ((slines (org-split-string s "\n")))
9132 (when (< lines (length slines))
9133 (setq s (mapconcat
9134 'identity
9135 (reverse (nthcdr (- (length slines) lines)
9136 (reverse slines))) "\n")))))
9137 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9139 (defun org-make-link-string (link &optional description)
9140 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9141 (unless (string-match "\\S-" link)
9142 (error "Empty link"))
9143 (when (and description
9144 (stringp description)
9145 (not (string-match "\\S-" description)))
9146 (setq description nil))
9147 (when (stringp description)
9148 ;; Remove brackets from the description, they are fatal.
9149 (while (string-match "\\[" description)
9150 (setq description (replace-match "{" t t description)))
9151 (while (string-match "\\]" description)
9152 (setq description (replace-match "}" t t description))))
9153 (when (equal link description)
9154 ;; No description needed, it is identical
9155 (setq description nil))
9156 (when (and (not description)
9157 (not (string-match (org-image-file-name-regexp) link))
9158 (not (equal link (org-link-escape link))))
9159 (setq description (org-extract-attributes link)))
9160 (setq link
9161 (cond ((string-match (org-image-file-name-regexp) link) link)
9162 ((string-match org-link-types-re link)
9163 (concat (match-string 1 link)
9164 (org-link-escape (substring link (match-end 1)))))
9165 (t (org-link-escape link))))
9166 (concat "[[" link "]"
9167 (if description (concat "[" description "]") "")
9168 "]"))
9170 (defconst org-link-escape-chars
9171 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9172 "List of characters that should be escaped in link.
9173 This is the list that is used for internal purposes.")
9175 (defconst org-link-escape-chars-browser
9176 '(?\ )
9177 "List of escapes for characters that are problematic in links.
9178 This is the list that is used before handing over to the browser.")
9180 (defun org-link-escape (text &optional table merge)
9181 "Return percent escaped representation of TEXT.
9182 TEXT is a string with the text to escape.
9183 Optional argument TABLE is a list with characters that should be
9184 escaped. When nil, `org-link-escape-chars' is used.
9185 If optional argument MERGE is set, merge TABLE into
9186 `org-link-escape-chars'."
9187 (cond
9188 ((and table merge)
9189 (mapc (lambda (defchr)
9190 (unless (member defchr table)
9191 (setq table (cons defchr table)))) org-link-escape-chars))
9192 ((null table)
9193 (setq table org-link-escape-chars)))
9194 (mapconcat
9195 (lambda (char)
9196 (if (or (member char table)
9197 (and (or (< char 32) (= char 37) (> char 126))
9198 org-url-hexify-p))
9199 (mapconcat (lambda (sequence-element)
9200 (format "%%%.2X" sequence-element))
9201 (or (encode-coding-char char 'utf-8)
9202 (error "Unable to percent escape character: %s"
9203 (char-to-string char))) "")
9204 (char-to-string char))) text ""))
9206 (defun org-link-unescape (str)
9207 "Unhex hexified Unicode strings as returned from the JavaScript function
9208 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9209 (unless (and (null str) (string= "" str))
9210 (let ((pos 0) (case-fold-search t) unhexed)
9211 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9212 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9213 (setq str (replace-match unhexed t t str))
9214 (setq pos (+ pos (length unhexed))))))
9215 str)
9217 (defun org-link-unescape-compound (hex)
9218 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9219 Note: this function also decodes single byte encodings like
9220 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9221 (save-match-data
9222 (let* ((bytes (cdr (split-string hex "%")))
9223 (ret "")
9224 (eat 0)
9225 (sum 0))
9226 (while bytes
9227 (let* ((val (string-to-number (pop bytes) 16))
9228 (shift-xor
9229 (if (= 0 eat)
9230 (cond
9231 ((>= val 252) (cons 6 252))
9232 ((>= val 248) (cons 5 248))
9233 ((>= val 240) (cons 4 240))
9234 ((>= val 224) (cons 3 224))
9235 ((>= val 192) (cons 2 192))
9236 (t (cons 0 0)))
9237 (cons 6 128))))
9238 (if (>= val 192) (setq eat (car shift-xor)))
9239 (setq val (logxor val (cdr shift-xor)))
9240 (setq sum (+ (lsh sum (car shift-xor)) val))
9241 (if (> eat 0) (setq eat (- eat 1)))
9242 (cond
9243 ((= 0 eat) ;multi byte
9244 (setq ret (concat ret (org-char-to-string sum)))
9245 (setq sum 0))
9246 ((not bytes) ; single byte(s)
9247 (setq ret (org-link-unescape-single-byte-sequence hex))))
9248 )) ;; end (while bytes
9249 ret )))
9251 (defun org-link-unescape-single-byte-sequence (hex)
9252 "Unhexify hex-encoded single byte character sequences."
9253 (mapconcat (lambda (byte)
9254 (char-to-string (string-to-number byte 16)))
9255 (cdr (split-string hex "%")) ""))
9257 (defun org-xor (a b)
9258 "Exclusive or."
9259 (if a (not b) b))
9261 (defun org-fixup-message-id-for-http (s)
9262 "Replace special characters in a message id, so it can be used in an http query."
9263 (when (string-match "%" s)
9264 (setq s (mapconcat (lambda (c)
9265 (if (eq c ?%)
9266 "%25"
9267 (char-to-string c)))
9268 s "")))
9269 (while (string-match "<" s)
9270 (setq s (replace-match "%3C" t t s)))
9271 (while (string-match ">" s)
9272 (setq s (replace-match "%3E" t t s)))
9273 (while (string-match "@" s)
9274 (setq s (replace-match "%40" t t s)))
9277 (defun org-link-prettify (link)
9278 "Return a human-readable representation of LINK.
9279 The car of LINK must be a raw link the cdr of LINK must be either
9280 a link description or nil."
9281 (let ((desc (or (cadr link) "<no description>")))
9282 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9283 "<" (car link) ">")))
9285 ;;;###autoload
9286 (defun org-insert-link-global ()
9287 "Insert a link like Org-mode does.
9288 This command can be called in any mode to insert a link in Org-mode syntax."
9289 (interactive)
9290 (org-load-modules-maybe)
9291 (org-run-like-in-org-mode 'org-insert-link))
9293 (defun org-insert-all-links (&optional keep)
9294 "Insert all links in `org-stored-links'."
9295 (interactive "P")
9296 (let ((links (copy-sequence org-stored-links)) l)
9297 (while (setq l (if keep (pop links) (pop org-stored-links)))
9298 (insert "- ")
9299 (org-insert-link nil (car l) (cadr l))
9300 (insert "\n"))))
9302 (defun org-link-fontify-links-to-this-file ()
9303 "Fontify links to the current file in `org-stored-links'."
9304 (let ((f (buffer-file-name)) a b)
9305 (setq a (mapcar (lambda(l)
9306 (let ((ll (car l)))
9307 (when (and (string-match "^file:\\(.+\\)::" ll)
9308 (equal f (expand-file-name (match-string 1 ll))))
9309 ll)))
9310 org-stored-links))
9311 (when (featurep 'org-id)
9312 (setq b (mapcar (lambda(l)
9313 (let ((ll (car l)))
9314 (when (and (string-match "^id:\\(.+\\)$" ll)
9315 (equal f (expand-file-name
9316 (or (org-id-find-id-file
9317 (match-string 1 ll)) ""))))
9318 ll)))
9319 org-stored-links)))
9320 (mapcar (lambda(l)
9321 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9322 (delq nil (append a b)))))
9324 (defvar org-link-links-in-this-file nil)
9325 (defun org-insert-link (&optional complete-file link-location default-description)
9326 "Insert a link. At the prompt, enter the link.
9328 Completion can be used to insert any of the link protocol prefixes like
9329 http or ftp in use.
9331 The history can be used to select a link previously stored with
9332 `org-store-link'. When the empty string is entered (i.e. if you just
9333 press RET at the prompt), the link defaults to the most recently
9334 stored link. As SPC triggers completion in the minibuffer, you need to
9335 use M-SPC or C-q SPC to force the insertion of a space character.
9337 You will also be prompted for a description, and if one is given, it will
9338 be displayed in the buffer instead of the link.
9340 If there is already a link at point, this command will allow you to edit link
9341 and description parts.
9343 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9344 be selected using completion. The path to the file will be relative to the
9345 current directory if the file is in the current directory or a subdirectory.
9346 Otherwise, the link will be the absolute path as completed in the minibuffer
9347 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9348 option `org-link-file-path-type'.
9350 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9351 the current directory or below.
9353 With three \\[universal-argument] prefixes, negate the meaning of
9354 `org-keep-stored-link-after-insertion'.
9356 If `org-make-link-description-function' is non-nil, this function will be
9357 called with the link target, and the result will be the default
9358 link description.
9360 If the LINK-LOCATION parameter is non-nil, this value will be
9361 used as the link location instead of reading one interactively.
9363 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9364 be used as the default description."
9365 (interactive "P")
9366 (let* ((wcf (current-window-configuration))
9367 (region (if (org-region-active-p)
9368 (buffer-substring (region-beginning) (region-end))))
9369 (remove (and region (list (region-beginning) (region-end))))
9370 (desc region)
9371 tmphist ; byte-compile incorrectly complains about this
9372 (link link-location)
9373 (abbrevs org-link-abbrev-alist-local)
9374 entry file all-prefixes auto-desc)
9375 (cond
9376 (link-location) ; specified by arg, just use it.
9377 ((org-in-regexp org-bracket-link-regexp 1)
9378 ;; We do have a link at point, and we are going to edit it.
9379 (setq remove (list (match-beginning 0) (match-end 0)))
9380 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9381 (setq link (read-string "Link: "
9382 (org-link-unescape
9383 (org-match-string-no-properties 1)))))
9384 ((or (org-in-regexp org-angle-link-re)
9385 (org-in-regexp org-plain-link-re))
9386 ;; Convert to bracket link
9387 (setq remove (list (match-beginning 0) (match-end 0))
9388 link (read-string "Link: "
9389 (org-remove-angle-brackets (match-string 0)))))
9390 ((member complete-file '((4) (16)))
9391 ;; Completing read for file names.
9392 (setq link (org-file-complete-link complete-file)))
9394 ;; Read link, with completion for stored links.
9395 (org-link-fontify-links-to-this-file)
9396 (org-switch-to-buffer-other-window "*Org Links*")
9397 (with-current-buffer "*Org Links*"
9398 (erase-buffer)
9399 (insert "Insert a link.
9400 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9401 (when org-stored-links
9402 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9403 (insert (mapconcat 'org-link-prettify
9404 (reverse org-stored-links) "\n")))
9405 (goto-char (point-min)))
9406 (let ((cw (selected-window)))
9407 (select-window (get-buffer-window "*Org Links*" 'visible))
9408 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9409 (unless (pos-visible-in-window-p (point-max))
9410 (org-fit-window-to-buffer))
9411 (and (window-live-p cw) (select-window cw)))
9412 ;; Fake a link history, containing the stored links.
9413 (setq tmphist (append (mapcar 'car org-stored-links)
9414 org-insert-link-history))
9415 (setq all-prefixes (append (mapcar 'car abbrevs)
9416 (mapcar 'car org-link-abbrev-alist)
9417 org-link-types))
9418 (unwind-protect
9419 (progn
9420 (setq link
9421 (let ((org-completion-use-ido nil)
9422 (org-completion-use-iswitchb nil))
9423 (org-completing-read
9424 "Link: "
9425 (append
9426 (mapcar (lambda (x) (list (concat x ":")))
9427 all-prefixes)
9428 (mapcar 'car org-stored-links)
9429 (mapcar 'cadr org-stored-links))
9430 nil nil nil
9431 'tmphist
9432 (caar org-stored-links))))
9433 (if (not (string-match "\\S-" link))
9434 (error "No link selected"))
9435 (mapc (lambda(l)
9436 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9437 org-stored-links)
9438 (if (or (member link all-prefixes)
9439 (and (equal ":" (substring link -1))
9440 (member (substring link 0 -1) all-prefixes)
9441 (setq link (substring link 0 -1))))
9442 (setq link (org-link-try-special-completion link))))
9443 (set-window-configuration wcf)
9444 (kill-buffer "*Org Links*"))
9445 (setq entry (assoc link org-stored-links))
9446 (or entry (push link org-insert-link-history))
9447 (setq desc (or desc (nth 1 entry)))))
9449 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9450 (not org-keep-stored-link-after-insertion))
9451 (setq org-stored-links (delq (assoc link org-stored-links)
9452 org-stored-links)))
9454 (if (string-match org-plain-link-re link)
9455 ;; URL-like link, normalize the use of angular brackets.
9456 (setq link (org-remove-angle-brackets link)))
9458 ;; Check if we are linking to the current file with a search option
9459 ;; If yes, simplify the link by using only the search option.
9460 (when (and buffer-file-name
9461 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9462 (let* ((path (match-string 1 link))
9463 (case-fold-search nil)
9464 (search (match-string 2 link)))
9465 (save-match-data
9466 (if (equal (file-truename buffer-file-name) (file-truename path))
9467 ;; We are linking to this same file, with a search option
9468 (setq link search)))))
9470 ;; Check if we can/should use a relative path. If yes, simplify the link
9471 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9472 (let* ((type (match-string 1 link))
9473 (path (match-string 2 link))
9474 (origpath path)
9475 (case-fold-search nil))
9476 (cond
9477 ((or (eq org-link-file-path-type 'absolute)
9478 (equal complete-file '(16)))
9479 (setq path (abbreviate-file-name (expand-file-name path))))
9480 ((eq org-link-file-path-type 'noabbrev)
9481 (setq path (expand-file-name path)))
9482 ((eq org-link-file-path-type 'relative)
9483 (setq path (file-relative-name path)))
9485 (save-match-data
9486 (if (string-match (concat "^" (regexp-quote
9487 (expand-file-name
9488 (file-name-as-directory
9489 default-directory))))
9490 (expand-file-name path))
9491 ;; We are linking a file with relative path name.
9492 (setq path (substring (expand-file-name path)
9493 (match-end 0)))
9494 (setq path (abbreviate-file-name (expand-file-name path)))))))
9495 (setq link (concat type path))
9496 (if (equal desc origpath)
9497 (setq desc path))))
9499 (if org-make-link-description-function
9500 (setq desc
9501 (or (condition-case nil
9502 (funcall org-make-link-description-function link desc)
9503 (error (progn (message "Can't get link description from `%s'"
9504 (symbol-name org-make-link-description-function))
9505 (sit-for 2) nil)))
9506 (read-string "Description: " default-description)))
9507 (if default-description (setq desc default-description)
9508 (setq desc (or (and auto-desc desc)
9509 (read-string "Description: " desc)))))
9511 (unless (string-match "\\S-" desc) (setq desc nil))
9512 (if remove (apply 'delete-region remove))
9513 (insert (org-make-link-string link desc))))
9515 (defun org-link-try-special-completion (type)
9516 "If there is completion support for link type TYPE, offer it."
9517 (let ((fun (intern (concat "org-" type "-complete-link"))))
9518 (if (functionp fun)
9519 (funcall fun)
9520 (read-string "Link (no completion support): " (concat type ":")))))
9522 (defun org-file-complete-link (&optional arg)
9523 "Create a file link using completion."
9524 (let (file link)
9525 (setq file (read-file-name "File: "))
9526 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9527 (pwd1 (file-name-as-directory (abbreviate-file-name
9528 (expand-file-name ".")))))
9529 (cond
9530 ((equal arg '(16))
9531 (setq link (concat
9532 "file:"
9533 (abbreviate-file-name (expand-file-name file)))))
9534 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9535 (setq link (concat "file:" (match-string 1 file))))
9536 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9537 (expand-file-name file))
9538 (setq link (concat
9539 "file:" (match-string 1 (expand-file-name file)))))
9540 (t (setq link (concat "file:" file)))))
9541 link))
9543 (defun org-completing-read (&rest args)
9544 "Completing-read with SPACE being a normal character."
9545 (let ((enable-recursive-minibuffers t)
9546 (minibuffer-local-completion-map
9547 (copy-keymap minibuffer-local-completion-map)))
9548 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9549 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9550 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9551 (apply 'org-icompleting-read args)))
9553 (defun org-completing-read-no-i (&rest args)
9554 (let (org-completion-use-ido org-completion-use-iswitchb)
9555 (apply 'org-completing-read args)))
9557 (defun org-iswitchb-completing-read (prompt choices &rest args)
9558 "Use iswitch as a completing-read replacement to choose from choices.
9559 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9560 from."
9561 (let* ((iswitchb-use-virtual-buffers nil)
9562 (iswitchb-make-buflist-hook
9563 (lambda ()
9564 (setq iswitchb-temp-buflist choices))))
9565 (iswitchb-read-buffer prompt)))
9567 (defun org-icompleting-read (&rest args)
9568 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9569 (org-without-partial-completion
9570 (if (and org-completion-use-ido
9571 (fboundp 'ido-completing-read)
9572 (boundp 'ido-mode) ido-mode
9573 (listp (second args)))
9574 (let ((ido-enter-matching-directory nil))
9575 (apply 'ido-completing-read (concat (car args))
9576 (if (consp (car (nth 1 args)))
9577 (mapcar 'car (nth 1 args))
9578 (nth 1 args))
9579 (cddr args)))
9580 (if (and org-completion-use-iswitchb
9581 (boundp 'iswitchb-mode) iswitchb-mode
9582 (listp (second args)))
9583 (apply 'org-iswitchb-completing-read (concat (car args))
9584 (if (consp (car (nth 1 args)))
9585 (mapcar 'car (nth 1 args))
9586 (nth 1 args))
9587 (cddr args))
9588 (apply 'completing-read args)))))
9590 (defun org-extract-attributes (s)
9591 "Extract the attributes cookie from a string and set as text property."
9592 (let (a attr (start 0) key value)
9593 (save-match-data
9594 (when (string-match "{{\\([^}]+\\)}}$" s)
9595 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9596 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9597 (setq key (match-string 1 a) value (match-string 2 a)
9598 start (match-end 0)
9599 attr (plist-put attr (intern key) value))))
9600 (org-add-props s nil 'org-attr attr))
9603 (defun org-extract-attributes-from-string (tag)
9604 (let (key value attr)
9605 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9606 (setq key (match-string 1 tag) value (match-string 2 tag)
9607 tag (replace-match "" t t tag)
9608 attr (plist-put attr (intern key) value)))
9609 (cons tag attr)))
9611 (defun org-attributes-to-string (plist)
9612 "Format a property list into an HTML attribute list."
9613 (let ((s "") key value)
9614 (while plist
9615 (setq key (pop plist) value (pop plist))
9616 (and value
9617 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9620 ;;; Opening/following a link
9622 (defvar org-link-search-failed nil)
9624 (defvar org-open-link-functions nil
9625 "Hook for functions finding a plain text link.
9626 These functions must take a single argument, the link content.
9627 They will be called for links that look like [[link text][description]]
9628 when LINK TEXT does not have a protocol like \"http:\" and does not look
9629 like a filename (e.g. \"./blue.png\").
9631 These functions will be called *before* Org attempts to resolve the
9632 link by doing text searches in the current buffer - so if you want a
9633 link \"[[target]]\" to still find \"<<target>>\", your function should
9634 handle this as a special case.
9636 When the function does handle the link, it must return a non-nil value.
9637 If it decides that it is not responsible for this link, it must return
9638 nil to indicate that that Org-mode can continue with other options
9639 like exact and fuzzy text search.")
9641 (defun org-next-link ()
9642 "Move forward to the next link.
9643 If the link is in hidden text, expose it."
9644 (interactive)
9645 (when (and org-link-search-failed (eq this-command last-command))
9646 (goto-char (point-min))
9647 (message "Link search wrapped back to beginning of buffer"))
9648 (setq org-link-search-failed nil)
9649 (let* ((pos (point))
9650 (ct (org-context))
9651 (a (assoc :link ct)))
9652 (if a (goto-char (nth 2 a)))
9653 (if (re-search-forward org-any-link-re nil t)
9654 (progn
9655 (goto-char (match-beginning 0))
9656 (if (outline-invisible-p) (org-show-context)))
9657 (goto-char pos)
9658 (setq org-link-search-failed t)
9659 (error "No further link found"))))
9661 (defun org-previous-link ()
9662 "Move backward to the previous link.
9663 If the link is in hidden text, expose it."
9664 (interactive)
9665 (when (and org-link-search-failed (eq this-command last-command))
9666 (goto-char (point-max))
9667 (message "Link search wrapped back to end of buffer"))
9668 (setq org-link-search-failed nil)
9669 (let* ((pos (point))
9670 (ct (org-context))
9671 (a (assoc :link ct)))
9672 (if a (goto-char (nth 1 a)))
9673 (if (re-search-backward org-any-link-re nil t)
9674 (progn
9675 (goto-char (match-beginning 0))
9676 (if (outline-invisible-p) (org-show-context)))
9677 (goto-char pos)
9678 (setq org-link-search-failed t)
9679 (error "No further link found"))))
9681 (defun org-translate-link (s)
9682 "Translate a link string if a translation function has been defined."
9683 (if (and org-link-translation-function
9684 (fboundp org-link-translation-function)
9685 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9686 (progn
9687 (setq s (funcall org-link-translation-function
9688 (match-string 1 s) (match-string 2 s)))
9689 (concat (car s) ":" (cdr s)))
9692 (defun org-translate-link-from-planner (type path)
9693 "Translate a link from Emacs Planner syntax so that Org can follow it.
9694 This is still an experimental function, your mileage may vary."
9695 (cond
9696 ((member type '("http" "https" "news" "ftp"))
9697 ;; standard Internet links are the same.
9698 nil)
9699 ((and (equal type "irc") (string-match "^//" path))
9700 ;; Planner has two / at the beginning of an irc link, we have 1.
9701 ;; We should have zero, actually....
9702 (setq path (substring path 1)))
9703 ((and (equal type "lisp") (string-match "^/" path))
9704 ;; Planner has a slash, we do not.
9705 (setq type "elisp" path (substring path 1)))
9706 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9707 ;; A typical message link. Planner has the id after the final slash,
9708 ;; we separate it with a hash mark
9709 (setq path (concat (match-string 1 path) "#"
9710 (org-remove-angle-brackets (match-string 2 path)))))
9712 (cons type path))
9714 (defun org-find-file-at-mouse (ev)
9715 "Open file link or URL at mouse."
9716 (interactive "e")
9717 (mouse-set-point ev)
9718 (org-open-at-point 'in-emacs))
9720 (defun org-open-at-mouse (ev)
9721 "Open file link or URL at mouse.
9722 See the docstring of `org-open-file' for details."
9723 (interactive "e")
9724 (mouse-set-point ev)
9725 (if (eq major-mode 'org-agenda-mode)
9726 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9727 (org-open-at-point))
9729 (defvar org-window-config-before-follow-link nil
9730 "The window configuration before following a link.
9731 This is saved in case the need arises to restore it.")
9733 (defvar org-open-link-marker (make-marker)
9734 "Marker pointing to the location where `org-open-at-point; was called.")
9736 ;;;###autoload
9737 (defun org-open-at-point-global ()
9738 "Follow a link like Org-mode does.
9739 This command can be called in any mode to follow a link that has
9740 Org-mode syntax."
9741 (interactive)
9742 (org-run-like-in-org-mode 'org-open-at-point))
9744 ;;;###autoload
9745 (defun org-open-link-from-string (s &optional arg reference-buffer)
9746 "Open a link in the string S, as if it was in Org-mode."
9747 (interactive "sLink: \nP")
9748 (let ((reference-buffer (or reference-buffer (current-buffer))))
9749 (with-temp-buffer
9750 (let ((org-inhibit-startup (not reference-buffer)))
9751 (org-mode)
9752 (insert s)
9753 (goto-char (point-min))
9754 (when reference-buffer
9755 (setq org-link-abbrev-alist-local
9756 (with-current-buffer reference-buffer
9757 org-link-abbrev-alist-local)))
9758 (org-open-at-point arg reference-buffer)))))
9760 (defvar org-open-at-point-functions nil
9761 "Hook that is run when following a link at point.
9763 Functions in this hook must return t if they identify and follow
9764 a link at point. If they don't find anything interesting at point,
9765 they must return nil.")
9767 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9768 (defun org-open-at-point (&optional arg reference-buffer)
9769 "Open link at or after point.
9770 If there is no link at point, this function will search forward up to
9771 the end of the current line.
9772 Normally, files will be opened by an appropriate application. If the
9773 optional prefix argument ARG is non-nil, Emacs will visit the file.
9774 With a double prefix argument, try to open outside of Emacs, in the
9775 application the system uses for this file type."
9776 (interactive "P")
9777 ;; if in a code block, then open the block's results
9778 (unless (call-interactively #'org-babel-open-src-block-result)
9779 (org-load-modules-maybe)
9780 (move-marker org-open-link-marker (point))
9781 (setq org-window-config-before-follow-link (current-window-configuration))
9782 (org-remove-occur-highlights nil nil t)
9783 (cond
9784 ((and (org-at-heading-p)
9785 (not (org-at-timestamp-p t))
9786 (not (org-in-regexp
9787 (concat org-plain-link-re "\\|"
9788 org-bracket-link-regexp "\\|"
9789 org-angle-link-re "\\|"
9790 "[ \t]:[^ \t\n]+:[ \t]*$")))
9791 (not (get-text-property (point) 'org-linked-text)))
9792 (or (org-offer-links-in-entry arg)
9793 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9794 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9795 ((and (org-at-timestamp-p t)
9796 (not (org-in-regexp org-bracket-link-regexp)))
9797 (org-follow-timestamp-link))
9798 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9799 (not (org-in-regexp org-bracket-link-regexp)))
9800 (org-footnote-action))
9802 (let (type path link line search (pos (point)))
9803 (catch 'match
9804 (save-excursion
9805 (skip-chars-forward "^]\n\r")
9806 (when (org-in-regexp org-bracket-link-regexp 1)
9807 (setq link (org-extract-attributes
9808 (org-link-unescape (org-match-string-no-properties 1))))
9809 (while (string-match " *\n *" link)
9810 (setq link (replace-match " " t t link)))
9811 (setq link (org-link-expand-abbrev link))
9812 (cond
9813 ((or (file-name-absolute-p link)
9814 (string-match "^\\.\\.?/" link))
9815 (setq type "file" path link))
9816 ((string-match org-link-re-with-space3 link)
9817 (setq type (match-string 1 link) path (match-string 2 link)))
9818 ((string-match "^help:+\\(.+\\)" link)
9819 (setq type "help" path (match-string 1 link)))
9820 (t (setq type "thisfile" path link)))
9821 (throw 'match t)))
9823 (when (get-text-property (point) 'org-linked-text)
9824 (setq type "thisfile"
9825 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9826 (1+ (point)) (point))
9827 path (buffer-substring
9828 (or (previous-single-property-change pos 'org-linked-text)
9829 (point-min))
9830 (or (next-single-property-change pos 'org-linked-text)
9831 (point-max))))
9832 (throw 'match t))
9834 (save-excursion
9835 (when (or (org-in-regexp org-angle-link-re)
9836 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9837 (save-match-data (not (looking-back "\\[\\[")))))
9838 (setq type (match-string 1)
9839 path (org-link-unescape (match-string 2)))
9840 (throw 'match t)))
9841 (save-excursion
9842 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9843 (setq type "tags"
9844 path (match-string 1))
9845 (while (string-match ":" path)
9846 (setq path (replace-match "+" t t path)))
9847 (throw 'match t)))
9848 (when (org-in-regexp "<\\([^><\n]+\\)>")
9849 (setq type "tree-match"
9850 path (match-string 1))
9851 (throw 'match t)))
9852 (unless path
9853 (error "No link found"))
9855 ;; switch back to reference buffer
9856 ;; needed when if called in a temporary buffer through
9857 ;; org-open-link-from-string
9858 (with-current-buffer (or reference-buffer (current-buffer))
9860 ;; Remove any trailing spaces in path
9861 (if (string-match " +\\'" path)
9862 (setq path (replace-match "" t t path)))
9863 (if (and org-link-translation-function
9864 (fboundp org-link-translation-function))
9865 ;; Check if we need to translate the link
9866 (let ((tmp (funcall org-link-translation-function type path)))
9867 (setq type (car tmp) path (cdr tmp))))
9869 (cond
9871 ((assoc type org-link-protocols)
9872 (funcall (nth 1 (assoc type org-link-protocols)) path))
9874 ((equal type "help")
9875 (let ((f-or-v (intern path)))
9876 (cond ((fboundp f-or-v)
9877 (describe-function f-or-v))
9878 ((boundp f-or-v)
9879 (describe-variable f-or-v))
9880 (t (error "Not a known function or variable")))))
9882 ((equal type "mailto")
9883 (let ((cmd (car org-link-mailto-program))
9884 (args (cdr org-link-mailto-program)) args1
9885 (address path) (subject "") a)
9886 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9887 (setq address (match-string 1 path)
9888 subject (org-link-escape (match-string 2 path))))
9889 (while args
9890 (cond
9891 ((not (stringp (car args))) (push (pop args) args1))
9892 (t (setq a (pop args))
9893 (if (string-match "%a" a)
9894 (setq a (replace-match address t t a)))
9895 (if (string-match "%s" a)
9896 (setq a (replace-match subject t t a)))
9897 (push a args1))))
9898 (apply cmd (nreverse args1))))
9900 ((member type '("http" "https" "ftp" "news"))
9901 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9902 (org-link-escape
9903 path org-link-escape-chars-browser)
9904 path))))
9906 ((string= type "doi")
9907 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9908 (org-link-escape
9909 path org-link-escape-chars-browser)
9910 path))))
9912 ((member type '("message"))
9913 (browse-url (concat type ":" path)))
9915 ((string= type "tags")
9916 (org-tags-view arg path))
9918 ((string= type "tree-match")
9919 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9921 ((string= type "file")
9922 (if (string-match "::\\([0-9]+\\)\\'" path)
9923 (setq line (string-to-number (match-string 1 path))
9924 path (substring path 0 (match-beginning 0)))
9925 (if (string-match "::\\(.+\\)\\'" path)
9926 (setq search (match-string 1 path)
9927 path (substring path 0 (match-beginning 0)))))
9928 (if (string-match "[*?{]" (file-name-nondirectory path))
9929 (dired path)
9930 (org-open-file path arg line search)))
9932 ((string= type "shell")
9933 (let ((buf (generate-new-buffer "*Org Shell Output"))
9934 (cmd path))
9935 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9936 (string-match org-confirm-shell-link-not-regexp cmd))
9937 (not org-confirm-shell-link-function)
9938 (funcall org-confirm-shell-link-function
9939 (format "Execute \"%s\" in shell? "
9940 (org-add-props cmd nil
9941 'face 'org-warning))))
9942 (progn
9943 (message "Executing %s" cmd)
9944 (shell-command cmd buf)
9945 (if (featurep 'midnight)
9946 (setq clean-buffer-list-kill-buffer-names
9947 (cons buf clean-buffer-list-kill-buffer-names))))
9948 (error "Abort"))))
9950 ((string= type "elisp")
9951 (let ((cmd path))
9952 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9953 (string-match org-confirm-elisp-link-not-regexp cmd))
9954 (not org-confirm-elisp-link-function)
9955 (funcall org-confirm-elisp-link-function
9956 (format "Execute \"%s\" as elisp? "
9957 (org-add-props cmd nil
9958 'face 'org-warning))))
9959 (message "%s => %s" cmd
9960 (if (equal (string-to-char cmd) ?\()
9961 (eval (read cmd))
9962 (call-interactively (read cmd))))
9963 (error "Abort"))))
9965 ((and (string= type "thisfile")
9966 (run-hook-with-args-until-success
9967 'org-open-link-functions path)))
9969 ((string= type "thisfile")
9970 (if arg
9971 (switch-to-buffer-other-window
9972 (org-get-buffer-for-internal-link (current-buffer)))
9973 (org-mark-ring-push))
9974 (let ((cmd `(org-link-search
9975 ,path
9976 ,(cond ((equal arg '(4)) ''occur)
9977 ((equal arg '(16)) ''org-occur))
9978 ,pos)))
9979 (condition-case nil (let ((org-link-search-inhibit-query t))
9980 (eval cmd))
9981 (error (progn (widen) (eval cmd))))))
9983 (t (browse-url-at-point)))))))
9984 (move-marker org-open-link-marker nil)
9985 (run-hook-with-args 'org-follow-link-hook)))
9987 (defun org-offer-links-in-entry (&optional nth zero)
9988 "Offer links in the current entry and follow the selected link.
9989 If there is only one link, follow it immediately as well.
9990 If NTH is an integer, immediately pick the NTH link found.
9991 If ZERO is a string, check also this string for a link, and if
9992 there is one, offer it as link number zero."
9993 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9994 "\\(" org-angle-link-re "\\)\\|"
9995 "\\(" org-plain-link-re "\\)"))
9996 (cnt ?0)
9997 (in-emacs (if (integerp nth) nil nth))
9998 have-zero end links link c)
9999 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10000 (push (match-string 0 zero) links)
10001 (setq cnt (1- cnt) have-zero t))
10002 (save-excursion
10003 (org-back-to-heading t)
10004 (setq end (save-excursion (outline-next-heading) (point)))
10005 (while (re-search-forward re end t)
10006 (push (match-string 0) links))
10007 (setq links (org-uniquify (reverse links))))
10009 (cond
10010 ((null links)
10011 (message "No links"))
10012 ((equal (length links) 1)
10013 (setq link (list (car links))))
10014 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10015 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10016 (t ; we have to select a link
10017 (save-excursion
10018 (save-window-excursion
10019 (delete-other-windows)
10020 (with-output-to-temp-buffer "*Select Link*"
10021 (mapc (lambda (l)
10022 (if (not (string-match org-bracket-link-regexp l))
10023 (princ (format "[%c] %s\n" (incf cnt)
10024 (org-remove-angle-brackets l)))
10025 (if (match-end 3)
10026 (princ (format "[%c] %s (%s)\n" (incf cnt)
10027 (match-string 3 l) (match-string 1 l)))
10028 (princ (format "[%c] %s\n" (incf cnt)
10029 (match-string 1 l))))))
10030 links))
10031 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10032 (message "Select link to open, RET to open all:")
10033 (setq c (read-char-exclusive))
10034 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10035 (when (equal c ?q) (error "Abort"))
10036 (if (equal c ?\C-m)
10037 (setq link links)
10038 (setq nth (- c ?0))
10039 (if have-zero (setq nth (1+ nth)))
10040 (unless (and (integerp nth) (>= (length links) nth))
10041 (error "Invalid link selection"))
10042 (setq link (list (nth (1- nth) links))))))
10043 (if link
10044 (let ((buf (current-buffer)))
10045 (dolist (l link)
10046 (org-open-link-from-string l in-emacs buf))
10048 nil)))
10050 ;; Add special file links that specify the way of opening
10052 (org-add-link-type "file+sys" 'org-open-file-with-system)
10053 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10054 (defun org-open-file-with-system (path)
10055 "Open file at PATH using the system way of opening it."
10056 (org-open-file path 'system))
10057 (defun org-open-file-with-emacs (path)
10058 "Open file at PATH in Emacs."
10059 (org-open-file path 'emacs))
10060 (defun org-remove-file-link-modifiers ()
10061 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10062 (goto-char (point-min))
10063 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10064 (org-if-unprotected
10065 (replace-match "file:" t t))))
10066 (eval-after-load "org-exp"
10067 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10068 'org-remove-file-link-modifiers))
10070 ;;;; Time estimates
10072 (defun org-get-effort (&optional pom)
10073 "Get the effort estimate for the current entry."
10074 (org-entry-get pom org-effort-property))
10076 ;;; File search
10078 (defvar org-create-file-search-functions nil
10079 "List of functions to construct the right search string for a file link.
10080 These functions are called in turn with point at the location to
10081 which the link should point.
10083 A function in the hook should first test if it would like to
10084 handle this file type, for example by checking the `major-mode'
10085 or the file extension. If it decides not to handle this file, it
10086 should just return nil to give other functions a chance. If it
10087 does handle the file, it must return the search string to be used
10088 when following the link. The search string will be part of the
10089 file link, given after a double colon, and `org-open-at-point'
10090 will automatically search for it. If special measures must be
10091 taken to make the search successful, another function should be
10092 added to the companion hook `org-execute-file-search-functions',
10093 which see.
10095 A function in this hook may also use `setq' to set the variable
10096 `description' to provide a suggestion for the descriptive text to
10097 be used for this link when it gets inserted into an Org-mode
10098 buffer with \\[org-insert-link].")
10100 (defvar org-execute-file-search-functions nil
10101 "List of functions to execute a file search triggered by a link.
10103 Functions added to this hook must accept a single argument, the
10104 search string that was part of the file link, the part after the
10105 double colon. The function must first check if it would like to
10106 handle this search, for example by checking the `major-mode' or
10107 the file extension. If it decides not to handle this search, it
10108 should just return nil to give other functions a chance. If it
10109 does handle the search, it must return a non-nil value to keep
10110 other functions from trying.
10112 Each function can access the current prefix argument through the
10113 variable `current-prefix-argument'. Note that a single prefix is
10114 used to force opening a link in Emacs, so it may be good to only
10115 use a numeric or double prefix to guide the search function.
10117 In case this is needed, a function in this hook can also restore
10118 the window configuration before `org-open-at-point' was called using:
10120 (set-window-configuration org-window-config-before-follow-link)")
10122 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10123 (defun org-link-search (s &optional type avoid-pos stealth)
10124 "Search for a link search option.
10125 If S is surrounded by forward slashes, it is interpreted as a
10126 regular expression. In org-mode files, this will create an `org-occur'
10127 sparse tree. In ordinary files, `occur' will be used to list matches.
10128 If the current buffer is in `dired-mode', grep will be used to search
10129 in all files. If AVOID-POS is given, ignore matches near that position.
10131 When optional argument STEALTH is non-nil, do not modify
10132 visibility around point, thus ignoring
10133 `org-show-hierarchy-above', `org-show-following-heading' and
10134 `org-show-siblings' variables."
10135 (let ((case-fold-search t)
10136 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10137 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10138 (append '(("") (" ") ("\t") ("\n"))
10139 org-emphasis-alist)
10140 "\\|") "\\)"))
10141 (pos (point))
10142 (pre nil) (post nil)
10143 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10144 (cond
10145 ;; First check if there are any special search functions
10146 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10147 ;; Now try the builtin stuff
10148 ((and (equal (string-to-char s0) ?#)
10149 (> (length s0) 1)
10150 (save-excursion
10151 (goto-char (point-min))
10152 (and
10153 (re-search-forward
10154 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10155 (setq type 'dedicated
10156 pos (match-beginning 0))))
10157 ;; There is an exact target for this
10158 (goto-char pos)
10159 (org-back-to-heading t)))
10160 ((save-excursion
10161 (goto-char (point-min))
10162 (and
10163 (re-search-forward
10164 (concat "<<" (regexp-quote s0) ">>") nil t)
10165 (setq type 'dedicated
10166 pos (match-beginning 0))))
10167 ;; There is an exact target for this
10168 (goto-char pos))
10169 ((save-excursion
10170 (goto-char (point-min))
10171 (and
10172 (re-search-forward
10173 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10174 (setq type 'dedicated pos (match-beginning 0))))
10175 ;; Found an invisible target.
10176 (goto-char pos))
10177 ((save-excursion
10178 (goto-char (point-min))
10179 (and
10180 (re-search-forward
10181 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10182 (setq type 'dedicated pos (match-beginning 0))))
10183 ;; Found an element with a matching #+name affiliated keyword.
10184 (goto-char pos))
10185 ((and (string-match "^(\\(.*\\))$" s0)
10186 (save-excursion
10187 (goto-char (point-min))
10188 (and
10189 (re-search-forward
10190 (concat "[^[]" (regexp-quote
10191 (format org-coderef-label-format
10192 (match-string 1 s0))))
10193 nil t)
10194 (setq type 'dedicated
10195 pos (1+ (match-beginning 0))))))
10196 ;; There is a coderef target for this
10197 (goto-char pos))
10198 ((string-match "^/\\(.*\\)/$" s)
10199 ;; A regular expression
10200 (cond
10201 ((derived-mode-p 'org-mode)
10202 (org-occur (match-string 1 s)))
10203 ;;((eq major-mode 'dired-mode)
10204 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10205 (t (org-do-occur (match-string 1 s)))))
10206 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10207 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10208 (goto-char (point-min))
10209 (cond
10210 ((let (case-fold-search)
10211 (re-search-forward (format org-complex-heading-regexp-format
10212 (regexp-quote s))
10213 nil t))
10214 ;; OK, found a match
10215 (setq type 'dedicated)
10216 (goto-char (match-beginning 0)))
10217 ((and (not org-link-search-inhibit-query)
10218 (eq org-link-search-must-match-exact-headline 'query-to-create)
10219 (y-or-n-p "No match - create this as a new heading? "))
10220 (goto-char (point-max))
10221 (or (bolp) (newline))
10222 (insert "* " s "\n")
10223 (beginning-of-line 0))
10225 (goto-char pos)
10226 (error "No match"))))
10228 ;; A normal search string
10229 (when (equal (string-to-char s) ?*)
10230 ;; Anchor on headlines, post may include tags.
10231 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10232 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10233 s (substring s 1)))
10234 (remove-text-properties
10235 0 (length s)
10236 '(face nil mouse-face nil keymap nil fontified nil) s)
10237 ;; Make a series of regular expressions to find a match
10238 (setq words (org-split-string s "[ \n\r\t]+")
10240 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10241 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10242 "\\)" markers)
10243 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10244 re2a (concat "[ \t\r\n]" re2a_)
10245 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10246 re4 (concat "[^a-zA-Z_]" re4_)
10248 re1 (concat pre re2 post)
10249 re3 (concat pre (if pre re4_ re4) post)
10250 re5 (concat pre ".*" re4)
10251 re2 (concat pre re2)
10252 re2a (concat pre (if pre re2a_ re2a))
10253 re4 (concat pre (if pre re4_ re4))
10254 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10255 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10256 re5 "\\)"
10258 (cond
10259 ((eq type 'org-occur) (org-occur reall))
10260 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10261 (t (goto-char (point-min))
10262 (setq type 'fuzzy)
10263 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10264 (org-search-not-self 1 re1 nil t)
10265 (org-search-not-self 1 re2 nil t)
10266 (org-search-not-self 1 re2a nil t)
10267 (org-search-not-self 1 re3 nil t)
10268 (org-search-not-self 1 re4 nil t)
10269 (org-search-not-self 1 re5 nil t)
10271 (goto-char (match-beginning 1))
10272 (goto-char pos)
10273 (error "No match"))))))
10274 (and (derived-mode-p 'org-mode)
10275 (not stealth)
10276 (org-show-context 'link-search))
10277 type))
10279 (defun org-search-not-self (group &rest args)
10280 "Execute `re-search-forward', but only accept matches that do not
10281 enclose the position of `org-open-link-marker'."
10282 (let ((m org-open-link-marker))
10283 (catch 'exit
10284 (while (apply 're-search-forward args)
10285 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10286 (goto-char (match-end group))
10287 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10288 (> (match-beginning 0) (marker-position m))
10289 (< (match-end 0) (marker-position m)))
10290 (save-match-data
10291 (or (not (org-in-regexp
10292 org-bracket-link-analytic-regexp 1))
10293 (not (match-end 4)) ; no description
10294 (and (<= (match-beginning 4) (point))
10295 (>= (match-end 4) (point))))))
10296 (throw 'exit (point))))))))
10298 (defun org-get-buffer-for-internal-link (buffer)
10299 "Return a buffer to be used for displaying the link target of internal links."
10300 (cond
10301 ((not org-display-internal-link-with-indirect-buffer)
10302 buffer)
10303 ((string-match "(Clone)$" (buffer-name buffer))
10304 (message "Buffer is already a clone, not making another one")
10305 ;; we also do not modify visibility in this case
10306 buffer)
10307 (t ; make a new indirect buffer for displaying the link
10308 (let* ((bn (buffer-name buffer))
10309 (ibn (concat bn "(Clone)"))
10310 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10311 (with-current-buffer ib (org-overview))
10312 ib))))
10314 (defun org-do-occur (regexp &optional cleanup)
10315 "Call the Emacs command `occur'.
10316 If CLEANUP is non-nil, remove the printout of the regular expression
10317 in the *Occur* buffer. This is useful if the regex is long and not useful
10318 to read."
10319 (occur regexp)
10320 (when cleanup
10321 (let ((cwin (selected-window)) win beg end)
10322 (when (setq win (get-buffer-window "*Occur*"))
10323 (select-window win))
10324 (goto-char (point-min))
10325 (when (re-search-forward "match[a-z]+" nil t)
10326 (setq beg (match-end 0))
10327 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10328 (setq end (1- (match-beginning 0)))))
10329 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10330 (goto-char (point-min))
10331 (select-window cwin))))
10333 ;;; The mark ring for links jumps
10335 (defvar org-mark-ring nil
10336 "Mark ring for positions before jumps in Org-mode.")
10337 (defvar org-mark-ring-last-goto nil
10338 "Last position in the mark ring used to go back.")
10339 ;; Fill and close the ring
10340 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10341 (loop for i from 1 to org-mark-ring-length do
10342 (push (make-marker) org-mark-ring))
10343 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10344 org-mark-ring)
10346 (defun org-mark-ring-push (&optional pos buffer)
10347 "Put the current position or POS into the mark ring and rotate it."
10348 (interactive)
10349 (setq pos (or pos (point)))
10350 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10351 (move-marker (car org-mark-ring)
10352 (or pos (point))
10353 (or buffer (current-buffer)))
10354 (message "%s"
10355 (substitute-command-keys
10356 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10358 (defun org-mark-ring-goto (&optional n)
10359 "Jump to the previous position in the mark ring.
10360 With prefix arg N, jump back that many stored positions. When
10361 called several times in succession, walk through the entire ring.
10362 Org-mode commands jumping to a different position in the current file,
10363 or to another Org-mode file, automatically push the old position
10364 onto the ring."
10365 (interactive "p")
10366 (let (p m)
10367 (if (eq last-command this-command)
10368 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10369 (setq p org-mark-ring))
10370 (setq org-mark-ring-last-goto p)
10371 (setq m (car p))
10372 (org-pop-to-buffer-same-window (marker-buffer m))
10373 (goto-char m)
10374 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10376 (defun org-remove-angle-brackets (s)
10377 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10378 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10380 (defun org-add-angle-brackets (s)
10381 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10382 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10384 (defun org-remove-double-quotes (s)
10385 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10386 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10389 ;;; Following specific links
10391 (defun org-follow-timestamp-link ()
10392 "Open an agenda view for the time-stamp date/range at point."
10393 (cond
10394 ((org-at-date-range-p t)
10395 (let ((org-agenda-start-on-weekday)
10396 (t1 (match-string 1))
10397 (t2 (match-string 2)) tt1 tt2)
10398 (setq tt1 (time-to-days (org-time-string-to-time t1))
10399 tt2 (time-to-days (org-time-string-to-time t2)))
10400 (let ((org-agenda-buffer-tmp-name
10401 (format "*Org Agenda(a:%s)"
10402 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10403 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10404 ((org-at-timestamp-p t)
10405 (let ((org-agenda-buffer-tmp-name
10406 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10407 (org-agenda-list nil (time-to-days (org-time-string-to-time
10408 (substring (match-string 1) 0 10)))
10409 1)))
10410 (t (error "This should not happen"))))
10413 ;;; Following file links
10414 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10415 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10416 (declare-function mailcap-mime-info
10417 "mailcap" (string &optional request no-decode))
10418 (defvar org-wait nil)
10419 (defun org-open-file (path &optional in-emacs line search)
10420 "Open the file at PATH.
10421 First, this expands any special file name abbreviations. Then the
10422 configuration variable `org-file-apps' is checked if it contains an
10423 entry for this file type, and if yes, the corresponding command is launched.
10425 If no application is found, Emacs simply visits the file.
10427 With optional prefix argument IN-EMACS, Emacs will visit the file.
10428 With a double \\[universal-argument] \\[universal-argument] \
10429 prefix arg, Org tries to avoid opening in Emacs
10430 and to use an external application to visit the file.
10432 Optional LINE specifies a line to go to, optional SEARCH a string
10433 to search for. If LINE or SEARCH is given, the file will be
10434 opened in Emacs, unless an entry from org-file-apps that makes
10435 use of groups in a regexp matches.
10437 If you want to change the way frames are used when following a
10438 link, please customize `org-link-frame-setup'.
10440 If the file does not exist, an error is thrown."
10441 (let* ((file (if (equal path "")
10442 buffer-file-name
10443 (substitute-in-file-name (expand-file-name path))))
10444 (file-apps (append org-file-apps (org-default-apps)))
10445 (apps (org-remove-if
10446 'org-file-apps-entry-match-against-dlink-p file-apps))
10447 (apps-dlink (org-remove-if-not
10448 'org-file-apps-entry-match-against-dlink-p file-apps))
10449 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10450 (dirp (if remp nil (file-directory-p file)))
10451 (file (if (and dirp org-open-directory-means-index-dot-org)
10452 (concat (file-name-as-directory file) "index.org")
10453 file))
10454 (a-m-a-p (assq 'auto-mode apps))
10455 (dfile (downcase file))
10456 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10457 (link (cond ((and (eq line nil)
10458 (eq search nil))
10459 file)
10460 (line
10461 (concat file "::" (number-to-string line)))
10462 (search
10463 (concat file "::" search))))
10464 (dlink (downcase link))
10465 (old-buffer (current-buffer))
10466 (old-pos (point))
10467 (old-mode major-mode)
10468 ext cmd link-match-data)
10469 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10470 (setq ext (match-string 1 dfile))
10471 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10472 (setq ext (match-string 1 dfile))))
10473 (cond
10474 ((member in-emacs '((16) system))
10475 (setq cmd (cdr (assoc 'system apps))))
10476 (in-emacs (setq cmd 'emacs))
10478 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10479 (and dirp (cdr (assoc 'directory apps)))
10480 ; first, try matching against apps-dlink
10481 ; if we get a match here, store the match data for later
10482 (let ((match (assoc-default dlink apps-dlink
10483 'string-match)))
10484 (if match
10485 (progn (setq link-match-data (match-data))
10486 match)
10487 (progn (setq in-emacs (or in-emacs line search))
10488 nil))) ; if we have no match in apps-dlink,
10489 ; always open the file in emacs if line or search
10490 ; is given (for backwards compatibility)
10491 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10492 'string-match)
10493 (cdr (assoc ext apps))
10494 (cdr (assoc t apps))))))
10495 (when (eq cmd 'system)
10496 (setq cmd (cdr (assoc 'system apps))))
10497 (when (eq cmd 'default)
10498 (setq cmd (cdr (assoc t apps))))
10499 (when (eq cmd 'mailcap)
10500 (require 'mailcap)
10501 (mailcap-parse-mailcaps)
10502 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10503 (command (mailcap-mime-info mime-type)))
10504 (if (stringp command)
10505 (setq cmd command)
10506 (setq cmd 'emacs))))
10507 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10508 (not (file-exists-p file))
10509 (not org-open-non-existing-files))
10510 (error "No such file: %s" file))
10511 (cond
10512 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10513 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10514 (while (string-match "['\"]%s['\"]" cmd)
10515 (setq cmd (replace-match "%s" t t cmd)))
10516 (while (string-match "%s" cmd)
10517 (setq cmd (replace-match
10518 (save-match-data
10519 (shell-quote-argument
10520 (convert-standard-filename file)))
10521 t t cmd)))
10523 ;; Replace "%1", "%2" etc. in command with group matches from regex
10524 (save-match-data
10525 (let ((match-index 1)
10526 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10527 (set-match-data link-match-data)
10528 (while (<= match-index number-of-groups)
10529 (let ((regex (concat "%" (number-to-string match-index)))
10530 (replace-with (match-string match-index dlink)))
10531 (while (string-match regex cmd)
10532 (setq cmd (replace-match replace-with t t cmd))))
10533 (setq match-index (+ match-index 1)))))
10535 (save-window-excursion
10536 (start-process-shell-command cmd nil cmd)
10537 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10539 ((or (stringp cmd)
10540 (eq cmd 'emacs))
10541 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10542 (widen)
10543 (if line (org-goto-line line)
10544 (if search (org-link-search search))))
10545 ((consp cmd)
10546 (let ((file (convert-standard-filename file)))
10547 (save-match-data
10548 (set-match-data link-match-data)
10549 (eval cmd))))
10550 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10551 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10552 (or (not (equal old-buffer (current-buffer)))
10553 (not (equal old-pos (point))))
10554 (org-mark-ring-push old-pos old-buffer))))
10556 (defun org-file-apps-entry-match-against-dlink-p (entry)
10557 "This function returns non-nil if `entry' uses a regular
10558 expression which should be matched against the whole link by
10559 org-open-file.
10561 It assumes that is the case when the entry uses a regular
10562 expression which has at least one grouping construct and the
10563 action is either a lisp form or a command string containing
10564 '%1', i.e. using at least one subexpression match as a
10565 parameter."
10566 (let ((selector (car entry))
10567 (action (cdr entry)))
10568 (if (stringp selector)
10569 (and (> (regexp-opt-depth selector) 0)
10570 (or (and (stringp action)
10571 (string-match "%[0-9]" action))
10572 (consp action)))
10573 nil)))
10575 (defun org-default-apps ()
10576 "Return the default applications for this operating system."
10577 (cond
10578 ((eq system-type 'darwin)
10579 org-file-apps-defaults-macosx)
10580 ((eq system-type 'windows-nt)
10581 org-file-apps-defaults-windowsnt)
10582 (t org-file-apps-defaults-gnu)))
10584 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10585 "Convert extensions to regular expressions in the cars of LIST.
10586 Also, weed out any non-string entries, because the return value is used
10587 only for regexp matching.
10588 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10589 point to the symbol `emacs', indicating that the file should
10590 be opened in Emacs."
10591 (append
10592 (delq nil
10593 (mapcar (lambda (x)
10594 (if (not (stringp (car x)))
10596 (if (string-match "\\W" (car x))
10598 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10599 list))
10600 (if add-auto-mode
10601 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10603 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10604 (defun org-file-remote-p (file)
10605 "Test whether FILE specifies a location on a remote system.
10606 Return non-nil if the location is indeed remote.
10608 For example, the filename \"/user@host:/foo\" specifies a location
10609 on the system \"/user@host:\"."
10610 (cond ((fboundp 'file-remote-p)
10611 (file-remote-p file))
10612 ((fboundp 'tramp-handle-file-remote-p)
10613 (tramp-handle-file-remote-p file))
10614 ((and (boundp 'ange-ftp-name-format)
10615 (string-match (car ange-ftp-name-format) file))
10616 t)))
10619 ;;;; Refiling
10621 (defun org-get-org-file ()
10622 "Read a filename, with default directory `org-directory'."
10623 (let ((default (or org-default-notes-file remember-data-file)))
10624 (read-file-name (format "File name [%s]: " default)
10625 (file-name-as-directory org-directory)
10626 default)))
10628 (defun org-notes-order-reversed-p ()
10629 "Check if the current file should receive notes in reversed order."
10630 (cond
10631 ((not org-reverse-note-order) nil)
10632 ((eq t org-reverse-note-order) t)
10633 ((not (listp org-reverse-note-order)) nil)
10634 (t (catch 'exit
10635 (let ((all org-reverse-note-order)
10636 entry)
10637 (while (setq entry (pop all))
10638 (if (string-match (car entry) buffer-file-name)
10639 (throw 'exit (cdr entry))))
10640 nil)))))
10642 (defvar org-refile-target-table nil
10643 "The list of refile targets, created by `org-refile'.")
10645 (defvar org-agenda-new-buffers nil
10646 "Buffers created to visit agenda files.")
10648 (defvar org-refile-cache nil
10649 "Cache for refile targets.")
10651 (defvar org-refile-markers nil
10652 "All the markers used for caching refile locations.")
10654 (defun org-refile-marker (pos)
10655 "Get a new refile marker, but only if caching is in use."
10656 (if (not org-refile-use-cache)
10658 (let ((m (make-marker)))
10659 (move-marker m pos)
10660 (push m org-refile-markers)
10661 m)))
10663 (defun org-refile-cache-clear ()
10664 "Clear the refile cache and disable all the markers."
10665 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10666 (setq org-refile-markers nil)
10667 (setq org-refile-cache nil)
10668 (message "Refile cache has been cleared"))
10670 (defun org-refile-cache-check-set (set)
10671 "Check if all the markers in the cache still have live buffers."
10672 (let (marker)
10673 (catch 'exit
10674 (while (and set (setq marker (nth 3 (pop set))))
10675 ;; if org-refile-use-outline-path is 'file, marker may be nil
10676 (when (and marker (null (marker-buffer marker)))
10677 (message "not found") (sit-for 3)
10678 (throw 'exit nil)))
10679 t)))
10681 (defun org-refile-cache-put (set &rest identifiers)
10682 "Push the refile targets SET into the cache, under IDENTIFIERS."
10683 (let* ((key (sha1 (prin1-to-string identifiers)))
10684 (entry (assoc key org-refile-cache)))
10685 (if entry
10686 (setcdr entry set)
10687 (push (cons key set) org-refile-cache))))
10689 (defun org-refile-cache-get (&rest identifiers)
10690 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10691 (cond
10692 ((not org-refile-cache) nil)
10693 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10695 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10696 org-refile-cache))))
10697 (and set (org-refile-cache-check-set set) set)))))
10699 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10700 "Produce a table with refile targets."
10701 (let ((case-fold-search nil)
10702 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10703 (entries (or org-refile-targets '((nil . (:level . 1)))))
10704 targets tgs txt re files f desc descre fast-path-p level pos0)
10705 (message "Getting targets...")
10706 (with-current-buffer (or default-buffer (current-buffer))
10707 (while (setq entry (pop entries))
10708 (setq files (car entry) desc (cdr entry))
10709 (setq fast-path-p nil)
10710 (cond
10711 ((null files) (setq files (list (current-buffer))))
10712 ((eq files 'org-agenda-files)
10713 (setq files (org-agenda-files 'unrestricted)))
10714 ((and (symbolp files) (fboundp files))
10715 (setq files (funcall files)))
10716 ((and (symbolp files) (boundp files))
10717 (setq files (symbol-value files))))
10718 (if (stringp files) (setq files (list files)))
10719 (cond
10720 ((eq (car desc) :tag)
10721 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10722 ((eq (car desc) :todo)
10723 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10724 ((eq (car desc) :regexp)
10725 (setq descre (cdr desc)))
10726 ((eq (car desc) :level)
10727 (setq descre (concat "^\\*\\{" (number-to-string
10728 (if org-odd-levels-only
10729 (1- (* 2 (cdr desc)))
10730 (cdr desc)))
10731 "\\}[ \t]")))
10732 ((eq (car desc) :maxlevel)
10733 (setq fast-path-p t)
10734 (setq descre (concat "^\\*\\{1," (number-to-string
10735 (if org-odd-levels-only
10736 (1- (* 2 (cdr desc)))
10737 (cdr desc)))
10738 "\\}[ \t]")))
10739 (t (error "Bad refiling target description %s" desc)))
10740 (while (setq f (pop files))
10741 (with-current-buffer
10742 (if (bufferp f) f (org-get-agenda-file-buffer f))
10744 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10745 (progn
10746 (if (bufferp f) (setq f (buffer-file-name
10747 (buffer-base-buffer f))))
10748 (setq f (and f (expand-file-name f)))
10749 (if (eq org-refile-use-outline-path 'file)
10750 (push (list (file-name-nondirectory f) f nil nil) tgs))
10751 (save-excursion
10752 (save-restriction
10753 (widen)
10754 (goto-char (point-min))
10755 (while (re-search-forward descre nil t)
10756 (goto-char (setq pos0 (point-at-bol)))
10757 (catch 'next
10758 (when org-refile-target-verify-function
10759 (save-match-data
10760 (or (funcall org-refile-target-verify-function)
10761 (throw 'next t))))
10762 (when (and (looking-at org-complex-heading-regexp)
10763 (not (member (match-string 4) excluded-entries))
10764 (match-string 4))
10765 (setq level (org-reduced-level
10766 (- (match-end 1) (match-beginning 1)))
10767 txt (org-link-display-format (match-string 4))
10768 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10769 re (format org-complex-heading-regexp-format
10770 (regexp-quote (match-string 4))))
10771 (when org-refile-use-outline-path
10772 (setq txt (mapconcat
10773 'org-protect-slash
10774 (append
10775 (if (eq org-refile-use-outline-path
10776 'file)
10777 (list (file-name-nondirectory
10778 (buffer-file-name
10779 (buffer-base-buffer))))
10780 (if (eq org-refile-use-outline-path
10781 'full-file-path)
10782 (list (buffer-file-name
10783 (buffer-base-buffer)))))
10784 (org-get-outline-path fast-path-p
10785 level txt)
10786 (list txt))
10787 "/")))
10788 (push (list txt f re (org-refile-marker (point)))
10789 tgs)))
10790 (when (= (point) pos0)
10791 ;; verification function has not moved point
10792 (goto-char (point-at-eol))))))))
10793 (when org-refile-use-cache
10794 (org-refile-cache-put tgs (buffer-file-name) descre))
10795 (setq targets (append tgs targets))
10796 ))))
10797 (message "Getting targets...done")
10798 (nreverse targets)))
10800 (defun org-protect-slash (s)
10801 (while (string-match "/" s)
10802 (setq s (replace-match "\\" t t s)))
10805 (defvar org-olpa (make-vector 20 nil))
10807 (defun org-get-outline-path (&optional fastp level heading)
10808 "Return the outline path to the current entry, as a list.
10810 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10811 routine which makes outline path derivations for an entire file,
10812 avoiding backtracing. Refile target collection makes use of that."
10813 (if fastp
10814 (progn
10815 (if (> level 19)
10816 (error "Outline path failure, more than 19 levels"))
10817 (loop for i from level upto 19 do
10818 (aset org-olpa i nil))
10819 (prog1
10820 (delq nil (append org-olpa nil))
10821 (aset org-olpa level heading)))
10822 (let (rtn case-fold-search)
10823 (save-excursion
10824 (save-restriction
10825 (widen)
10826 (while (org-up-heading-safe)
10827 (when (looking-at org-complex-heading-regexp)
10828 (push (org-match-string-no-properties 4) rtn)))
10829 rtn)))))
10831 (defun org-format-outline-path (path &optional width prefix)
10832 "Format the outline path PATH for display.
10833 Width is the maximum number of characters that is available.
10834 Prefix is a prefix to be included in the returned string,
10835 such as the file name."
10836 (setq width (or width 79))
10837 (if prefix (setq width (- width (length prefix))))
10838 (if (not path)
10839 (or prefix "")
10840 (let* ((nsteps (length path))
10841 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10842 (maxwidth (if (<= total-width width)
10843 10000 ;; everything fits
10844 ;; we need to shorten the level headings
10845 (/ (- width nsteps) nsteps)))
10846 (org-odd-levels-only nil)
10847 (n 0)
10848 (total (1+ (length prefix))))
10849 (setq maxwidth (max maxwidth 10))
10850 (concat prefix
10851 (mapconcat
10852 (lambda (h)
10853 (setq n (1+ n))
10854 (if (and (= n nsteps) (< maxwidth 10000))
10855 (setq maxwidth (- total-width total)))
10856 (if (< (length h) maxwidth)
10857 (progn (setq total (+ total (length h) 1)) h)
10858 (setq h (substring h 0 (- maxwidth 2))
10859 total (+ total maxwidth 1))
10860 (if (string-match "[ \t]+\\'" h)
10861 (setq h (substring h 0 (match-beginning 0))))
10862 (setq h (concat h "..")))
10863 (org-add-props h nil 'face
10864 (nth (% (1- n) org-n-level-faces)
10865 org-level-faces))
10867 path "/")))))
10869 (defun org-display-outline-path (&optional file current)
10870 "Display the current outline path in the echo area."
10871 (interactive "P")
10872 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10873 (case-fold-search nil)
10874 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10875 (if current (setq path (append path
10876 (save-excursion
10877 (org-back-to-heading t)
10878 (if (looking-at org-complex-heading-regexp)
10879 (list (match-string 4)))))))
10880 (message "%s"
10881 (org-format-outline-path
10882 path
10883 (1- (frame-width))
10884 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10886 (defvar org-refile-history nil
10887 "History for refiling operations.")
10889 (defvar org-after-refile-insert-hook nil
10890 "Hook run after `org-refile' has inserted its stuff at the new location.
10891 Note that this is still *before* the stuff will be removed from
10892 the *old* location.")
10894 (defvar org-capture-last-stored-marker)
10895 (defun org-refile (&optional goto default-buffer rfloc)
10896 "Move the entry or entries at point to another heading.
10897 The list of target headings is compiled using the information in
10898 `org-refile-targets', which see.
10900 At the target location, the entry is filed as a subitem of the target
10901 heading. Depending on `org-reverse-note-order', the new subitem will
10902 either be the first or the last subitem.
10904 If there is an active region, all entries in that region will be moved.
10905 However, the region must fulfill the requirement that the first heading
10906 is the first one sets the top-level of the moved text - at most siblings
10907 below it are allowed.
10909 With prefix arg GOTO, the command will only visit the target location
10910 and not actually move anything.
10912 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10913 go to the location where the last refiling operation has put the subtree.
10914 With a prefix argument of `2', refile to the running clock.
10916 RFLOC can be a refile location obtained in a different way.
10918 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10920 If you are using target caching (see `org-refile-use-cache'),
10921 you have to clear the target cache in order to find new targets.
10922 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10923 prefix argument (`C-u C-u C-u C-c C-w')."
10925 (interactive "P")
10926 (if (member goto '(0 (64)))
10927 (org-refile-cache-clear)
10928 (let* ((cbuf (current-buffer))
10929 (regionp (org-region-active-p))
10930 (region-start (and regionp (region-beginning)))
10931 (region-end (and regionp (region-end)))
10932 (region-length (and regionp (- region-end region-start)))
10933 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10934 pos it nbuf file re level reversed)
10935 (setq last-command nil)
10936 (when regionp
10937 (goto-char region-start)
10938 (or (bolp) (goto-char (point-at-bol)))
10939 (setq region-start (point))
10940 (unless (or (org-kill-is-subtree-p
10941 (buffer-substring region-start region-end))
10942 (prog1 org-refile-active-region-within-subtree
10943 (org-toggle-heading)))
10944 (error "The region is not a (sequence of) subtree(s)")))
10945 (if (equal goto '(16))
10946 (org-refile-goto-last-stored)
10947 (when (or
10948 (and (equal goto 2)
10949 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10950 (prog1
10951 (setq it (list (or org-clock-heading "running clock")
10952 (buffer-file-name
10953 (marker-buffer org-clock-hd-marker))
10955 (marker-position org-clock-hd-marker)))
10956 (setq goto nil)))
10957 (setq it (or rfloc
10958 (let (heading-text)
10959 (save-excursion
10960 (unless goto
10961 (org-back-to-heading t)
10962 (setq heading-text
10963 (nth 4 (org-heading-components))))
10964 (org-refile-get-location
10965 (cond (goto "Goto")
10966 (regionp "Refile region to")
10967 (t (concat "Refile subtree \""
10968 heading-text "\" to")))
10969 default-buffer
10970 (and (not (equal '(4) goto))
10971 org-refile-allow-creating-parent-nodes)
10972 goto))))))
10973 (setq file (nth 1 it)
10974 re (nth 2 it)
10975 pos (nth 3 it))
10976 (if (and (not goto)
10978 (equal (buffer-file-name) file)
10979 (if regionp
10980 (and (>= pos region-start)
10981 (<= pos region-end))
10982 (and (>= pos (point))
10983 (< pos (save-excursion
10984 (org-end-of-subtree t t))))))
10985 (error "Cannot refile to position inside the tree or region"))
10987 (setq nbuf (or (find-buffer-visiting file)
10988 (find-file-noselect file)))
10989 (if goto
10990 (progn
10991 (org-pop-to-buffer-same-window nbuf)
10992 (goto-char pos)
10993 (org-show-context 'org-goto))
10994 (if regionp
10995 (progn
10996 (org-kill-new (buffer-substring region-start region-end))
10997 (org-save-markers-in-region region-start region-end))
10998 (org-copy-subtree 1 nil t))
10999 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11000 (find-file-noselect file)))
11001 (setq reversed (org-notes-order-reversed-p))
11002 (save-excursion
11003 (save-restriction
11004 (widen)
11005 (if pos
11006 (progn
11007 (goto-char pos)
11008 (looking-at org-outline-regexp)
11009 (setq level (org-get-valid-level (funcall outline-level) 1))
11010 (goto-char
11011 (if reversed
11012 (or (outline-next-heading) (point-max))
11013 (or (save-excursion (org-get-next-sibling))
11014 (org-end-of-subtree t t)
11015 (point-max)))))
11016 (setq level 1)
11017 (if (not reversed)
11018 (goto-char (point-max))
11019 (goto-char (point-min))
11020 (or (outline-next-heading) (goto-char (point-max)))))
11021 (if (not (bolp)) (newline))
11022 (org-paste-subtree level)
11023 (when org-log-refile
11024 (org-add-log-setup 'refile nil nil 'findpos
11025 org-log-refile)
11026 (unless (eq org-log-refile 'note)
11027 (save-excursion (org-add-log-note))))
11028 (and org-auto-align-tags
11029 (let ((org-loop-over-headlines-in-active-region nil))
11030 (org-set-tags nil t)))
11031 (bookmark-set "org-refile-last-stored")
11032 ;; If we are refiling for capture, make sure that the
11033 ;; last-capture pointers point here
11034 (when (org-bound-and-true-p org-refile-for-capture)
11035 (bookmark-set "org-capture-last-stored-marker")
11036 (move-marker org-capture-last-stored-marker (point)))
11037 (if (fboundp 'deactivate-mark) (deactivate-mark))
11038 (run-hooks 'org-after-refile-insert-hook))))
11039 (if regionp
11040 (delete-region (point) (+ (point) region-length))
11041 (org-cut-subtree))
11042 (when (featurep 'org-inlinetask)
11043 (org-inlinetask-remove-END-maybe))
11044 (setq org-markers-to-move nil)
11045 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11047 (defun org-refile-goto-last-stored ()
11048 "Go to the location where the last refile was stored."
11049 (interactive)
11050 (bookmark-jump "org-refile-last-stored")
11051 (message "This is the location of the last refile"))
11053 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11054 no-exclude)
11055 "Prompt the user for a refile location, using PROMPT.
11056 PROMPT should not be suffixed with a colon and a space, because
11057 this function appends the default value from
11058 `org-refile-history' automatically, if that is not empty.
11059 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11060 this is used for the GOTO interface."
11061 (let ((org-refile-targets org-refile-targets)
11062 (org-refile-use-outline-path org-refile-use-outline-path)
11063 excluded-entries)
11064 (when (and (derived-mode-p 'org-mode)
11065 (not org-refile-use-cache)
11066 (not no-exclude))
11067 (org-map-tree
11068 (lambda()
11069 (setq excluded-entries
11070 (append excluded-entries (list (org-get-heading t t)))))))
11071 (setq org-refile-target-table
11072 (org-refile-get-targets default-buffer excluded-entries)))
11073 (unless org-refile-target-table
11074 (error "No refile targets"))
11075 (let* ((prompt (concat prompt
11076 (and (car org-refile-history)
11077 (concat " (default " (car org-refile-history) ")"))
11078 ": "))
11079 (cbuf (current-buffer))
11080 (partial-completion-mode nil)
11081 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11082 (cfunc (if (and org-refile-use-outline-path
11083 org-outline-path-complete-in-steps)
11084 'org-olpath-completing-read
11085 'org-icompleting-read))
11086 (extra (if org-refile-use-outline-path "/" ""))
11087 (filename (and cfn (expand-file-name cfn)))
11088 (tbl (mapcar
11089 (lambda (x)
11090 (if (and (not (member org-refile-use-outline-path
11091 '(file full-file-path)))
11092 (not (equal filename (nth 1 x))))
11093 (cons (concat (car x) extra " ("
11094 (file-name-nondirectory (nth 1 x)) ")")
11095 (cdr x))
11096 (cons (concat (car x) extra) (cdr x))))
11097 org-refile-target-table))
11098 (completion-ignore-case t)
11099 pa answ parent-target child parent old-hist)
11100 (setq old-hist org-refile-history)
11101 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11102 nil 'org-refile-history (car org-refile-history)))
11103 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11104 (org-refile-check-position pa)
11105 (if pa
11106 (progn
11107 (when (or (not org-refile-history)
11108 (not (eq old-hist org-refile-history))
11109 (not (equal (car pa) (car org-refile-history))))
11110 (setq org-refile-history
11111 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11112 org-refile-history
11113 (cdr org-refile-history))))
11114 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11115 (pop org-refile-history)))
11117 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11118 (progn
11119 (setq parent (match-string 1 answ)
11120 child (match-string 2 answ))
11121 (setq parent-target (or (assoc parent tbl)
11122 (assoc (concat parent "/") tbl)))
11123 (when (and parent-target
11124 (or (eq new-nodes t)
11125 (and (eq new-nodes 'confirm)
11126 (y-or-n-p (format "Create new node \"%s\"? "
11127 child)))))
11128 (org-refile-new-child parent-target child)))
11129 (error "Invalid target location")))))
11131 (declare-function org-string-nw-p "org-macs.el" (s))
11132 (defun org-refile-check-position (refile-pointer)
11133 "Check if the refile pointer matches the readline to which it points."
11134 (let* ((file (nth 1 refile-pointer))
11135 (re (nth 2 refile-pointer))
11136 (pos (nth 3 refile-pointer))
11137 buffer)
11138 (when (org-string-nw-p re)
11139 (setq buffer (if (markerp pos)
11140 (marker-buffer pos)
11141 (or (find-buffer-visiting file)
11142 (find-file-noselect file))))
11143 (with-current-buffer buffer
11144 (save-excursion
11145 (save-restriction
11146 (widen)
11147 (goto-char pos)
11148 (beginning-of-line 1)
11149 (unless (org-looking-at-p re)
11150 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11152 (defun org-refile-new-child (parent-target child)
11153 "Use refile target PARENT-TARGET to add new CHILD below it."
11154 (unless parent-target
11155 (error "Cannot find parent for new node"))
11156 (let ((file (nth 1 parent-target))
11157 (pos (nth 3 parent-target))
11158 level)
11159 (with-current-buffer (or (find-buffer-visiting file)
11160 (find-file-noselect file))
11161 (save-excursion
11162 (save-restriction
11163 (widen)
11164 (if pos
11165 (goto-char pos)
11166 (goto-char (point-max))
11167 (if (not (bolp)) (newline)))
11168 (when (looking-at org-outline-regexp)
11169 (setq level (funcall outline-level))
11170 (org-end-of-subtree t t))
11171 (org-back-over-empty-lines)
11172 (insert "\n" (make-string
11173 (if pos (org-get-valid-level level 1) 1) ?*)
11174 " " child "\n")
11175 (beginning-of-line 0)
11176 (list (concat (car parent-target) "/" child) file "" (point)))))))
11178 (defun org-olpath-completing-read (prompt collection &rest args)
11179 "Read an outline path like a file name."
11180 (let ((thetable collection)
11181 (org-completion-use-ido nil) ; does not work with ido.
11182 (org-completion-use-iswitchb nil)) ; or iswitchb
11183 (apply
11184 'org-icompleting-read prompt
11185 (lambda (string predicate &optional flag)
11186 (let (rtn r f (l (length string)))
11187 (cond
11188 ((eq flag nil)
11189 ;; try completion
11190 (try-completion string thetable))
11191 ((eq flag t)
11192 ;; all-completions
11193 (setq rtn (all-completions string thetable predicate))
11194 (mapcar
11195 (lambda (x)
11196 (setq r (substring x l))
11197 (if (string-match " ([^)]*)$" x)
11198 (setq f (match-string 0 x))
11199 (setq f ""))
11200 (if (string-match "/" r)
11201 (concat string (substring r 0 (match-end 0)) f)
11203 rtn))
11204 ((eq flag 'lambda)
11205 ;; exact match?
11206 (assoc string thetable)))))
11207 args)))
11209 ;;;; Dynamic blocks
11211 (defun org-find-dblock (name)
11212 "Find the first dynamic block with name NAME in the buffer.
11213 If not found, stay at current position and return nil."
11214 (let ((case-fold-search t) pos)
11215 (save-excursion
11216 (goto-char (point-min))
11217 (setq pos (and (re-search-forward
11218 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11219 (match-beginning 0))))
11220 (if pos (goto-char pos))
11221 pos))
11223 (defconst org-dblock-start-re
11224 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11225 "Matches the start line of a dynamic block, with parameters.")
11227 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11228 "Matches the end of a dynamic block.")
11230 (defun org-create-dblock (plist)
11231 "Create a dynamic block section, with parameters taken from PLIST.
11232 PLIST must contain a :name entry which is used as name of the block."
11233 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11234 (end-of-line 1)
11235 (newline))
11236 (let ((col (current-column))
11237 (name (plist-get plist :name)))
11238 (insert "#+BEGIN: " name)
11239 (while plist
11240 (if (eq (car plist) :name)
11241 (setq plist (cddr plist))
11242 (insert " " (prin1-to-string (pop plist)))))
11243 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11244 (beginning-of-line -2)))
11246 (defun org-prepare-dblock ()
11247 "Prepare dynamic block for refresh.
11248 This empties the block, puts the cursor at the insert position and returns
11249 the property list including an extra property :name with the block name."
11250 (unless (looking-at org-dblock-start-re)
11251 (error "Not at a dynamic block"))
11252 (let* ((begdel (1+ (match-end 0)))
11253 (name (org-no-properties (match-string 1)))
11254 (params (append (list :name name)
11255 (read (concat "(" (match-string 3) ")")))))
11256 (save-excursion
11257 (beginning-of-line 1)
11258 (skip-chars-forward " \t")
11259 (setq params (plist-put params :indentation-column (current-column))))
11260 (unless (re-search-forward org-dblock-end-re nil t)
11261 (error "Dynamic block not terminated"))
11262 (setq params
11263 (append params
11264 (list :content (buffer-substring
11265 begdel (match-beginning 0)))))
11266 (delete-region begdel (match-beginning 0))
11267 (goto-char begdel)
11268 (open-line 1)
11269 params))
11271 (defun org-map-dblocks (&optional command)
11272 "Apply COMMAND to all dynamic blocks in the current buffer.
11273 If COMMAND is not given, use `org-update-dblock'."
11274 (let ((cmd (or command 'org-update-dblock)))
11275 (save-excursion
11276 (goto-char (point-min))
11277 (while (re-search-forward org-dblock-start-re nil t)
11278 (goto-char (match-beginning 0))
11279 (save-excursion
11280 (condition-case nil
11281 (funcall cmd)
11282 (error (message "Error during update of dynamic block"))))
11283 (unless (re-search-forward org-dblock-end-re nil t)
11284 (error "Dynamic block not terminated"))))))
11286 (defun org-dblock-update (&optional arg)
11287 "User command for updating dynamic blocks.
11288 Update the dynamic block at point. With prefix ARG, update all dynamic
11289 blocks in the buffer."
11290 (interactive "P")
11291 (if arg
11292 (org-update-all-dblocks)
11293 (or (looking-at org-dblock-start-re)
11294 (org-beginning-of-dblock))
11295 (org-update-dblock)))
11297 (defun org-update-dblock ()
11298 "Update the dynamic block at point.
11299 This means to empty the block, parse for parameters and then call
11300 the correct writing function."
11301 (interactive)
11302 (save-window-excursion
11303 (let* ((pos (point))
11304 (line (org-current-line))
11305 (params (org-prepare-dblock))
11306 (name (plist-get params :name))
11307 (indent (plist-get params :indentation-column))
11308 (cmd (intern (concat "org-dblock-write:" name))))
11309 (message "Updating dynamic block `%s' at line %d..." name line)
11310 (funcall cmd params)
11311 (message "Updating dynamic block `%s' at line %d...done" name line)
11312 (goto-char pos)
11313 (when (and indent (> indent 0))
11314 (setq indent (make-string indent ?\ ))
11315 (save-excursion
11316 (org-beginning-of-dblock)
11317 (forward-line 1)
11318 (while (not (looking-at org-dblock-end-re))
11319 (insert indent)
11320 (beginning-of-line 2))
11321 (when (looking-at org-dblock-end-re)
11322 (and (looking-at "[ \t]+")
11323 (replace-match ""))
11324 (insert indent)))))))
11326 (defun org-beginning-of-dblock ()
11327 "Find the beginning of the dynamic block at point.
11328 Error if there is no such block at point."
11329 (let ((pos (point))
11330 beg)
11331 (end-of-line 1)
11332 (if (and (re-search-backward org-dblock-start-re nil t)
11333 (setq beg (match-beginning 0))
11334 (re-search-forward org-dblock-end-re nil t)
11335 (> (match-end 0) pos))
11336 (goto-char beg)
11337 (goto-char pos)
11338 (error "Not in a dynamic block"))))
11340 ;;;###autoload
11341 (defun org-update-all-dblocks ()
11342 "Update all dynamic blocks in the buffer.
11343 This function can be used in a hook."
11344 (interactive)
11345 (when (derived-mode-p 'org-mode)
11346 (org-map-dblocks 'org-update-dblock)))
11349 ;;;; Completion
11351 (defconst org-additional-option-like-keywords
11352 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11353 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11354 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11355 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11356 "BEGIN:" "END:"
11357 "ORGTBL" "TBLFM:" "TBLNAME:"
11358 "BEGIN_EXAMPLE" "END_EXAMPLE"
11359 "BEGIN_VERBATIM" "END_VERBATIM"
11360 "BEGIN_QUOTE" "END_QUOTE"
11361 "BEGIN_VERSE" "END_VERSE"
11362 "BEGIN_CENTER" "END_CENTER"
11363 "BEGIN_SRC" "END_SRC"
11364 "BEGIN_RESULT" "END_RESULT"
11365 "BEGIN_lstlisting" "END_lstlisting"
11366 "NAME:" "RESULTS:"
11367 "HEADER:" "HEADERS:"
11368 "COLUMNS:" "PROPERTY:"
11369 "CAPTION:" "LABEL:"
11370 "SETUPFILE:"
11371 "INCLUDE:"
11372 "BIND:"
11373 "MACRO:"))
11375 (defconst org-options-keywords
11376 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11377 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11378 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11379 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11380 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11381 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11382 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11384 (defconst org-additional-option-like-keywords-for-flyspell
11385 (delete-dups
11386 (split-string
11387 (mapconcat (lambda(k)
11388 (replace-regexp-in-string
11389 "_\\|:" " "
11390 (concat k " " (downcase k) " " (upcase k))))
11391 (append org-options-keywords org-additional-option-like-keywords)
11392 " ")
11393 " +" t)))
11395 (defcustom org-structure-template-alist
11397 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11398 "<src lang=\"?\">\n\n</src>")
11399 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11400 "<example>\n?\n</example>")
11401 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11402 "<quote>\n?\n</quote>")
11403 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11404 "<verse>\n?\n</verse>")
11405 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11406 "<center>\n?\n</center>")
11407 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11408 "<literal style=\"latex\">\n?\n</literal>")
11409 ("L" "#+LaTeX: "
11410 "<literal style=\"latex\">?</literal>")
11411 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11412 "<literal style=\"html\">\n?\n</literal>")
11413 ("H" "#+HTML: "
11414 "<literal style=\"html\">?</literal>")
11415 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11416 ("A" "#+ASCII: ")
11417 ("i" "#+INDEX: ?"
11418 "#+INDEX: ?")
11419 ("I" "#+INCLUDE: %file ?"
11420 "<include file=%file markup=\"?\">")
11422 "Structure completion elements.
11423 This is a list of abbreviation keys and values. The value gets inserted
11424 if you type `<' followed by the key and then press the completion key,
11425 usually `M-TAB'. %file will be replaced by a file name after prompting
11426 for the file using completion. The cursor will be placed at the position
11427 of the `?` in the template.
11428 There are two templates for each key, the first uses the original Org syntax,
11429 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11430 the default when the /org-mtags.el/ module has been loaded. See also the
11431 variable `org-mtags-prefer-muse-templates'."
11432 :group 'org-completion
11433 :type '(repeat
11434 (string :tag "Key")
11435 (string :tag "Template")
11436 (string :tag "Muse Template")))
11438 (defun org-try-structure-completion ()
11439 "Try to complete a structure template before point.
11440 This looks for strings like \"<e\" on an otherwise empty line and
11441 expands them."
11442 (let ((l (buffer-substring (point-at-bol) (point)))
11444 (when (and (looking-at "[ \t]*$")
11445 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11446 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11447 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11448 (match-beginning 1)) a)
11449 t)))
11451 (defun org-complete-expand-structure-template (start cell)
11452 "Expand a structure template."
11453 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11454 (rpl (nth (if musep 2 1) cell))
11455 (ind ""))
11456 (delete-region start (point))
11457 (when (string-match "\\`#\\+" rpl)
11458 (cond
11459 ((bolp))
11460 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11461 (setq ind (buffer-substring (point-at-bol) (point))))
11462 (t (newline))))
11463 (setq start (point))
11464 (if (string-match "%file" rpl)
11465 (setq rpl (replace-match
11466 (concat
11467 "\""
11468 (save-match-data
11469 (abbreviate-file-name (read-file-name "Include file: ")))
11470 "\"")
11471 t t rpl)))
11472 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11473 (concat "\n" ind)))
11474 (insert rpl)
11475 (if (re-search-backward "\\?" start t) (delete-char 1))))
11477 ;;;; TODO, DEADLINE, Comments
11479 (defun org-toggle-comment ()
11480 "Change the COMMENT state of an entry."
11481 (interactive)
11482 (save-excursion
11483 (org-back-to-heading)
11484 (let (case-fold-search)
11485 (cond
11486 ((looking-at (format org-heading-keyword-regexp-format
11487 org-comment-string))
11488 (goto-char (match-end 1))
11489 (looking-at (concat " +" org-comment-string))
11490 (replace-match "" t t)
11491 (when (eolp) (insert " ")))
11492 ((looking-at org-outline-regexp)
11493 (goto-char (match-end 0))
11494 (insert org-comment-string " "))))))
11496 (defvar org-last-todo-state-is-todo nil
11497 "This is non-nil when the last TODO state change led to a TODO state.
11498 If the last change removed the TODO tag or switched to DONE, then
11499 this is nil.")
11501 (defvar org-setting-tags nil) ; dynamically skipped
11503 (defvar org-todo-setup-filter-hook nil
11504 "Hook for functions that pre-filter todo specs.
11505 Each function takes a todo spec and returns either nil or the spec
11506 transformed into canonical form." )
11508 (defvar org-todo-get-default-hook nil
11509 "Hook for functions that get a default item for todo.
11510 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11511 nil or a string to be used for the todo mark." )
11513 (defvar org-agenda-headline-snapshot-before-repeat)
11515 (defun org-current-effective-time ()
11516 "Return current time adjusted for `org-extend-today-until' variable."
11517 (let* ((ct (org-current-time))
11518 (dct (decode-time ct))
11519 (ct1
11520 (if (and org-use-effective-time
11521 (< (nth 2 dct) org-extend-today-until))
11522 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11523 ct)))
11524 ct1))
11526 (defun org-todo-yesterday (&optional arg)
11527 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11528 (interactive "P")
11529 (if (eq major-mode 'org-agenda-mode)
11530 (apply 'org-agenda-todo-yesterday arg)
11531 (let* ((hour (third (decode-time
11532 (org-current-time))))
11533 (org-extend-today-until (1+ hour)))
11534 (org-todo arg))))
11536 (defun org-todo (&optional arg)
11537 "Change the TODO state of an item.
11538 The state of an item is given by a keyword at the start of the heading,
11539 like
11540 *** TODO Write paper
11541 *** DONE Call mom
11543 The different keywords are specified in the variable `org-todo-keywords'.
11544 By default the available states are \"TODO\" and \"DONE\".
11545 So for this example: when the item starts with TODO, it is changed to DONE.
11546 When it starts with DONE, the DONE is removed. And when neither TODO nor
11547 DONE are present, add TODO at the beginning of the heading.
11549 With \\[universal-argument] prefix arg, use completion to determine the new \
11550 state.
11551 With numeric prefix arg, switch to that state.
11552 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11553 keywords (nextset).
11554 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11555 With a numeric prefix arg of 0, inhibit note taking for the change.
11557 For calling through lisp, arg is also interpreted in the following way:
11558 'none -> empty state
11559 \"\"(empty string) -> switch to empty state
11560 'done -> switch to DONE
11561 'nextset -> switch to the next set of keywords
11562 'previousset -> switch to the previous set of keywords
11563 \"WAITING\" -> switch to the specified keyword, but only if it
11564 really is a member of `org-todo-keywords'."
11565 (interactive "P")
11566 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11567 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11568 'region-start-level 'region))
11569 org-loop-over-headlines-in-active-region)
11570 (org-map-entries
11571 `(org-todo ,arg)
11572 org-loop-over-headlines-in-active-region
11573 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11574 (if (equal arg '(16)) (setq arg 'nextset))
11575 (let ((org-blocker-hook org-blocker-hook)
11576 (case-fold-search nil))
11577 (when (equal arg '(64))
11578 (setq arg nil org-blocker-hook nil))
11579 (when (and org-blocker-hook
11580 (or org-inhibit-blocking
11581 (org-entry-get nil "NOBLOCKING")))
11582 (setq org-blocker-hook nil))
11583 (save-excursion
11584 (catch 'exit
11585 (org-back-to-heading t)
11586 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11587 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11588 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11589 (let* ((match-data (match-data))
11590 (startpos (point-at-bol))
11591 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11592 (org-log-done org-log-done)
11593 (org-log-repeat org-log-repeat)
11594 (org-todo-log-states org-todo-log-states)
11595 (org-inhibit-logging
11596 (if (equal arg 0)
11597 (progn (setq arg nil) 'note) org-inhibit-logging))
11598 (this (match-string 1))
11599 (hl-pos (match-beginning 0))
11600 (head (org-get-todo-sequence-head this))
11601 (ass (assoc head org-todo-kwd-alist))
11602 (interpret (nth 1 ass))
11603 (done-word (nth 3 ass))
11604 (final-done-word (nth 4 ass))
11605 (org-last-state (or this ""))
11606 (completion-ignore-case t)
11607 (member (member this org-todo-keywords-1))
11608 (tail (cdr member))
11609 (org-state (cond
11610 ((and org-todo-key-trigger
11611 (or (and (equal arg '(4))
11612 (eq org-use-fast-todo-selection 'prefix))
11613 (and (not arg) org-use-fast-todo-selection
11614 (not (eq org-use-fast-todo-selection
11615 'prefix)))))
11616 ;; Use fast selection
11617 (org-fast-todo-selection))
11618 ((and (equal arg '(4))
11619 (or (not org-use-fast-todo-selection)
11620 (not org-todo-key-trigger)))
11621 ;; Read a state with completion
11622 (org-icompleting-read
11623 "State: " (mapcar (lambda(x) (list x))
11624 org-todo-keywords-1)
11625 nil t))
11626 ((eq arg 'right)
11627 (if this
11628 (if tail (car tail) nil)
11629 (car org-todo-keywords-1)))
11630 ((eq arg 'left)
11631 (if (equal member org-todo-keywords-1)
11633 (if this
11634 (nth (- (length org-todo-keywords-1)
11635 (length tail) 2)
11636 org-todo-keywords-1)
11637 (org-last org-todo-keywords-1))))
11638 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11639 (setq arg nil))) ; hack to fall back to cycling
11640 (arg
11641 ;; user or caller requests a specific state
11642 (cond
11643 ((equal arg "") nil)
11644 ((eq arg 'none) nil)
11645 ((eq arg 'done) (or done-word (car org-done-keywords)))
11646 ((eq arg 'nextset)
11647 (or (car (cdr (member head org-todo-heads)))
11648 (car org-todo-heads)))
11649 ((eq arg 'previousset)
11650 (let ((org-todo-heads (reverse org-todo-heads)))
11651 (or (car (cdr (member head org-todo-heads)))
11652 (car org-todo-heads))))
11653 ((car (member arg org-todo-keywords-1)))
11654 ((stringp arg)
11655 (error "State `%s' not valid in this file" arg))
11656 ((nth (1- (prefix-numeric-value arg))
11657 org-todo-keywords-1))))
11658 ((null member) (or head (car org-todo-keywords-1)))
11659 ((equal this final-done-word) nil) ;; -> make empty
11660 ((null tail) nil) ;; -> first entry
11661 ((memq interpret '(type priority))
11662 (if (eq this-command last-command)
11663 (car tail)
11664 (if (> (length tail) 0)
11665 (or done-word (car org-done-keywords))
11666 nil)))
11668 (car tail))))
11669 (org-state (or
11670 (run-hook-with-args-until-success
11671 'org-todo-get-default-hook org-state org-last-state)
11672 org-state))
11673 (next (if org-state (concat " " org-state " ") " "))
11674 (change-plist (list :type 'todo-state-change :from this :to org-state
11675 :position startpos))
11676 dolog now-done-p)
11677 (when org-blocker-hook
11678 (setq org-last-todo-state-is-todo
11679 (not (member this org-done-keywords)))
11680 (unless (save-excursion
11681 (save-match-data
11682 (org-with-wide-buffer
11683 (run-hook-with-args-until-failure
11684 'org-blocker-hook change-plist))))
11685 (if (org-called-interactively-p 'interactive)
11686 (error "TODO state change from %s to %s blocked" this org-state)
11687 ;; fail silently
11688 (message "TODO state change from %s to %s blocked" this org-state)
11689 (throw 'exit nil))))
11690 (store-match-data match-data)
11691 (replace-match next t t)
11692 (unless (pos-visible-in-window-p hl-pos)
11693 (message "TODO state changed to %s" (org-trim next)))
11694 (unless head
11695 (setq head (org-get-todo-sequence-head org-state)
11696 ass (assoc head org-todo-kwd-alist)
11697 interpret (nth 1 ass)
11698 done-word (nth 3 ass)
11699 final-done-word (nth 4 ass)))
11700 (when (memq arg '(nextset previousset))
11701 (message "Keyword-Set %d/%d: %s"
11702 (- (length org-todo-sets) -1
11703 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11704 (length org-todo-sets)
11705 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11706 (setq org-last-todo-state-is-todo
11707 (not (member org-state org-done-keywords)))
11708 (setq now-done-p (and (member org-state org-done-keywords)
11709 (not (member this org-done-keywords))))
11710 (and logging (org-local-logging logging))
11711 (when (and (or org-todo-log-states org-log-done)
11712 (not (eq org-inhibit-logging t))
11713 (not (memq arg '(nextset previousset))))
11714 ;; we need to look at recording a time and note
11715 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11716 (nth 2 (assoc this org-todo-log-states))))
11717 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11718 (setq dolog 'time))
11719 (when (and org-state
11720 (member org-state org-not-done-keywords)
11721 (not (member this org-not-done-keywords)))
11722 ;; This is now a todo state and was not one before
11723 ;; If there was a CLOSED time stamp, get rid of it.
11724 (org-add-planning-info nil nil 'closed))
11725 (when (and now-done-p org-log-done)
11726 ;; It is now done, and it was not done before
11727 (org-add-planning-info 'closed (org-current-effective-time))
11728 (if (and (not dolog) (eq 'note org-log-done))
11729 (org-add-log-setup 'done org-state this 'findpos 'note)))
11730 (when (and org-state dolog)
11731 ;; This is a non-nil state, and we need to log it
11732 (org-add-log-setup 'state org-state this 'findpos dolog)))
11733 ;; Fixup tag positioning
11734 (org-todo-trigger-tag-changes org-state)
11735 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11736 (when org-provide-todo-statistics
11737 (org-update-parent-todo-statistics))
11738 (run-hooks 'org-after-todo-state-change-hook)
11739 (if (and arg (not (member org-state org-done-keywords)))
11740 (setq head (org-get-todo-sequence-head org-state)))
11741 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11742 ;; Do we need to trigger a repeat?
11743 (when now-done-p
11744 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11745 ;; This is for the agenda, take a snapshot of the headline.
11746 (save-match-data
11747 (setq org-agenda-headline-snapshot-before-repeat
11748 (org-get-heading))))
11749 (org-auto-repeat-maybe org-state))
11750 ;; Fixup cursor location if close to the keyword
11751 (if (and (outline-on-heading-p)
11752 (not (bolp))
11753 (save-excursion (beginning-of-line 1)
11754 (looking-at org-todo-line-regexp))
11755 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11756 (progn
11757 (goto-char (or (match-end 2) (match-end 1)))
11758 (and (looking-at " ") (just-one-space))))
11759 (when org-trigger-hook
11760 (save-excursion
11761 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11763 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11764 "Block turning an entry into a TODO, using the hierarchy.
11765 This checks whether the current task should be blocked from state
11766 changes. Such blocking occurs when:
11768 1. The task has children which are not all in a completed state.
11770 2. A task has a parent with the property :ORDERED:, and there
11771 are siblings prior to the current task with incomplete
11772 status.
11774 3. The parent of the task is blocked because it has siblings that should
11775 be done first, or is child of a block grandparent TODO entry."
11777 (if (not org-enforce-todo-dependencies)
11778 t ; if locally turned off don't block
11779 (catch 'dont-block
11780 ;; If this is not a todo state change, or if this entry is already DONE,
11781 ;; do not block
11782 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11783 (member (plist-get change-plist :from)
11784 (cons 'done org-done-keywords))
11785 (member (plist-get change-plist :to)
11786 (cons 'todo org-not-done-keywords))
11787 (not (plist-get change-plist :to)))
11788 (throw 'dont-block t))
11789 ;; If this task has children, and any are undone, it's blocked
11790 (save-excursion
11791 (org-back-to-heading t)
11792 (let ((this-level (funcall outline-level)))
11793 (outline-next-heading)
11794 (let ((child-level (funcall outline-level)))
11795 (while (and (not (eobp))
11796 (> child-level this-level))
11797 ;; this todo has children, check whether they are all
11798 ;; completed
11799 (if (and (not (org-entry-is-done-p))
11800 (org-entry-is-todo-p))
11801 (throw 'dont-block nil))
11802 (outline-next-heading)
11803 (setq child-level (funcall outline-level))))))
11804 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11805 ;; any previous siblings are undone, it's blocked
11806 (save-excursion
11807 (org-back-to-heading t)
11808 (let* ((pos (point))
11809 (parent-pos (and (org-up-heading-safe) (point))))
11810 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11811 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11812 (forward-line 1)
11813 (re-search-forward org-not-done-heading-regexp pos t))
11814 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11815 ;; Search further up the hierarchy, to see if an ancestor is blocked
11816 (while t
11817 (goto-char parent-pos)
11818 (if (not (looking-at org-not-done-heading-regexp))
11819 (throw 'dont-block t)) ; do not block, parent is not a TODO
11820 (setq pos (point))
11821 (setq parent-pos (and (org-up-heading-safe) (point)))
11822 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11823 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11824 (forward-line 1)
11825 (re-search-forward org-not-done-heading-regexp pos t))
11826 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11828 (defcustom org-track-ordered-property-with-tag nil
11829 "Should the ORDERED property also be shown as a tag?
11830 The ORDERED property decides if an entry should require subtasks to be
11831 completed in sequence. Since a property is not very visible, setting
11832 this option means that toggling the ORDERED property with the command
11833 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11834 not relevant for the behavior, but it makes things more visible.
11836 Note that toggling the tag with tags commands will not change the property
11837 and therefore not influence behavior!
11839 This can be t, meaning the tag ORDERED should be used, It can also be a
11840 string to select a different tag for this task."
11841 :group 'org-todo
11842 :type '(choice
11843 (const :tag "No tracking" nil)
11844 (const :tag "Track with ORDERED tag" t)
11845 (string :tag "Use other tag")))
11847 (defun org-toggle-ordered-property ()
11848 "Toggle the ORDERED property of the current entry.
11849 For better visibility, you can track the value of this property with a tag.
11850 See variable `org-track-ordered-property-with-tag'."
11851 (interactive)
11852 (let* ((t1 org-track-ordered-property-with-tag)
11853 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11854 (save-excursion
11855 (org-back-to-heading)
11856 (if (org-entry-get nil "ORDERED")
11857 (progn
11858 (org-delete-property "ORDERED")
11859 (and tag (org-toggle-tag tag 'off))
11860 (message "Subtasks can be completed in arbitrary order"))
11861 (org-entry-put nil "ORDERED" "t")
11862 (and tag (org-toggle-tag tag 'on))
11863 (message "Subtasks must be completed in sequence")))))
11865 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11866 (defun org-block-todo-from-checkboxes (change-plist)
11867 "Block turning an entry into a TODO, using checkboxes.
11868 This checks whether the current task should be blocked from state
11869 changes because there are unchecked boxes in this entry."
11870 (if (not org-enforce-todo-checkbox-dependencies)
11871 t ; if locally turned off don't block
11872 (catch 'dont-block
11873 ;; If this is not a todo state change, or if this entry is already DONE,
11874 ;; do not block
11875 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11876 (member (plist-get change-plist :from)
11877 (cons 'done org-done-keywords))
11878 (member (plist-get change-plist :to)
11879 (cons 'todo org-not-done-keywords))
11880 (not (plist-get change-plist :to)))
11881 (throw 'dont-block t))
11882 ;; If this task has checkboxes that are not checked, it's blocked
11883 (save-excursion
11884 (org-back-to-heading t)
11885 (let ((beg (point)) end)
11886 (outline-next-heading)
11887 (setq end (point))
11888 (goto-char beg)
11889 (if (org-list-search-forward
11890 (concat (org-item-beginning-re)
11891 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11892 "\\[[- ]\\]")
11893 end t)
11894 (progn
11895 (if (boundp 'org-blocked-by-checkboxes)
11896 (setq org-blocked-by-checkboxes t))
11897 (throw 'dont-block nil)))))
11898 t))) ; do not block
11900 (defun org-entry-blocked-p ()
11901 "Is the current entry blocked?"
11902 (if (org-entry-get nil "NOBLOCKING")
11903 nil ;; Never block this entry
11904 (not
11905 (run-hook-with-args-until-failure
11906 'org-blocker-hook
11907 (list :type 'todo-state-change
11908 :position (point)
11909 :from 'todo
11910 :to 'done)))))
11912 (defun org-update-statistics-cookies (all)
11913 "Update the statistics cookie, either from TODO or from checkboxes.
11914 This should be called with the cursor in a line with a statistics cookie."
11915 (interactive "P")
11916 (if all
11917 (progn
11918 (org-update-checkbox-count 'all)
11919 (org-map-entries 'org-update-parent-todo-statistics))
11920 (if (not (org-at-heading-p))
11921 (org-update-checkbox-count)
11922 (let ((pos (move-marker (make-marker) (point)))
11923 end l1 l2)
11924 (ignore-errors (org-back-to-heading t))
11925 (if (not (org-at-heading-p))
11926 (org-update-checkbox-count)
11927 (setq l1 (org-outline-level))
11928 (setq end (save-excursion
11929 (outline-next-heading)
11930 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11931 (point)))
11932 (if (and (save-excursion
11933 (re-search-forward
11934 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11935 (not (save-excursion (re-search-forward
11936 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11937 (org-update-checkbox-count)
11938 (if (and l2 (> l2 l1))
11939 (progn
11940 (goto-char end)
11941 (org-update-parent-todo-statistics))
11942 (goto-char pos)
11943 (beginning-of-line 1)
11944 (while (re-search-forward
11945 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11946 (point-at-eol) t)
11947 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11948 (goto-char pos)
11949 (move-marker pos nil)))))
11951 (defvar org-entry-property-inherited-from) ;; defined below
11952 (defun org-update-parent-todo-statistics ()
11953 "Update any statistics cookie in the parent of the current headline.
11954 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11955 the entire subtree and this will travel up the hierarchy and update
11956 statistics everywhere."
11957 (let* ((prop (save-excursion (org-up-heading-safe)
11958 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11959 (recursive (or (not org-hierarchical-todo-statistics)
11960 (and prop (string-match "\\<recursive\\>" prop))))
11961 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11963 (first t)
11964 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11965 level ltoggle l1 new ndel
11966 (cnt-all 0) (cnt-done 0) is-percent kwd
11967 checkbox-beg ov ovs ove cookie-present)
11968 (catch 'exit
11969 (save-excursion
11970 (beginning-of-line 1)
11971 (setq ltoggle (funcall outline-level))
11972 ;; Three situations are to consider:
11974 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11975 ;; to the top-level ancestor on the headline;
11977 ;; 2. If parent has "recursive" property, repeat up to the
11978 ;; headline setting that property, taking inheritance into
11979 ;; account;
11981 ;; 3. Else, move up to direct parent and proceed only once.
11982 (while (and (setq level (org-up-heading-safe))
11983 (or recursive first)
11984 (>= (point) lim))
11985 (setq first nil cookie-present nil)
11986 (unless (and level
11987 (not (string-match
11988 "\\<checkbox\\>"
11989 (downcase (or (org-entry-get nil "COOKIE_DATA")
11990 "")))))
11991 (throw 'exit nil))
11992 (while (re-search-forward box-re (point-at-eol) t)
11993 (setq cnt-all 0 cnt-done 0 cookie-present t)
11994 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11995 (save-match-data
11996 (unless (outline-next-heading) (throw 'exit nil))
11997 (while (and (looking-at org-complex-heading-regexp)
11998 (> (setq l1 (length (match-string 1))) level))
11999 (setq kwd (and (or recursive (= l1 ltoggle))
12000 (match-string 2)))
12001 (if (or (eq org-provide-todo-statistics 'all-headlines)
12002 (and (listp org-provide-todo-statistics)
12003 (or (member kwd org-provide-todo-statistics)
12004 (member kwd org-done-keywords))))
12005 (setq cnt-all (1+ cnt-all))
12006 (if (eq org-provide-todo-statistics t)
12007 (and kwd (setq cnt-all (1+ cnt-all)))))
12008 (and (member kwd org-done-keywords)
12009 (setq cnt-done (1+ cnt-done)))
12010 (outline-next-heading)))
12011 (setq new
12012 (if is-percent
12013 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12014 (format "[%d/%d]" cnt-done cnt-all))
12015 ndel (- (match-end 0) checkbox-beg))
12016 ;; handle overlays when updating cookie from column view
12017 (when (setq ov (car (overlays-at checkbox-beg)))
12018 (setq ovs (overlay-start ov) ove (overlay-end ov))
12019 (delete-overlay ov))
12020 (goto-char checkbox-beg)
12021 (insert new)
12022 (delete-region (point) (+ (point) ndel))
12023 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12024 (when ov (move-overlay ov ovs ove)))
12025 (when cookie-present
12026 (run-hook-with-args 'org-after-todo-statistics-hook
12027 cnt-done (- cnt-all cnt-done))))))
12028 (run-hooks 'org-todo-statistics-hook)))
12030 (defvar org-after-todo-statistics-hook nil
12031 "Hook that is called after a TODO statistics cookie has been updated.
12032 Each function is called with two arguments: the number of not-done entries
12033 and the number of done entries.
12035 For example, the following function, when added to this hook, will switch
12036 an entry to DONE when all children are done, and back to TODO when new
12037 entries are set to a TODO status. Note that this hook is only called
12038 when there is a statistics cookie in the headline!
12040 (defun org-summary-todo (n-done n-not-done)
12041 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12042 (let (org-log-done org-log-states) ; turn off logging
12043 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12046 (defvar org-todo-statistics-hook nil
12047 "Hook that is run whenever Org thinks TODO statistics should be updated.
12048 This hook runs even if there is no statistics cookie present, in which case
12049 `org-after-todo-statistics-hook' would not run.")
12051 (defun org-todo-trigger-tag-changes (state)
12052 "Apply the changes defined in `org-todo-state-tags-triggers'."
12053 (let ((l org-todo-state-tags-triggers)
12054 changes)
12055 (when (or (not state) (equal state ""))
12056 (setq changes (append changes (cdr (assoc "" l)))))
12057 (when (and (stringp state) (> (length state) 0))
12058 (setq changes (append changes (cdr (assoc state l)))))
12059 (when (member state org-not-done-keywords)
12060 (setq changes (append changes (cdr (assoc 'todo l)))))
12061 (when (member state org-done-keywords)
12062 (setq changes (append changes (cdr (assoc 'done l)))))
12063 (dolist (c changes)
12064 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12066 (defun org-local-logging (value)
12067 "Get logging settings from a property VALUE."
12068 (let* (words w a)
12069 ;; directly set the variables, they are already local.
12070 (setq org-log-done nil
12071 org-log-repeat nil
12072 org-todo-log-states nil)
12073 (setq words (org-split-string value))
12074 (while (setq w (pop words))
12075 (cond
12076 ((setq a (assoc w org-startup-options))
12077 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12078 (set (nth 1 a) (nth 2 a))))
12079 ((setq a (org-extract-log-state-settings w))
12080 (and (member (car a) org-todo-keywords-1)
12081 (push a org-todo-log-states)))))))
12083 (defun org-get-todo-sequence-head (kwd)
12084 "Return the head of the TODO sequence to which KWD belongs.
12085 If KWD is not set, check if there is a text property remembering the
12086 right sequence."
12087 (let (p)
12088 (cond
12089 ((not kwd)
12090 (or (get-text-property (point-at-bol) 'org-todo-head)
12091 (progn
12092 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12093 nil (point-at-eol)))
12094 (get-text-property p 'org-todo-head))))
12095 ((not (member kwd org-todo-keywords-1))
12096 (car org-todo-keywords-1))
12097 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12099 (defun org-fast-todo-selection ()
12100 "Fast TODO keyword selection with single keys.
12101 Returns the new TODO keyword, or nil if no state change should occur."
12102 (let* ((fulltable org-todo-key-alist)
12103 (done-keywords org-done-keywords) ;; needed for the faces.
12104 (maxlen (apply 'max (mapcar
12105 (lambda (x)
12106 (if (stringp (car x)) (string-width (car x)) 0))
12107 fulltable)))
12108 (expert nil)
12109 (fwidth (+ maxlen 3 1 3))
12110 (ncol (/ (- (window-width) 4) fwidth))
12111 tg cnt e c tbl
12112 groups ingroup)
12113 (save-excursion
12114 (save-window-excursion
12115 (if expert
12116 (set-buffer (get-buffer-create " *Org todo*"))
12117 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12118 (erase-buffer)
12119 (org-set-local 'org-done-keywords done-keywords)
12120 (setq tbl fulltable cnt 0)
12121 (while (setq e (pop tbl))
12122 (cond
12123 ((equal e '(:startgroup))
12124 (push '() groups) (setq ingroup t)
12125 (when (not (= cnt 0))
12126 (setq cnt 0)
12127 (insert "\n"))
12128 (insert "{ "))
12129 ((equal e '(:endgroup))
12130 (setq ingroup nil cnt 0)
12131 (insert "}\n"))
12132 ((equal e '(:newline))
12133 (when (not (= cnt 0))
12134 (setq cnt 0)
12135 (insert "\n")
12136 (setq e (car tbl))
12137 (while (equal (car tbl) '(:newline))
12138 (insert "\n")
12139 (setq tbl (cdr tbl)))))
12141 (setq tg (car e) c (cdr e))
12142 (if ingroup (push tg (car groups)))
12143 (setq tg (org-add-props tg nil 'face
12144 (org-get-todo-face tg)))
12145 (if (and (= cnt 0) (not ingroup)) (insert " "))
12146 (insert "[" c "] " tg (make-string
12147 (- fwidth 4 (length tg)) ?\ ))
12148 (when (= (setq cnt (1+ cnt)) ncol)
12149 (insert "\n")
12150 (if ingroup (insert " "))
12151 (setq cnt 0)))))
12152 (insert "\n")
12153 (goto-char (point-min))
12154 (if (not expert) (org-fit-window-to-buffer))
12155 (message "[a-z..]:Set [SPC]:clear")
12156 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12157 (cond
12158 ((or (= c ?\C-g)
12159 (and (= c ?q) (not (rassoc c fulltable))))
12160 (setq quit-flag t))
12161 ((= c ?\ ) nil)
12162 ((setq e (rassoc c fulltable) tg (car e))
12164 (t (setq quit-flag t)))))))
12166 (defun org-entry-is-todo-p ()
12167 (member (org-get-todo-state) org-not-done-keywords))
12169 (defun org-entry-is-done-p ()
12170 (member (org-get-todo-state) org-done-keywords))
12172 (defun org-get-todo-state ()
12173 (save-excursion
12174 (org-back-to-heading t)
12175 (and (looking-at org-todo-line-regexp)
12176 (match-end 2)
12177 (match-string 2))))
12179 (defun org-at-date-range-p (&optional inactive-ok)
12180 "Is the cursor inside a date range?"
12181 (interactive)
12182 (save-excursion
12183 (catch 'exit
12184 (let ((pos (point)))
12185 (skip-chars-backward "^[<\r\n")
12186 (skip-chars-backward "<[")
12187 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12188 (>= (match-end 0) pos)
12189 (throw 'exit t))
12190 (skip-chars-backward "^<[\r\n")
12191 (skip-chars-backward "<[")
12192 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12193 (>= (match-end 0) pos)
12194 (throw 'exit t)))
12195 nil)))
12197 (defun org-get-repeat (&optional tagline)
12198 "Check if there is a deadline/schedule with repeater in this entry."
12199 (save-match-data
12200 (save-excursion
12201 (org-back-to-heading t)
12202 (and (re-search-forward (if tagline
12203 (concat tagline "\\s-*" org-repeat-re)
12204 org-repeat-re)
12205 (org-entry-end-position) t)
12206 (match-string-no-properties 1)))))
12208 (defvar org-last-changed-timestamp)
12209 (defvar org-last-inserted-timestamp)
12210 (defvar org-log-post-message)
12211 (defvar org-log-note-purpose)
12212 (defvar org-log-note-how)
12213 (defvar org-log-note-extra)
12214 (defun org-auto-repeat-maybe (done-word)
12215 "Check if the current headline contains a repeated deadline/schedule.
12216 If yes, set TODO state back to what it was and change the base date
12217 of repeating deadline/scheduled time stamps to new date.
12218 This function is run automatically after each state change to a DONE state."
12219 ;; last-state is dynamically scoped into this function
12220 (let* ((repeat (org-get-repeat))
12221 (aa (assoc org-last-state org-todo-kwd-alist))
12222 (interpret (nth 1 aa))
12223 (head (nth 2 aa))
12224 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12225 (msg "Entry repeats: ")
12226 (org-log-done nil)
12227 (org-todo-log-states nil)
12228 re type n what ts time to-state)
12229 (when repeat
12230 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12231 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12232 org-todo-repeat-to-state))
12233 (unless (and to-state (member to-state org-todo-keywords-1))
12234 (setq to-state (if (eq interpret 'type) org-last-state head)))
12235 (org-todo to-state)
12236 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12237 (org-entry-put nil "LAST_REPEAT" (format-time-string
12238 (org-time-stamp-format t t))))
12239 (when org-log-repeat
12240 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12241 (memq 'org-add-log-note post-command-hook))
12242 ;; OK, we are already setup for some record
12243 (if (eq org-log-repeat 'note)
12244 ;; make sure we take a note, not only a time stamp
12245 (setq org-log-note-how 'note))
12246 ;; Set up for taking a record
12247 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12248 org-last-state
12249 'findpos org-log-repeat)))
12250 (org-back-to-heading t)
12251 (org-add-planning-info nil nil 'closed)
12252 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12253 org-deadline-time-regexp "\\)\\|\\("
12254 org-ts-regexp "\\)"))
12255 (while (re-search-forward
12256 re (save-excursion (outline-next-heading) (point)) t)
12257 (setq type (if (match-end 1) org-scheduled-string
12258 (if (match-end 3) org-deadline-string "Plain:"))
12259 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12260 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12261 (setq n (string-to-number (match-string 2 ts))
12262 what (match-string 3 ts))
12263 (if (equal what "w") (setq n (* n 7) what "d"))
12264 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12265 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12266 ;; Preparation, see if we need to modify the start date for the change
12267 (when (match-end 1)
12268 (setq time (save-match-data (org-time-string-to-time ts)))
12269 (cond
12270 ((equal (match-string 1 ts) ".")
12271 ;; Shift starting date to today
12272 (org-timestamp-change
12273 (- (org-today) (time-to-days time))
12274 'day))
12275 ((equal (match-string 1 ts) "+")
12276 (let ((nshiftmax 10) (nshift 0))
12277 (while (or (= nshift 0)
12278 (<= (time-to-days time)
12279 (time-to-days (current-time))))
12280 (when (= (incf nshift) nshiftmax)
12281 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12282 (error "Abort")))
12283 (org-timestamp-change n (cdr (assoc what whata)))
12284 (org-at-timestamp-p t)
12285 (setq ts (match-string 1))
12286 (setq time (save-match-data (org-time-string-to-time ts)))))
12287 (org-timestamp-change (- n) (cdr (assoc what whata)))
12288 ;; rematch, so that we have everything in place for the real shift
12289 (org-at-timestamp-p t)
12290 (setq ts (match-string 1))
12291 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12292 (org-timestamp-change n (cdr (assoc what whata)))
12293 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12294 (setq org-log-post-message msg)
12295 (message "%s" msg))))
12297 (defun org-show-todo-tree (arg)
12298 "Make a compact tree which shows all headlines marked with TODO.
12299 The tree will show the lines where the regexp matches, and all higher
12300 headlines above the match.
12301 With a \\[universal-argument] prefix, prompt for a regexp to match.
12302 With a numeric prefix N, construct a sparse tree for the Nth element
12303 of `org-todo-keywords-1'."
12304 (interactive "P")
12305 (let ((case-fold-search nil)
12306 (kwd-re
12307 (cond ((null arg) org-not-done-regexp)
12308 ((equal arg '(4))
12309 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12310 (mapcar 'list org-todo-keywords-1))))
12311 (concat "\\("
12312 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12313 "\\)\\>")))
12314 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12315 (regexp-quote (nth (1- (prefix-numeric-value arg))
12316 org-todo-keywords-1)))
12317 (t (error "Invalid prefix argument: %s" arg)))))
12318 (message "%d TODO entries found"
12319 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12321 (defun org-deadline (&optional remove time)
12322 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12323 With argument REMOVE, remove any deadline from the item.
12324 With argument TIME, set the deadline at the corresponding date. TIME
12325 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12326 (interactive "P")
12327 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12328 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12329 'region-start-level 'region))
12330 org-loop-over-headlines-in-active-region)
12331 (org-map-entries
12332 `(org-deadline ',remove ,time)
12333 org-loop-over-headlines-in-active-region
12334 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12335 (let* ((old-date (org-entry-get nil "DEADLINE"))
12336 (repeater (and old-date
12337 (string-match
12338 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12339 old-date)
12340 (match-string 1 old-date))))
12341 (if remove
12342 (progn
12343 (when (and old-date org-log-redeadline)
12344 (org-add-log-setup 'deldeadline nil old-date 'findpos
12345 org-log-redeadline))
12346 (org-remove-timestamp-with-keyword org-deadline-string)
12347 (message "Item no longer has a deadline."))
12348 (org-add-planning-info 'deadline time 'closed)
12349 (when (and old-date org-log-redeadline
12350 (not (equal old-date
12351 (substring org-last-inserted-timestamp 1 -1))))
12352 (org-add-log-setup 'redeadline nil old-date 'findpos
12353 org-log-redeadline))
12354 (when repeater
12355 (save-excursion
12356 (org-back-to-heading t)
12357 (when (re-search-forward (concat org-deadline-string " "
12358 org-last-inserted-timestamp)
12359 (save-excursion
12360 (outline-next-heading) (point)) t)
12361 (goto-char (1- (match-end 0)))
12362 (insert " " repeater)
12363 (setq org-last-inserted-timestamp
12364 (concat (substring org-last-inserted-timestamp 0 -1)
12365 " " repeater
12366 (substring org-last-inserted-timestamp -1))))))
12367 (message "Deadline on %s" org-last-inserted-timestamp)))))
12369 (defun org-schedule (&optional remove time)
12370 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12371 With argument REMOVE, remove any scheduling date from the item.
12372 With argument TIME, scheduled at the corresponding date. TIME can
12373 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12374 (interactive "P")
12375 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12376 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12377 'region-start-level 'region))
12378 org-loop-over-headlines-in-active-region)
12379 (org-map-entries
12380 `(org-schedule ',remove ,time)
12381 org-loop-over-headlines-in-active-region
12382 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12383 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12384 (repeater (and old-date
12385 (string-match
12386 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12387 old-date)
12388 (match-string 1 old-date))))
12389 (if remove
12390 (progn
12391 (when (and old-date org-log-reschedule)
12392 (org-add-log-setup 'delschedule nil old-date 'findpos
12393 org-log-reschedule))
12394 (org-remove-timestamp-with-keyword org-scheduled-string)
12395 (message "Item is no longer scheduled."))
12396 (org-add-planning-info 'scheduled time 'closed)
12397 (when (and old-date org-log-reschedule
12398 (not (equal old-date
12399 (substring org-last-inserted-timestamp 1 -1))))
12400 (org-add-log-setup 'reschedule nil old-date 'findpos
12401 org-log-reschedule))
12402 (when repeater
12403 (save-excursion
12404 (org-back-to-heading t)
12405 (when (re-search-forward (concat org-scheduled-string " "
12406 org-last-inserted-timestamp)
12407 (save-excursion
12408 (outline-next-heading) (point)) t)
12409 (goto-char (1- (match-end 0)))
12410 (insert " " repeater)
12411 (setq org-last-inserted-timestamp
12412 (concat (substring org-last-inserted-timestamp 0 -1)
12413 " " repeater
12414 (substring org-last-inserted-timestamp -1))))))
12415 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12417 (defun org-get-scheduled-time (pom &optional inherit)
12418 "Get the scheduled time as a time tuple, of a format suitable
12419 for calling org-schedule with, or if there is no scheduling,
12420 returns nil."
12421 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12422 (when time
12423 (apply 'encode-time (org-parse-time-string time)))))
12425 (defun org-get-deadline-time (pom &optional inherit)
12426 "Get the deadline as a time tuple, of a format suitable for
12427 calling org-deadline with, or if there is no scheduling, returns
12428 nil."
12429 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12430 (when time
12431 (apply 'encode-time (org-parse-time-string time)))))
12433 (defun org-remove-timestamp-with-keyword (keyword)
12434 "Remove all time stamps with KEYWORD in the current entry."
12435 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12436 beg)
12437 (save-excursion
12438 (org-back-to-heading t)
12439 (setq beg (point))
12440 (outline-next-heading)
12441 (while (re-search-backward re beg t)
12442 (replace-match "")
12443 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12444 (equal (char-before) ?\ ))
12445 (backward-delete-char 1)
12446 (if (string-match "^[ \t]*$" (buffer-substring
12447 (point-at-bol) (point-at-eol)))
12448 (delete-region (point-at-bol)
12449 (min (point-max) (1+ (point-at-eol))))))))))
12451 (defun org-add-planning-info (what &optional time &rest remove)
12452 "Insert new timestamp with keyword in the line directly after the headline.
12453 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12454 If non is given, the user is prompted for a date.
12455 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12456 be removed."
12457 (interactive)
12458 (let (org-time-was-given org-end-time-was-given ts
12459 end default-time default-input)
12461 (catch 'exit
12462 (when (and (memq what '(scheduled deadline))
12463 (or (not time)
12464 (and (stringp time)
12465 (string-match "^[-+]+[0-9]" time))))
12466 ;; Try to get a default date/time from existing timestamp
12467 (save-excursion
12468 (org-back-to-heading t)
12469 (setq end (save-excursion (outline-next-heading) (point)))
12470 (when (re-search-forward (if (eq what 'scheduled)
12471 org-scheduled-time-regexp
12472 org-deadline-time-regexp)
12473 end t)
12474 (setq ts (match-string 1)
12475 default-time
12476 (apply 'encode-time (org-parse-time-string ts))
12477 default-input (and ts (org-get-compact-tod ts))))))
12478 (when what
12479 (setq time
12480 (if (stringp time)
12481 ;; This is a string (relative or absolute), set proper date
12482 (apply 'encode-time
12483 (org-read-date-analyze
12484 time default-time (decode-time default-time)))
12485 ;; If necessary, get the time from the user
12486 (or time (org-read-date nil 'to-time nil nil
12487 default-time default-input)))))
12489 (when (and org-insert-labeled-timestamps-at-point
12490 (member what '(scheduled deadline)))
12491 (insert
12492 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12493 (org-insert-time-stamp time org-time-was-given
12494 nil nil nil (list org-end-time-was-given))
12495 (setq what nil))
12496 (save-excursion
12497 (save-restriction
12498 (let (col list elt ts buffer-invisibility-spec)
12499 (org-back-to-heading t)
12500 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12501 (goto-char (match-end 1))
12502 (setq col (current-column))
12503 (goto-char (match-end 0))
12504 (if (eobp) (insert "\n") (forward-char 1))
12505 (when (and (not what)
12506 (not (looking-at
12507 (concat "[ \t]*"
12508 org-keyword-time-not-clock-regexp))))
12509 ;; Nothing to add, nothing to remove...... :-)
12510 (throw 'exit nil))
12511 (if (and (not (looking-at org-outline-regexp))
12512 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12513 "[^\r\n]*"))
12514 (not (equal (match-string 1) org-clock-string)))
12515 (narrow-to-region (match-beginning 0) (match-end 0))
12516 (insert-before-markers "\n")
12517 (backward-char 1)
12518 (narrow-to-region (point) (point))
12519 (and org-adapt-indentation (org-indent-to-column col)))
12520 ;; Check if we have to remove something.
12521 (setq list (cons what remove))
12522 (while list
12523 (setq elt (pop list))
12524 (when (or (and (eq elt 'scheduled)
12525 (re-search-forward org-scheduled-time-regexp nil t))
12526 (and (eq elt 'deadline)
12527 (re-search-forward org-deadline-time-regexp nil t))
12528 (and (eq elt 'closed)
12529 (re-search-forward org-closed-time-regexp nil t)))
12530 (replace-match "")
12531 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12532 (and (looking-at "[ \t]+") (replace-match ""))
12533 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12534 (when what
12535 (insert
12536 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12537 (cond ((eq what 'scheduled) org-scheduled-string)
12538 ((eq what 'deadline) org-deadline-string)
12539 ((eq what 'closed) org-closed-string))
12540 " ")
12541 (setq ts (org-insert-time-stamp
12542 time
12543 (or org-time-was-given
12544 (and (eq what 'closed) org-log-done-with-time))
12545 (eq what 'closed)
12546 nil nil (list org-end-time-was-given)))
12547 (insert
12548 (if (not (or (bolp) (eq (char-before) ?\ )
12549 (memq (char-after) '(32 10))
12550 (eobp))) " " ""))
12551 (end-of-line 1))
12552 (goto-char (point-min))
12553 (widen)
12554 (if (and (looking-at "[ \t]*\n")
12555 (equal (char-before) ?\n))
12556 (delete-region (1- (point)) (point-at-eol)))
12557 ts))))))
12559 (defvar org-log-note-marker (make-marker))
12560 (defvar org-log-note-purpose nil)
12561 (defvar org-log-note-state nil)
12562 (defvar org-log-note-previous-state nil)
12563 (defvar org-log-note-how nil)
12564 (defvar org-log-note-extra nil)
12565 (defvar org-log-note-window-configuration nil)
12566 (defvar org-log-note-return-to (make-marker))
12567 (defvar org-log-note-effective-time nil
12568 "Remembered current time so that dynamically scoped
12569 `org-extend-today-until' affects tha timestamps in state change
12570 log")
12572 (defvar org-log-post-message nil
12573 "Message to be displayed after a log note has been stored.
12574 The auto-repeater uses this.")
12576 (defun org-add-note ()
12577 "Add a note to the current entry.
12578 This is done in the same way as adding a state change note."
12579 (interactive)
12580 (org-add-log-setup 'note nil nil 'findpos nil))
12582 (defvar org-property-end-re)
12583 (defun org-add-log-setup (&optional purpose state prev-state
12584 findpos how extra)
12585 "Set up the post command hook to take a note.
12586 If this is about to TODO state change, the new state is expected in STATE.
12587 When FINDPOS is non-nil, find the correct position for the note in
12588 the current entry. If not, assume that it can be inserted at point.
12589 HOW is an indicator what kind of note should be created.
12590 EXTRA is additional text that will be inserted into the notes buffer."
12591 (let* ((org-log-into-drawer (org-log-into-drawer))
12592 (drawer (cond ((stringp org-log-into-drawer)
12593 org-log-into-drawer)
12594 (org-log-into-drawer "LOGBOOK"))))
12595 (save-restriction
12596 (save-excursion
12597 (when findpos
12598 (org-back-to-heading t)
12599 (narrow-to-region (point) (save-excursion
12600 (outline-next-heading) (point)))
12601 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12602 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12603 "[^\r\n]*\\)?"))
12604 (goto-char (match-end 0))
12605 (cond
12606 (drawer
12607 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12608 nil t)
12609 (progn
12610 (goto-char (match-end 0))
12611 (or org-log-states-order-reversed
12612 (and (re-search-forward org-property-end-re nil t)
12613 (goto-char (1- (match-beginning 0))))))
12614 (insert "\n:" drawer ":\n:END:")
12615 (beginning-of-line 0)
12616 (org-indent-line)
12617 (beginning-of-line 2)
12618 (org-indent-line)
12619 (end-of-line 0)))
12620 ((and org-log-state-notes-insert-after-drawers
12621 (save-excursion
12622 (forward-line) (looking-at org-drawer-regexp)))
12623 (forward-line)
12624 (while (looking-at org-drawer-regexp)
12625 (goto-char (match-end 0))
12626 (re-search-forward org-property-end-re (point-max) t)
12627 (forward-line))
12628 (forward-line -1)))
12629 (unless org-log-states-order-reversed
12630 (and (= (char-after) ?\n) (forward-char 1))
12631 (org-skip-over-state-notes)
12632 (skip-chars-backward " \t\n\r")))
12633 (move-marker org-log-note-marker (point))
12634 (setq org-log-note-purpose purpose
12635 org-log-note-state state
12636 org-log-note-previous-state prev-state
12637 org-log-note-how how
12638 org-log-note-extra extra
12639 org-log-note-effective-time (org-current-effective-time))
12640 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12642 (defun org-skip-over-state-notes ()
12643 "Skip past the list of State notes in an entry."
12644 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12645 (when (ignore-errors (goto-char (org-in-item-p)))
12646 (let* ((struct (org-list-struct))
12647 (prevs (org-list-prevs-alist struct)))
12648 (while (looking-at "[ \t]*- State")
12649 (goto-char (or (org-list-get-next-item (point) struct prevs)
12650 (org-list-get-item-end (point) struct)))))))
12652 (defun org-add-log-note (&optional purpose)
12653 "Pop up a window for taking a note, and add this note later at point."
12654 (remove-hook 'post-command-hook 'org-add-log-note)
12655 (setq org-log-note-window-configuration (current-window-configuration))
12656 (delete-other-windows)
12657 (move-marker org-log-note-return-to (point))
12658 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12659 (goto-char org-log-note-marker)
12660 (org-switch-to-buffer-other-window "*Org Note*")
12661 (erase-buffer)
12662 (if (memq org-log-note-how '(time state))
12663 (let (current-prefix-arg) (org-store-log-note))
12664 (let ((org-inhibit-startup t)) (org-mode))
12665 (insert (format "# Insert note for %s.
12666 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12667 (cond
12668 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12669 ((eq org-log-note-purpose 'done) "closed todo item")
12670 ((eq org-log-note-purpose 'state)
12671 (format "state change from \"%s\" to \"%s\""
12672 (or org-log-note-previous-state "")
12673 (or org-log-note-state "")))
12674 ((eq org-log-note-purpose 'reschedule)
12675 "rescheduling")
12676 ((eq org-log-note-purpose 'delschedule)
12677 "no longer scheduled")
12678 ((eq org-log-note-purpose 'redeadline)
12679 "changing deadline")
12680 ((eq org-log-note-purpose 'deldeadline)
12681 "removing deadline")
12682 ((eq org-log-note-purpose 'refile)
12683 "refiling")
12684 ((eq org-log-note-purpose 'note)
12685 "this entry")
12686 (t (error "This should not happen")))))
12687 (if org-log-note-extra (insert org-log-note-extra))
12688 (org-set-local 'org-finish-function 'org-store-log-note)
12689 (run-hooks 'org-log-buffer-setup-hook)))
12691 (defvar org-note-abort nil) ; dynamically scoped
12692 (defun org-store-log-note ()
12693 "Finish taking a log note, and insert it to where it belongs."
12694 (let ((txt (buffer-string))
12695 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12696 lines ind bul)
12697 (kill-buffer (current-buffer))
12698 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12699 (setq txt (replace-match "" t t txt)))
12700 (if (string-match "\\s-+\\'" txt)
12701 (setq txt (replace-match "" t t txt)))
12702 (setq lines (org-split-string txt "\n"))
12703 (when (and note (string-match "\\S-" note))
12704 (setq note
12705 (org-replace-escapes
12706 note
12707 (list (cons "%u" (user-login-name))
12708 (cons "%U" user-full-name)
12709 (cons "%t" (format-time-string
12710 (org-time-stamp-format 'long 'inactive)
12711 org-log-note-effective-time))
12712 (cons "%T" (format-time-string
12713 (org-time-stamp-format 'long nil)
12714 org-log-note-effective-time))
12715 (cons "%d" (format-time-string
12716 (org-time-stamp-format nil 'inactive)
12717 org-log-note-effective-time))
12718 (cons "%D" (format-time-string
12719 (org-time-stamp-format nil nil)
12720 org-log-note-effective-time))
12721 (cons "%s" (if org-log-note-state
12722 (concat "\"" org-log-note-state "\"")
12723 ""))
12724 (cons "%S" (if org-log-note-previous-state
12725 (concat "\"" org-log-note-previous-state "\"")
12726 "\"\"")))))
12727 (if lines (setq note (concat note " \\\\")))
12728 (push note lines))
12729 (when (or current-prefix-arg org-note-abort)
12730 (when org-log-into-drawer
12731 (org-remove-empty-drawer-at
12732 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12733 org-log-note-marker))
12734 (setq lines nil))
12735 (when lines
12736 (with-current-buffer (marker-buffer org-log-note-marker)
12737 (save-excursion
12738 (goto-char org-log-note-marker)
12739 (move-marker org-log-note-marker nil)
12740 (end-of-line 1)
12741 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12742 (setq ind (save-excursion
12743 (if (ignore-errors (goto-char (org-in-item-p)))
12744 (let ((struct (org-list-struct)))
12745 (org-list-get-ind
12746 (org-list-get-top-point struct) struct))
12747 (skip-chars-backward " \r\t\n")
12748 (cond
12749 ((and (org-at-heading-p)
12750 org-adapt-indentation)
12751 (1+ (org-current-level)))
12752 ((org-at-heading-p) 0)
12753 (t (org-get-indentation))))))
12754 (setq bul (org-list-bullet-string "-"))
12755 (org-indent-line-to ind)
12756 (insert bul (pop lines))
12757 (let ((ind-body (+ (length bul) ind)))
12758 (while lines
12759 (insert "\n")
12760 (org-indent-line-to ind-body)
12761 (insert (pop lines))))
12762 (message "Note stored")
12763 (org-back-to-heading t)
12764 (org-cycle-hide-drawers 'children)))))
12765 (set-window-configuration org-log-note-window-configuration)
12766 (with-current-buffer (marker-buffer org-log-note-return-to)
12767 (goto-char org-log-note-return-to))
12768 (move-marker org-log-note-return-to nil)
12769 (and org-log-post-message (message "%s" org-log-post-message)))
12771 (defun org-remove-empty-drawer-at (drawer pos)
12772 "Remove an empty drawer DRAWER at position POS.
12773 POS may also be a marker."
12774 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12775 (save-excursion
12776 (save-restriction
12777 (widen)
12778 (goto-char pos)
12779 (if (org-in-regexp
12780 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12781 (replace-match ""))))))
12783 (defvar org-ts-type nil)
12784 (defun org-sparse-tree (&optional arg type)
12785 "Create a sparse tree, prompt for the details.
12786 This command can create sparse trees. You first need to select the type
12787 of match used to create the tree:
12789 t Show all TODO entries.
12790 T Show entries with a specific TODO keyword.
12791 m Show entries selected by a tags/property match.
12792 p Enter a property name and its value (both with completion on existing
12793 names/values) and show entries with that property.
12794 r Show entries matching a regular expression (`/' can be used as well).
12795 b Show deadlines and scheduled items before a date.
12796 a Show deadlines and scheduled items after a date.
12797 d Show deadlines due within `org-deadline-warning-days'.
12798 D Show deadlines and scheduled items between a date range."
12799 (interactive "P")
12800 (let (ans kwd value ts-type)
12801 (setq type (or type org-sparse-tree-default-date-type))
12802 (setq org-ts-type type)
12803 (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"
12804 (cond ((eq type 'all) "all timestamps")
12805 ((eq type 'scheduled) "only scheduled")
12806 ((eq type 'deadline) "only deadline")
12807 ((eq type 'active) "only active timestamps")
12808 ((eq type 'inactive) "only inactive timestamps")
12809 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12810 (t "scheduled/deadline")))
12811 (setq ans (read-char-exclusive))
12812 (cond
12813 ((equal ans ?c)
12814 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12815 ((equal ans ?d)
12816 (call-interactively 'org-check-deadlines))
12817 ((equal ans ?b)
12818 (call-interactively 'org-check-before-date))
12819 ((equal ans ?a)
12820 (call-interactively 'org-check-after-date))
12821 ((equal ans ?D)
12822 (call-interactively 'org-check-dates-range))
12823 ((equal ans ?t)
12824 (org-show-todo-tree nil))
12825 ((equal ans ?T)
12826 (org-show-todo-tree '(4)))
12827 ((member ans '(?T ?m))
12828 (call-interactively 'org-match-sparse-tree))
12829 ((member ans '(?p ?P))
12830 (setq kwd (org-icompleting-read "Property: "
12831 (mapcar 'list (org-buffer-property-keys))))
12832 (setq value (org-icompleting-read "Value: "
12833 (mapcar 'list (org-property-values kwd))))
12834 (unless (string-match "\\`{.*}\\'" value)
12835 (setq value (concat "\"" value "\"")))
12836 (org-match-sparse-tree arg (concat kwd "=" value)))
12837 ((member ans '(?r ?R ?/))
12838 (call-interactively 'org-occur))
12839 (t (error "No such sparse tree command \"%c\"" ans)))))
12841 (defvar org-occur-highlights nil
12842 "List of overlays used for occur matches.")
12843 (make-variable-buffer-local 'org-occur-highlights)
12844 (defvar org-occur-parameters nil
12845 "Parameters of the active org-occur calls.
12846 This is a list, each call to org-occur pushes as cons cell,
12847 containing the regular expression and the callback, onto the list.
12848 The list can contain several entries if `org-occur' has been called
12849 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12850 will only contain one set of parameters. When the highlights are
12851 removed (for example with `C-c C-c', or with the next edit (depending
12852 on `org-remove-highlights-with-change'), this variable is emptied
12853 as well.")
12854 (make-variable-buffer-local 'org-occur-parameters)
12856 (defun org-occur (regexp &optional keep-previous callback)
12857 "Make a compact tree which shows all matches of REGEXP.
12858 The tree will show the lines where the regexp matches, and all higher
12859 headlines above the match. It will also show the heading after the match,
12860 to make sure editing the matching entry is easy.
12861 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12862 call to `org-occur' will be kept, to allow stacking of calls to this
12863 command.
12864 If CALLBACK is non-nil, it is a function which is called to confirm
12865 that the match should indeed be shown."
12866 (interactive "sRegexp: \nP")
12867 (when (equal regexp "")
12868 (error "Regexp cannot be empty"))
12869 (unless keep-previous
12870 (org-remove-occur-highlights nil nil t))
12871 (push (cons regexp callback) org-occur-parameters)
12872 (let ((cnt 0))
12873 (save-excursion
12874 (goto-char (point-min))
12875 (if (or (not keep-previous) ; do not want to keep
12876 (not org-occur-highlights)) ; no previous matches
12877 ;; hide everything
12878 (org-overview))
12879 (while (re-search-forward regexp nil t)
12880 (when (or (not callback)
12881 (save-match-data (funcall callback)))
12882 (setq cnt (1+ cnt))
12883 (when org-highlight-sparse-tree-matches
12884 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12885 (org-show-context 'occur-tree))))
12886 (when org-remove-highlights-with-change
12887 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12888 nil 'local))
12889 (unless org-sparse-tree-open-archived-trees
12890 (org-hide-archived-subtrees (point-min) (point-max)))
12891 (run-hooks 'org-occur-hook)
12892 (if (org-called-interactively-p 'interactive)
12893 (message "%d match(es) for regexp %s" cnt regexp))
12894 cnt))
12896 (defun org-occur-next-match (&optional n reset)
12897 "Function for `next-error-function' to find sparse tree matches.
12898 N is the number of matches to move, when negative move backwards.
12899 RESET is entirely ignored - this function always goes back to the
12900 starting point when no match is found."
12901 (let* ((limit (if (< n 0) (point-min) (point-max)))
12902 (search-func (if (< n 0)
12903 'previous-single-char-property-change
12904 'next-single-char-property-change))
12905 (n (abs n))
12906 (pos (point))
12908 (catch 'exit
12909 (while (setq p1 (funcall search-func (point) 'org-type))
12910 (when (equal p1 limit)
12911 (goto-char pos)
12912 (error "No more matches"))
12913 (when (equal (get-char-property p1 'org-type) 'org-occur)
12914 (setq n (1- n))
12915 (when (= n 0)
12916 (goto-char p1)
12917 (throw 'exit (point))))
12918 (goto-char p1))
12919 (goto-char p1)
12920 (error "No more matches"))))
12922 (defun org-show-context (&optional key)
12923 "Make sure point and context are visible.
12924 How much context is shown depends upon the variables
12925 `org-show-hierarchy-above', `org-show-following-heading',
12926 `org-show-entry-below' and `org-show-siblings'."
12927 (let ((heading-p (org-at-heading-p t))
12928 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12929 (following-p (org-get-alist-option org-show-following-heading key))
12930 (entry-p (org-get-alist-option org-show-entry-below key))
12931 (siblings-p (org-get-alist-option org-show-siblings key)))
12932 (catch 'exit
12933 ;; Show heading or entry text
12934 (if (and heading-p (not entry-p))
12935 (org-flag-heading nil) ; only show the heading
12936 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12937 (org-show-hidden-entry))) ; show entire entry
12938 (when following-p
12939 ;; Show next sibling, or heading below text
12940 (save-excursion
12941 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12942 (org-flag-heading nil))))
12943 (when siblings-p (org-show-siblings))
12944 (when hierarchy-p
12945 ;; show all higher headings, possibly with siblings
12946 (save-excursion
12947 (while (and (condition-case nil
12948 (progn (org-up-heading-all 1) t)
12949 (error nil))
12950 (not (bobp)))
12951 (org-flag-heading nil)
12952 (when siblings-p (org-show-siblings))))))))
12954 (defvar org-reveal-start-hook nil
12955 "Hook run before revealing a location.")
12957 (defun org-reveal (&optional siblings)
12958 "Show current entry, hierarchy above it, and the following headline.
12959 This can be used to show a consistent set of context around locations
12960 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12961 not t for the search context.
12963 With optional argument SIBLINGS, on each level of the hierarchy all
12964 siblings are shown. This repairs the tree structure to what it would
12965 look like when opened with hierarchical calls to `org-cycle'.
12966 With double optional argument \\[universal-argument] \\[universal-argument], \
12967 go to the parent and show the
12968 entire tree."
12969 (interactive "P")
12970 (run-hooks 'org-reveal-start-hook)
12971 (let ((org-show-hierarchy-above t)
12972 (org-show-following-heading t)
12973 (org-show-siblings (if siblings t org-show-siblings)))
12974 (org-show-context nil))
12975 (when (equal siblings '(16))
12976 (save-excursion
12977 (when (org-up-heading-safe)
12978 (org-show-subtree)
12979 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12981 (defun org-highlight-new-match (beg end)
12982 "Highlight from BEG to END and mark the highlight is an occur headline."
12983 (let ((ov (make-overlay beg end)))
12984 (overlay-put ov 'face 'secondary-selection)
12985 (overlay-put ov 'org-type 'org-occur)
12986 (push ov org-occur-highlights)))
12988 (defun org-remove-occur-highlights (&optional beg end noremove)
12989 "Remove the occur highlights from the buffer.
12990 BEG and END are ignored. If NOREMOVE is nil, remove this function
12991 from the `before-change-functions' in the current buffer."
12992 (interactive)
12993 (unless org-inhibit-highlight-removal
12994 (mapc 'delete-overlay org-occur-highlights)
12995 (setq org-occur-highlights nil)
12996 (setq org-occur-parameters nil)
12997 (unless noremove
12998 (remove-hook 'before-change-functions
12999 'org-remove-occur-highlights 'local))))
13001 ;;;; Priorities
13003 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13004 "Regular expression matching the priority indicator.")
13006 (defvar org-remove-priority-next-time nil)
13008 (defun org-priority-up ()
13009 "Increase the priority of the current item."
13010 (interactive)
13011 (org-priority 'up))
13013 (defun org-priority-down ()
13014 "Decrease the priority of the current item."
13015 (interactive)
13016 (org-priority 'down))
13018 (defun org-priority (&optional action show)
13019 "Change the priority of an item.
13020 ACTION can be `set', `up', `down', or a character."
13021 (interactive "P")
13022 (if (equal action '(4))
13023 (org-show-priority)
13024 (unless org-enable-priority-commands
13025 (error "Priority commands are disabled"))
13026 (setq action (or action 'set))
13027 (let (current new news have remove)
13028 (save-excursion
13029 (org-back-to-heading t)
13030 (if (looking-at org-priority-regexp)
13031 (setq current (string-to-char (match-string 2))
13032 have t))
13033 (cond
13034 ((eq action 'remove)
13035 (setq remove t new ?\ ))
13036 ((or (eq action 'set)
13037 (if (featurep 'xemacs) (characterp action) (integerp action)))
13038 (if (not (eq action 'set))
13039 (setq new action)
13040 (message "Priority %c-%c, SPC to remove: "
13041 org-highest-priority org-lowest-priority)
13042 (save-match-data
13043 (setq new (read-char-exclusive))))
13044 (if (and (= (upcase org-highest-priority) org-highest-priority)
13045 (= (upcase org-lowest-priority) org-lowest-priority))
13046 (setq new (upcase new)))
13047 (cond ((equal new ?\ ) (setq remove t))
13048 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13049 (error "Priority must be between `%c' and `%c'"
13050 org-highest-priority org-lowest-priority))))
13051 ((eq action 'up)
13052 (setq new (if have
13053 (1- current) ; normal cycling
13054 ;; last priority was empty
13055 (if (eq last-command this-command)
13056 org-lowest-priority ; wrap around empty to lowest
13057 ;; default
13058 (if org-priority-start-cycle-with-default
13059 org-default-priority
13060 (1- org-default-priority))))))
13061 ((eq action 'down)
13062 (setq new (if have
13063 (1+ current) ; normal cycling
13064 ;; last priority was empty
13065 (if (eq last-command this-command)
13066 org-highest-priority ; wrap around empty to highest
13067 ;; default
13068 (if org-priority-start-cycle-with-default
13069 org-default-priority
13070 (1+ org-default-priority))))))
13071 (t (error "Invalid action")))
13072 (if (or (< (upcase new) org-highest-priority)
13073 (> (upcase new) org-lowest-priority))
13074 (if (and (memq action '(up down))
13075 (not have) (not (eq last-command this-command)))
13076 ;; `new' is from default priority
13077 (error
13078 "The default can not be set, see `org-default-priority' why")
13079 ;; normal cycling: `new' is beyond highest/lowest priority
13080 ;; and is wrapped around to the empty priority
13081 (setq remove t)))
13082 (setq news (format "%c" new))
13083 (if have
13084 (if remove
13085 (replace-match "" t t nil 1)
13086 (replace-match news t t nil 2))
13087 (if remove
13088 (error "No priority cookie found in line")
13089 (let ((case-fold-search nil))
13090 (looking-at org-todo-line-regexp))
13091 (if (match-end 2)
13092 (progn
13093 (goto-char (match-end 2))
13094 (insert " [#" news "]"))
13095 (goto-char (match-beginning 3))
13096 (insert "[#" news "] "))))
13097 (org-preserve-lc (org-set-tags nil 'align)))
13098 (if remove
13099 (message "Priority removed")
13100 (message "Priority of current item set to %s" news)))))
13102 (defun org-show-priority ()
13103 "Show the priority of the current item.
13104 This priority is composed of the main priority given with the [#A] cookies,
13105 and by additional input from the age of a schedules or deadline entry."
13106 (interactive)
13107 (let ((pri (if (eq major-mode 'org-agenda-mode)
13108 (org-get-at-bol 'priority)
13109 (save-excursion
13110 (save-match-data
13111 (beginning-of-line)
13112 (and (looking-at org-heading-regexp)
13113 (org-get-priority (match-string 0))))))))
13114 (message "Priority is %d" (if pri pri -1000))))
13116 (defun org-get-priority (s)
13117 "Find priority cookie and return priority."
13118 (if (functionp org-get-priority-function)
13119 (funcall org-get-priority-function)
13120 (save-match-data
13121 (if (not (string-match org-priority-regexp s))
13122 (* 1000 (- org-lowest-priority org-default-priority))
13123 (* 1000 (- org-lowest-priority
13124 (string-to-char (match-string 2 s))))))))
13126 ;;;; Tags
13128 (defvar org-agenda-archives-mode)
13129 (defvar org-map-continue-from nil
13130 "Position from where mapping should continue.
13131 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13133 (defvar org-scanner-tags nil
13134 "The current tag list while the tags scanner is running.")
13135 (defvar org-trust-scanner-tags nil
13136 "Should `org-get-tags-at' use the tags for the scanner.
13137 This is for internal dynamical scoping only.
13138 When this is non-nil, the function `org-get-tags-at' will return the value
13139 of `org-scanner-tags' instead of building the list by itself. This
13140 can lead to large speed-ups when the tags scanner is used in a file with
13141 many entries, and when the list of tags is retrieved, for example to
13142 obtain a list of properties. Building the tags list for each entry in such
13143 a file becomes an N^2 operation - but with this variable set, it scales
13144 as N.")
13146 (defun org-scan-tags (action matcher todo-only &optional start-level)
13147 "Scan headline tags with inheritance and produce output ACTION.
13149 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13150 or `agenda' to produce an entry list for an agenda view. It can also be
13151 a Lisp form or a function that should be called at each matched headline, in
13152 this case the return value is a list of all return values from these calls.
13154 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13155 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13156 only lines with a not-done TODO keyword are included in the output.
13157 This should be the same variable that was scoped into
13158 and set by `org-make-tags-matcher' when it constructed MATCHER.
13160 START-LEVEL can be a string with asterisks, reducing the scope to
13161 headlines matching this string."
13162 (require 'org-agenda)
13163 (let* ((re (concat "^"
13164 (if start-level
13165 ;; Get the correct level to match
13166 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13167 org-outline-regexp)
13168 " *\\(\\<\\("
13169 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13170 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13171 (props (list 'face 'default
13172 'done-face 'org-agenda-done
13173 'undone-face 'default
13174 'mouse-face 'highlight
13175 'org-not-done-regexp org-not-done-regexp
13176 'org-todo-regexp org-todo-regexp
13177 'org-complex-heading-regexp org-complex-heading-regexp
13178 'help-echo
13179 (format "mouse-2 or RET jump to org file %s"
13180 (abbreviate-file-name
13181 (or (buffer-file-name (buffer-base-buffer))
13182 (buffer-name (buffer-base-buffer)))))))
13183 (case-fold-search nil)
13184 (org-map-continue-from nil)
13185 lspos tags tags-list
13186 (tags-alist (list (cons 0 org-file-tags)))
13187 (llast 0) rtn rtn1 level category i txt
13188 todo marker entry priority)
13189 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13190 (setq action (list 'lambda nil action)))
13191 (save-excursion
13192 (goto-char (point-min))
13193 (when (eq action 'sparse-tree)
13194 (org-overview)
13195 (org-remove-occur-highlights))
13196 (while (re-search-forward re nil t)
13197 (setq org-map-continue-from nil)
13198 (catch :skip
13199 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13200 tags (if (match-end 4) (org-match-string-no-properties 4)))
13201 (goto-char (setq lspos (match-beginning 0)))
13202 (setq level (org-reduced-level (funcall outline-level))
13203 category (org-get-category))
13204 (setq i llast llast level)
13205 ;; remove tag lists from same and sublevels
13206 (while (>= i level)
13207 (when (setq entry (assoc i tags-alist))
13208 (setq tags-alist (delete entry tags-alist)))
13209 (setq i (1- i)))
13210 ;; add the next tags
13211 (when tags
13212 (setq tags (org-split-string tags ":")
13213 tags-alist
13214 (cons (cons level tags) tags-alist)))
13215 ;; compile tags for current headline
13216 (setq tags-list
13217 (if org-use-tag-inheritance
13218 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13219 tags)
13220 org-scanner-tags tags-list)
13221 (when org-use-tag-inheritance
13222 (setcdr (car tags-alist)
13223 (mapcar (lambda (x)
13224 (setq x (copy-sequence x))
13225 (org-add-prop-inherited x))
13226 (cdar tags-alist))))
13227 (when (and tags org-use-tag-inheritance
13228 (or (not (eq t org-use-tag-inheritance))
13229 org-tags-exclude-from-inheritance))
13230 ;; selective inheritance, remove uninherited ones
13231 (setcdr (car tags-alist)
13232 (org-remove-uninherited-tags (cdar tags-alist))))
13233 (when (and
13235 ;; eval matcher only when the todo condition is OK
13236 (and (or (not todo-only) (member todo org-not-done-keywords))
13237 (let ((case-fold-search t) (org-trust-scanner-tags t))
13238 (eval matcher)))
13240 ;; Call the skipper, but return t if it does not skip,
13241 ;; so that the `and' form continues evaluating
13242 (progn
13243 (unless (eq action 'sparse-tree) (org-agenda-skip))
13246 ;; Check if timestamps are deselecting this entry
13247 (or (not todo-only)
13248 (and (member todo org-not-done-keywords)
13249 (or (not org-agenda-tags-todo-honor-ignore-options)
13250 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13252 ;; Extra check for the archive tag
13253 ;; FIXME: Does the skipper already do this????
13255 (not (member org-archive-tag tags-list))
13256 ;; we have an archive tag, should we use this anyway?
13257 (or (not org-agenda-skip-archived-trees)
13258 (and (eq action 'agenda) org-agenda-archives-mode))))
13260 ;; select this headline
13262 (cond
13263 ((eq action 'sparse-tree)
13264 (and org-highlight-sparse-tree-matches
13265 (org-get-heading) (match-end 0)
13266 (org-highlight-new-match
13267 (match-beginning 1) (match-end 1)))
13268 (org-show-context 'tags-tree))
13269 ((eq action 'agenda)
13270 (setq txt (org-agenda-format-item
13272 (concat
13273 (if (eq org-tags-match-list-sublevels 'indented)
13274 (make-string (1- level) ?.) "")
13275 (org-get-heading))
13276 category
13277 tags-list)
13278 priority (org-get-priority txt))
13279 (goto-char lspos)
13280 (setq marker (org-agenda-new-marker))
13281 (org-add-props txt props
13282 'org-marker marker 'org-hd-marker marker 'org-category category
13283 'todo-state todo
13284 'priority priority 'type "tagsmatch")
13285 (push txt rtn))
13286 ((functionp action)
13287 (setq org-map-continue-from nil)
13288 (save-excursion
13289 (setq rtn1 (funcall action))
13290 (push rtn1 rtn)))
13291 (t (error "Invalid action")))
13293 ;; if we are to skip sublevels, jump to end of subtree
13294 (unless org-tags-match-list-sublevels
13295 (org-end-of-subtree t)
13296 (backward-char 1))))
13297 ;; Get the correct position from where to continue
13298 (if org-map-continue-from
13299 (goto-char org-map-continue-from)
13300 (and (= (point) lspos) (end-of-line 1)))))
13301 (when (and (eq action 'sparse-tree)
13302 (not org-sparse-tree-open-archived-trees))
13303 (org-hide-archived-subtrees (point-min) (point-max)))
13304 (nreverse rtn)))
13306 (defun org-remove-uninherited-tags (tags)
13307 "Remove all tags that are not inherited from the list TAGS."
13308 (cond
13309 ((eq org-use-tag-inheritance t)
13310 (if org-tags-exclude-from-inheritance
13311 (org-delete-all org-tags-exclude-from-inheritance tags)
13312 tags))
13313 ((not org-use-tag-inheritance) nil)
13314 ((stringp org-use-tag-inheritance)
13315 (delq nil (mapcar
13316 (lambda (x)
13317 (if (and (string-match org-use-tag-inheritance x)
13318 (not (member x org-tags-exclude-from-inheritance)))
13319 x nil))
13320 tags)))
13321 ((listp org-use-tag-inheritance)
13322 (delq nil (mapcar
13323 (lambda (x)
13324 (if (member x org-use-tag-inheritance) x nil))
13325 tags)))))
13327 (defun org-match-sparse-tree (&optional todo-only match)
13328 "Create a sparse tree according to tags string MATCH.
13329 MATCH can contain positive and negative selection of tags, like
13330 \"+WORK+URGENT-WITHBOSS\".
13331 If optional argument TODO-ONLY is non-nil, only select lines that are
13332 also TODO lines."
13333 (interactive "P")
13334 (org-agenda-prepare-buffers (list (current-buffer)))
13335 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13337 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13339 (defvar org-cached-props nil)
13340 (defun org-cached-entry-get (pom property)
13341 (if (or (eq t org-use-property-inheritance)
13342 (and (stringp org-use-property-inheritance)
13343 (string-match org-use-property-inheritance property))
13344 (and (listp org-use-property-inheritance)
13345 (member property org-use-property-inheritance)))
13346 ;; Caching is not possible, check it directly
13347 (org-entry-get pom property 'inherit)
13348 ;; Get all properties, so that we can do complicated checks easily
13349 (cdr (assoc property (or org-cached-props
13350 (setq org-cached-props
13351 (org-entry-properties pom)))))))
13353 (defun org-global-tags-completion-table (&optional files)
13354 "Return the list of all tags in all agenda buffer/files.
13355 Optional FILES argument is a list of files which can be used
13356 instead of the agenda files."
13357 (save-excursion
13358 (org-uniquify
13359 (delq nil
13360 (apply 'append
13361 (mapcar
13362 (lambda (file)
13363 (set-buffer (find-file-noselect file))
13364 (append (org-get-buffer-tags)
13365 (mapcar (lambda (x) (if (stringp (car-safe x))
13366 (list (car-safe x)) nil))
13367 org-tag-alist)))
13368 (if (and files (car files))
13369 files
13370 (org-agenda-files))))))))
13372 (defun org-make-tags-matcher (match)
13373 "Create the TAGS/TODO matcher form for the selection string MATCH.
13375 The variable `todo-only' is scoped dynamically into this function.
13376 It will be set to t if the matcher restricts matching to TODO entries,
13377 otherwise will not be touched.
13379 Returns a cons of the selection string MATCH and the constructed
13380 lisp form implementing the matcher. The matcher is to be evaluated
13381 at an Org entry, with point on the headline, and returns t if the
13382 entry matches the selection string MATCH. The returned lisp form
13383 references two variables with information about the entry, which
13384 must be bound around the form's evaluation: todo, the TODO keyword
13385 at the entry (or nil of none); and tags-list, the list of all tags
13386 at the entry including inherited ones. Additionally, the category
13387 of the entry (if any) must be specified as the text property
13388 'org-category on the headline.
13390 See also `org-scan-tags'.
13392 (declare (special todo-only))
13393 (unless (boundp 'todo-only)
13394 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13395 (unless match
13396 ;; Get a new match request, with completion
13397 (let ((org-last-tags-completion-table
13398 (org-global-tags-completion-table)))
13399 (setq match (org-completing-read-no-i
13400 "Match: " 'org-tags-completion-function nil nil nil
13401 'org-tags-history))))
13403 ;; Parse the string and create a lisp form
13404 (let ((match0 match)
13405 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13406 minus tag mm
13407 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13408 orterms term orlist re-p str-p level-p level-op time-p
13409 prop-p pn pv po gv rest)
13410 (if (string-match "/+" match)
13411 ;; match contains also a todo-matching request
13412 (progn
13413 (setq tagsmatch (substring match 0 (match-beginning 0))
13414 todomatch (substring match (match-end 0)))
13415 (if (string-match "^!" todomatch)
13416 (setq todo-only t todomatch (substring todomatch 1)))
13417 (if (string-match "^\\s-*$" todomatch)
13418 (setq todomatch nil)))
13419 ;; only matching tags
13420 (setq tagsmatch match todomatch nil))
13422 ;; Make the tags matcher
13423 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13424 (setq tagsmatcher t)
13425 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13426 (while (setq term (pop orterms))
13427 (while (and (equal (substring term -1) "\\") orterms)
13428 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13429 (while (string-match re term)
13430 (setq rest (substring term (match-end 0))
13431 minus (and (match-end 1)
13432 (equal (match-string 1 term) "-"))
13433 tag (save-match-data (replace-regexp-in-string
13434 "\\\\-" "-"
13435 (match-string 2 term)))
13436 re-p (equal (string-to-char tag) ?{)
13437 level-p (match-end 4)
13438 prop-p (match-end 5)
13439 mm (cond
13440 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13441 (level-p
13442 (setq level-op (org-op-to-function (match-string 3 term)))
13443 `(,level-op level ,(string-to-number
13444 (match-string 4 term))))
13445 (prop-p
13446 (setq pn (match-string 5 term)
13447 po (match-string 6 term)
13448 pv (match-string 7 term)
13449 re-p (equal (string-to-char pv) ?{)
13450 str-p (equal (string-to-char pv) ?\")
13451 time-p (save-match-data
13452 (string-match "^\"[[<].*[]>]\"$" pv))
13453 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13454 (if time-p (setq pv (org-matcher-time pv)))
13455 (setq po (org-op-to-function po (if time-p 'time str-p)))
13456 (cond
13457 ((equal pn "CATEGORY")
13458 (setq gv '(get-text-property (point) 'org-category)))
13459 ((equal pn "TODO")
13460 (setq gv 'todo))
13462 (setq gv `(org-cached-entry-get nil ,pn))))
13463 (if re-p
13464 (if (eq po 'org<>)
13465 `(not (string-match ,pv (or ,gv "")))
13466 `(string-match ,pv (or ,gv "")))
13467 (if str-p
13468 `(,po (or ,gv "") ,pv)
13469 `(,po (string-to-number (or ,gv ""))
13470 ,(string-to-number pv) ))))
13471 (t `(member ,tag tags-list)))
13472 mm (if minus (list 'not mm) mm)
13473 term rest)
13474 (push mm tagsmatcher))
13475 (push (if (> (length tagsmatcher) 1)
13476 (cons 'and tagsmatcher)
13477 (car tagsmatcher))
13478 orlist)
13479 (setq tagsmatcher nil))
13480 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13481 (setq tagsmatcher
13482 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13483 ;; Make the todo matcher
13484 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13485 (setq todomatcher t)
13486 (setq orterms (org-split-string todomatch "|") orlist nil)
13487 (while (setq term (pop orterms))
13488 (while (string-match re term)
13489 (setq minus (and (match-end 1)
13490 (equal (match-string 1 term) "-"))
13491 kwd (match-string 2 term)
13492 re-p (equal (string-to-char kwd) ?{)
13493 term (substring term (match-end 0))
13494 mm (if re-p
13495 `(string-match ,(substring kwd 1 -1) todo)
13496 (list 'equal 'todo kwd))
13497 mm (if minus (list 'not mm) mm))
13498 (push mm todomatcher))
13499 (push (if (> (length todomatcher) 1)
13500 (cons 'and todomatcher)
13501 (car todomatcher))
13502 orlist)
13503 (setq todomatcher nil))
13504 (setq todomatcher (if (> (length orlist) 1)
13505 (cons 'or orlist) (car orlist))))
13507 ;; Return the string and lisp forms of the matcher
13508 (setq matcher (if todomatcher
13509 (list 'and tagsmatcher todomatcher)
13510 tagsmatcher))
13511 (when todo-only
13512 (setq matcher (list 'and '(member todo org-not-done-keywords)
13513 matcher)))
13514 (cons match0 matcher)))
13516 (defun org-op-to-function (op &optional stringp)
13517 "Turn an operator into the appropriate function."
13518 (setq op
13519 (cond
13520 ((equal op "<" ) '(< string< org-time<))
13521 ((equal op ">" ) '(> org-string> org-time>))
13522 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13523 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13524 ((member op '("=" "==")) '(= string= org-time=))
13525 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13526 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13528 (defun org<> (a b) (not (= a b)))
13529 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13530 (defun org-string>= (a b) (not (string< a b)))
13531 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13532 (defun org-string<> (a b) (not (string= a b)))
13533 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13534 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13535 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13536 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13537 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13538 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13539 (defun org-2ft (s)
13540 "Convert S to a floating point time.
13541 If S is already a number, just return it. If it is a string, parse
13542 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13543 (cond
13544 ((numberp s) s)
13545 ((stringp s)
13546 (condition-case nil
13547 (float-time (apply 'encode-time (org-parse-time-string s)))
13548 (error 0.)))
13549 (t 0.)))
13551 (defun org-time-today ()
13552 "Time in seconds today at 0:00.
13553 Returns the float number of seconds since the beginning of the
13554 epoch to the beginning of today (00:00)."
13555 (float-time (apply 'encode-time
13556 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13558 (defun org-matcher-time (s)
13559 "Interpret a time comparison value."
13560 (save-match-data
13561 (cond
13562 ((string= s "<now>") (float-time))
13563 ((string= s "<today>") (org-time-today))
13564 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13565 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13566 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13567 (+ (org-time-today)
13568 (* (string-to-number (match-string 1 s))
13569 (cdr (assoc (match-string 2 s)
13570 '(("d" . 86400.0) ("w" . 604800.0)
13571 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13572 (t (org-2ft s)))))
13574 (defun org-match-any-p (re list)
13575 "Does re match any element of list?"
13576 (setq list (mapcar (lambda (x) (string-match re x)) list))
13577 (delq nil list))
13579 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13580 (defvar org-tags-overlay (make-overlay 1 1))
13581 (org-detach-overlay org-tags-overlay)
13583 (defun org-get-local-tags-at (&optional pos)
13584 "Get a list of tags defined in the current headline."
13585 (org-get-tags-at pos 'local))
13587 (defun org-get-local-tags ()
13588 "Get a list of tags defined in the current headline."
13589 (org-get-tags-at nil 'local))
13591 (defun org-get-tags-at (&optional pos local)
13592 "Get a list of all headline tags applicable at POS.
13593 POS defaults to point. If tags are inherited, the list contains
13594 the targets in the same sequence as the headlines appear, i.e.
13595 the tags of the current headline come last.
13596 When LOCAL is non-nil, only return tags from the current headline,
13597 ignore inherited ones."
13598 (interactive)
13599 (if (and org-trust-scanner-tags
13600 (or (not pos) (equal pos (point)))
13601 (not local))
13602 org-scanner-tags
13603 (let (tags ltags lastpos parent)
13604 (save-excursion
13605 (save-restriction
13606 (widen)
13607 (goto-char (or pos (point)))
13608 (save-match-data
13609 (catch 'done
13610 (condition-case nil
13611 (progn
13612 (org-back-to-heading t)
13613 (while (not (equal lastpos (point)))
13614 (setq lastpos (point))
13615 (when (looking-at
13616 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13617 (setq ltags (org-split-string
13618 (org-match-string-no-properties 1) ":"))
13619 (when parent
13620 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13621 (setq tags (append
13622 (if parent
13623 (org-remove-uninherited-tags ltags)
13624 ltags)
13625 tags)))
13626 (or org-use-tag-inheritance (throw 'done t))
13627 (if local (throw 'done t))
13628 (or (org-up-heading-safe) (error nil))
13629 (setq parent t)))
13630 (error nil)))))
13631 (if local
13632 tags
13633 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13635 (defun org-add-prop-inherited (s)
13636 (add-text-properties 0 (length s) '(inherited t) s)
13639 (defun org-toggle-tag (tag &optional onoff)
13640 "Toggle the tag TAG for the current line.
13641 If ONOFF is `on' or `off', don't toggle but set to this state."
13642 (let (res current)
13643 (save-excursion
13644 (org-back-to-heading t)
13645 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13646 (point-at-eol) t)
13647 (progn
13648 (setq current (match-string 1))
13649 (replace-match ""))
13650 (setq current ""))
13651 (setq current (nreverse (org-split-string current ":")))
13652 (cond
13653 ((eq onoff 'on)
13654 (setq res t)
13655 (or (member tag current) (push tag current)))
13656 ((eq onoff 'off)
13657 (or (not (member tag current)) (setq current (delete tag current))))
13658 (t (if (member tag current)
13659 (setq current (delete tag current))
13660 (setq res t)
13661 (push tag current))))
13662 (end-of-line 1)
13663 (if current
13664 (progn
13665 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13666 (org-set-tags nil t))
13667 (delete-horizontal-space))
13668 (run-hooks 'org-after-tags-change-hook))
13669 res))
13671 (defun org-align-tags-here (to-col)
13672 ;; Assumes that this is a headline
13673 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13674 (beginning-of-line 1)
13675 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13676 (< pos (match-beginning 2)))
13677 (progn
13678 (setq tags-l (- (match-end 2) (match-beginning 2)))
13679 (goto-char (match-beginning 1))
13680 (insert " ")
13681 (delete-region (point) (1+ (match-beginning 2)))
13682 (setq ncol (max (current-column)
13683 (1+ col)
13684 (if (> to-col 0)
13685 to-col
13686 (- (abs to-col) tags-l))))
13687 (setq p (point))
13688 (insert (make-string (- ncol (current-column)) ?\ ))
13689 (setq ncol (current-column))
13690 (when indent-tabs-mode (tabify p (point-at-eol)))
13691 (org-move-to-column (min ncol col) t))
13692 (goto-char pos))))
13694 (defun org-set-tags-command (&optional arg just-align)
13695 "Call the set-tags command for the current entry."
13696 (interactive "P")
13697 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13698 (org-set-tags arg just-align)
13699 (save-excursion
13700 (org-back-to-heading t)
13701 (org-set-tags arg just-align))))
13703 (defun org-set-tags-to (data)
13704 "Set the tags of the current entry to DATA, replacing the current tags.
13705 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13706 If DATA is nil or the empty string, any tags will be removed."
13707 (interactive "sTags: ")
13708 (setq data
13709 (cond
13710 ((eq data nil) "")
13711 ((equal data "") "")
13712 ((stringp data)
13713 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13714 ":"))
13715 ((listp data)
13716 (concat ":" (mapconcat 'identity data ":") ":"))))
13717 (when data
13718 (save-excursion
13719 (org-back-to-heading t)
13720 (when (looking-at org-complex-heading-regexp)
13721 (if (match-end 5)
13722 (progn
13723 (goto-char (match-beginning 5))
13724 (insert data)
13725 (delete-region (point) (point-at-eol))
13726 (org-set-tags nil 'align))
13727 (goto-char (point-at-eol))
13728 (insert " " data)
13729 (org-set-tags nil 'align)))
13730 (beginning-of-line 1)
13731 (if (looking-at ".*?\\([ \t]+\\)$")
13732 (delete-region (match-beginning 1) (match-end 1))))))
13734 (defun org-align-all-tags ()
13735 "Align the tags i all headings."
13736 (interactive)
13737 (save-excursion
13738 (or (ignore-errors (org-back-to-heading t))
13739 (outline-next-heading))
13740 (if (org-at-heading-p)
13741 (org-set-tags t)
13742 (message "No headings"))))
13744 (defvar org-indent-indentation-per-level)
13745 (defun org-set-tags (&optional arg just-align)
13746 "Set the tags for the current headline.
13747 With prefix ARG, realign all tags in headings in the current buffer."
13748 (interactive "P")
13749 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13750 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13751 'region-start-level 'region))
13752 org-loop-over-headlines-in-active-region)
13753 (org-map-entries
13754 ;; We don't use ARG and JUST-ALIGN here these args are not
13755 ;; useful when looping over headlines
13756 `(org-set-tags)
13757 org-loop-over-headlines-in-active-region
13758 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13759 (let* ((re org-outline-regexp-bol)
13760 (current (unless arg (org-get-tags-string)))
13761 (col (current-column))
13762 (org-setting-tags t)
13763 table current-tags inherited-tags ; computed below when needed
13764 tags p0 c0 c1 rpl di tc level)
13765 (if arg
13766 (save-excursion
13767 (goto-char (point-min))
13768 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13769 (while (re-search-forward re nil t)
13770 (org-set-tags nil t)
13771 (end-of-line 1)))
13772 (message "All tags realigned to column %d" org-tags-column))
13773 (if just-align
13774 (setq tags current)
13775 ;; Get a new set of tags from the user
13776 (save-excursion
13777 (setq table (append org-tag-persistent-alist
13778 (or org-tag-alist (org-get-buffer-tags))
13779 (and
13780 org-complete-tags-always-offer-all-agenda-tags
13781 (org-global-tags-completion-table
13782 (org-agenda-files))))
13783 org-last-tags-completion-table table
13784 current-tags (org-split-string current ":")
13785 inherited-tags (nreverse
13786 (nthcdr (length current-tags)
13787 (nreverse (org-get-tags-at))))
13788 tags
13789 (if (or (eq t org-use-fast-tag-selection)
13790 (and org-use-fast-tag-selection
13791 (delq nil (mapcar 'cdr table))))
13792 (org-fast-tag-selection
13793 current-tags inherited-tags table
13794 (if org-fast-tag-selection-include-todo
13795 org-todo-key-alist))
13796 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13797 (org-trim
13798 (org-icompleting-read "Tags: "
13799 'org-tags-completion-function
13800 nil nil current 'org-tags-history))))))
13801 (while (string-match "[-+&]+" tags)
13802 ;; No boolean logic, just a list
13803 (setq tags (replace-match ":" t t tags))))
13805 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13807 (if org-tags-sort-function
13808 (setq tags (mapconcat 'identity
13809 (sort (org-split-string
13810 tags (org-re "[^[:alnum:]_@#%]+"))
13811 org-tags-sort-function) ":")))
13813 (if (string-match "\\`[\t ]*\\'" tags)
13814 (setq tags "")
13815 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13816 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13818 ;; Insert new tags at the correct column
13819 (beginning-of-line 1)
13820 (setq level (or (and (looking-at org-outline-regexp)
13821 (- (match-end 0) (point) 1))
13823 (cond
13824 ((and (equal current "") (equal tags "")))
13825 ((re-search-forward
13826 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13827 (point-at-eol) t)
13828 (if (equal tags "")
13829 (setq rpl "")
13830 (goto-char (match-beginning 0))
13831 (setq c0 (current-column)
13832 ;; compute offset for the case of org-indent-mode active
13833 di (if org-indent-mode
13834 (* (1- org-indent-indentation-per-level) (1- level))
13836 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13837 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13838 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13839 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13840 (replace-match rpl t t)
13841 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13842 tags)
13843 (t (error "Tags alignment failed")))
13844 (org-move-to-column col)
13845 (unless just-align
13846 (run-hooks 'org-after-tags-change-hook))))))
13848 (defun org-change-tag-in-region (beg end tag off)
13849 "Add or remove TAG for each entry in the region.
13850 This works in the agenda, and also in an org-mode buffer."
13851 (interactive
13852 (list (region-beginning) (region-end)
13853 (let ((org-last-tags-completion-table
13854 (if (derived-mode-p 'org-mode)
13855 (org-get-buffer-tags)
13856 (org-global-tags-completion-table))))
13857 (org-icompleting-read
13858 "Tag: " 'org-tags-completion-function nil nil nil
13859 'org-tags-history))
13860 (progn
13861 (message "[s]et or [r]emove? ")
13862 (equal (read-char-exclusive) ?r))))
13863 (if (fboundp 'deactivate-mark) (deactivate-mark))
13864 (let ((agendap (equal major-mode 'org-agenda-mode))
13865 l1 l2 m buf pos newhead (cnt 0))
13866 (goto-char end)
13867 (setq l2 (1- (org-current-line)))
13868 (goto-char beg)
13869 (setq l1 (org-current-line))
13870 (loop for l from l1 to l2 do
13871 (org-goto-line l)
13872 (setq m (get-text-property (point) 'org-hd-marker))
13873 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13874 (and agendap m))
13875 (setq buf (if agendap (marker-buffer m) (current-buffer))
13876 pos (if agendap m (point)))
13877 (with-current-buffer buf
13878 (save-excursion
13879 (save-restriction
13880 (goto-char pos)
13881 (setq cnt (1+ cnt))
13882 (org-toggle-tag tag (if off 'off 'on))
13883 (setq newhead (org-get-heading)))))
13884 (and agendap (org-agenda-change-all-lines newhead m))))
13885 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13887 (defun org-tags-completion-function (string predicate &optional flag)
13888 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13889 (confirm (lambda (x) (stringp (car x)))))
13890 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13891 (setq s1 (match-string 1 string)
13892 s2 (match-string 2 string))
13893 (setq s1 "" s2 string))
13894 (cond
13895 ((eq flag nil)
13896 ;; try completion
13897 (setq rtn (try-completion s2 ctable confirm))
13898 (if (stringp rtn)
13899 (setq rtn
13900 (concat s1 s2 (substring rtn (length s2))
13901 (if (and org-add-colon-after-tag-completion
13902 (assoc rtn ctable))
13903 ":" ""))))
13904 rtn)
13905 ((eq flag t)
13906 ;; all-completions
13907 (all-completions s2 ctable confirm)
13909 ((eq flag 'lambda)
13910 ;; exact match?
13911 (assoc s2 ctable)))
13914 (defun org-fast-tag-insert (kwd tags face &optional end)
13915 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13916 (insert (format "%-12s" (concat kwd ":"))
13917 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13918 (or end "")))
13920 (defun org-fast-tag-show-exit (flag)
13921 (save-excursion
13922 (org-goto-line 3)
13923 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13924 (replace-match ""))
13925 (when flag
13926 (end-of-line 1)
13927 (org-move-to-column (- (window-width) 19) t)
13928 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13930 (defun org-set-current-tags-overlay (current prefix)
13931 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13932 (if (featurep 'xemacs)
13933 (org-overlay-display org-tags-overlay (concat prefix s)
13934 'secondary-selection)
13935 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13936 (org-overlay-display org-tags-overlay (concat prefix s)))))
13938 (defvar org-last-tag-selection-key nil)
13939 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13940 "Fast tag selection with single keys.
13941 CURRENT is the current list of tags in the headline, INHERITED is the
13942 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13943 possibly with grouping information. TODO-TABLE is a similar table with
13944 TODO keywords, should these have keys assigned to them.
13945 If the keys are nil, a-z are automatically assigned.
13946 Returns the new tags string, or nil to not change the current settings."
13947 (let* ((fulltable (append table todo-table))
13948 (maxlen (apply 'max (mapcar
13949 (lambda (x)
13950 (if (stringp (car x)) (string-width (car x)) 0))
13951 fulltable)))
13952 (buf (current-buffer))
13953 (expert (eq org-fast-tag-selection-single-key 'expert))
13954 (buffer-tags nil)
13955 (fwidth (+ maxlen 3 1 3))
13956 (ncol (/ (- (window-width) 4) fwidth))
13957 (i-face 'org-done)
13958 (c-face 'org-todo)
13959 tg cnt e c char c1 c2 ntable tbl rtn
13960 ov-start ov-end ov-prefix
13961 (exit-after-next org-fast-tag-selection-single-key)
13962 (done-keywords org-done-keywords)
13963 groups ingroup)
13964 (save-excursion
13965 (beginning-of-line 1)
13966 (if (looking-at
13967 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13968 (setq ov-start (match-beginning 1)
13969 ov-end (match-end 1)
13970 ov-prefix "")
13971 (setq ov-start (1- (point-at-eol))
13972 ov-end (1+ ov-start))
13973 (skip-chars-forward "^\n\r")
13974 (setq ov-prefix
13975 (concat
13976 (buffer-substring (1- (point)) (point))
13977 (if (> (current-column) org-tags-column)
13979 (make-string (- org-tags-column (current-column)) ?\ ))))))
13980 (move-overlay org-tags-overlay ov-start ov-end)
13981 (save-window-excursion
13982 (if expert
13983 (set-buffer (get-buffer-create " *Org tags*"))
13984 (delete-other-windows)
13985 (split-window-vertically)
13986 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13987 (erase-buffer)
13988 (org-set-local 'org-done-keywords done-keywords)
13989 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13990 (org-fast-tag-insert "Current" current c-face "\n\n")
13991 (org-fast-tag-show-exit exit-after-next)
13992 (org-set-current-tags-overlay current ov-prefix)
13993 (setq tbl fulltable char ?a cnt 0)
13994 (while (setq e (pop tbl))
13995 (cond
13996 ((equal (car e) :startgroup)
13997 (push '() groups) (setq ingroup t)
13998 (when (not (= cnt 0))
13999 (setq cnt 0)
14000 (insert "\n"))
14001 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14002 ((equal (car e) :endgroup)
14003 (setq ingroup nil cnt 0)
14004 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14005 ((equal e '(:newline))
14006 (when (not (= cnt 0))
14007 (setq cnt 0)
14008 (insert "\n")
14009 (setq e (car tbl))
14010 (while (equal (car tbl) '(:newline))
14011 (insert "\n")
14012 (setq tbl (cdr tbl)))))
14014 (setq tg (copy-sequence (car e)) c2 nil)
14015 (if (cdr e)
14016 (setq c (cdr e))
14017 ;; automatically assign a character.
14018 (setq c1 (string-to-char
14019 (downcase (substring
14020 tg (if (= (string-to-char tg) ?@) 1 0)))))
14021 (if (or (rassoc c1 ntable) (rassoc c1 table))
14022 (while (or (rassoc char ntable) (rassoc char table))
14023 (setq char (1+ char)))
14024 (setq c2 c1))
14025 (setq c (or c2 char)))
14026 (if ingroup (push tg (car groups)))
14027 (setq tg (org-add-props tg nil 'face
14028 (cond
14029 ((not (assoc tg table))
14030 (org-get-todo-face tg))
14031 ((member tg current) c-face)
14032 ((member tg inherited) i-face))))
14033 (if (and (= cnt 0) (not ingroup)) (insert " "))
14034 (insert "[" c "] " tg (make-string
14035 (- fwidth 4 (length tg)) ?\ ))
14036 (push (cons tg c) ntable)
14037 (when (= (setq cnt (1+ cnt)) ncol)
14038 (insert "\n")
14039 (if ingroup (insert " "))
14040 (setq cnt 0)))))
14041 (setq ntable (nreverse ntable))
14042 (insert "\n")
14043 (goto-char (point-min))
14044 (if (not expert) (org-fit-window-to-buffer))
14045 (setq rtn
14046 (catch 'exit
14047 (while t
14048 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14049 (if (not groups) "no " "")
14050 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14051 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14052 (setq org-last-tag-selection-key c)
14053 (cond
14054 ((= c ?\r) (throw 'exit t))
14055 ((= c ?!)
14056 (setq groups (not groups))
14057 (goto-char (point-min))
14058 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14059 ((= c ?\C-c)
14060 (if (not expert)
14061 (org-fast-tag-show-exit
14062 (setq exit-after-next (not exit-after-next)))
14063 (setq expert nil)
14064 (delete-other-windows)
14065 (set-window-buffer (split-window-vertically) " *Org tags*")
14066 (org-switch-to-buffer-other-window " *Org tags*")
14067 (org-fit-window-to-buffer)))
14068 ((or (= c ?\C-g)
14069 (and (= c ?q) (not (rassoc c ntable))))
14070 (org-detach-overlay org-tags-overlay)
14071 (setq quit-flag t))
14072 ((= c ?\ )
14073 (setq current nil)
14074 (if exit-after-next (setq exit-after-next 'now)))
14075 ((= c ?\t)
14076 (condition-case nil
14077 (setq tg (org-icompleting-read
14078 "Tag: "
14079 (or buffer-tags
14080 (with-current-buffer buf
14081 (org-get-buffer-tags)))))
14082 (quit (setq tg "")))
14083 (when (string-match "\\S-" tg)
14084 (add-to-list 'buffer-tags (list tg))
14085 (if (member tg current)
14086 (setq current (delete tg current))
14087 (push tg current)))
14088 (if exit-after-next (setq exit-after-next 'now)))
14089 ((setq e (rassoc c todo-table) tg (car e))
14090 (with-current-buffer buf
14091 (save-excursion (org-todo tg)))
14092 (if exit-after-next (setq exit-after-next 'now)))
14093 ((setq e (rassoc c ntable) tg (car e))
14094 (if (member tg current)
14095 (setq current (delete tg current))
14096 (loop for g in groups do
14097 (if (member tg g)
14098 (mapc (lambda (x)
14099 (setq current (delete x current)))
14100 g)))
14101 (push tg current))
14102 (if exit-after-next (setq exit-after-next 'now))))
14104 ;; Create a sorted list
14105 (setq current
14106 (sort current
14107 (lambda (a b)
14108 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14109 (if (eq exit-after-next 'now) (throw 'exit t))
14110 (goto-char (point-min))
14111 (beginning-of-line 2)
14112 (delete-region (point) (point-at-eol))
14113 (org-fast-tag-insert "Current" current c-face)
14114 (org-set-current-tags-overlay current ov-prefix)
14115 (while (re-search-forward
14116 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14117 (setq tg (match-string 1))
14118 (add-text-properties
14119 (match-beginning 1) (match-end 1)
14120 (list 'face
14121 (cond
14122 ((member tg current) c-face)
14123 ((member tg inherited) i-face)
14124 (t (get-text-property (match-beginning 1) 'face))))))
14125 (goto-char (point-min)))))
14126 (org-detach-overlay org-tags-overlay)
14127 (if rtn
14128 (mapconcat 'identity current ":")
14129 nil))))
14131 (defun org-get-tags-string ()
14132 "Get the TAGS string in the current headline."
14133 (unless (org-at-heading-p t)
14134 (error "Not on a heading"))
14135 (save-excursion
14136 (beginning-of-line 1)
14137 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14138 (org-match-string-no-properties 1)
14139 "")))
14141 (defun org-get-tags ()
14142 "Get the list of tags specified in the current headline."
14143 (org-split-string (org-get-tags-string) ":"))
14145 (defun org-get-buffer-tags ()
14146 "Get a table of all tags used in the buffer, for completion."
14147 (let (tags)
14148 (save-excursion
14149 (goto-char (point-min))
14150 (while (re-search-forward
14151 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14152 (when (equal (char-after (point-at-bol 0)) ?*)
14153 (mapc (lambda (x) (add-to-list 'tags x))
14154 (org-split-string (org-match-string-no-properties 1) ":")))))
14155 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14156 (mapcar 'list tags)))
14158 ;;;; The mapping API
14160 ;;;###autoload
14161 (defun org-map-entries (func &optional match scope &rest skip)
14162 "Call FUNC at each headline selected by MATCH in SCOPE.
14164 FUNC is a function or a lisp form. The function will be called without
14165 arguments, with the cursor positioned at the beginning of the headline.
14166 The return values of all calls to the function will be collected and
14167 returned as a list.
14169 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14170 does not need to preserve point. After evaluation, the cursor will be
14171 moved to the end of the line (presumably of the headline of the
14172 processed entry) and search continues from there. Under some
14173 circumstances, this may not produce the wanted results. For example,
14174 if you have removed (e.g. archived) the current (sub)tree it could
14175 mean that the next entry will be skipped entirely. In such cases, you
14176 can specify the position from where search should continue by making
14177 FUNC set the variable `org-map-continue-from' to the desired buffer
14178 position.
14180 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14181 Only headlines that are matched by this query will be considered during
14182 the iteration. When MATCH is nil or t, all headlines will be
14183 visited by the iteration.
14185 SCOPE determines the scope of this command. It can be any of:
14187 nil The current buffer, respecting the restriction if any
14188 tree The subtree started with the entry at point
14189 region The entries within the active region, if any
14190 region-start-level
14191 The entries within the active region, but only those at
14192 the same level than the first one.
14193 file The current buffer, without restriction
14194 file-with-archives
14195 The current buffer, and any archives associated with it
14196 agenda All agenda files
14197 agenda-with-archives
14198 All agenda files with any archive files associated with them
14199 \(file1 file2 ...)
14200 If this is a list, all files in the list will be scanned
14202 The remaining args are treated as settings for the skipping facilities of
14203 the scanner. The following items can be given here:
14205 archive skip trees with the archive tag.
14206 comment skip trees with the COMMENT keyword
14207 function or Emacs Lisp form:
14208 will be used as value for `org-agenda-skip-function', so whenever
14209 the function returns t, FUNC will not be called for that
14210 entry and search will continue from the point where the
14211 function leaves it.
14213 If your function needs to retrieve the tags including inherited tags
14214 at the *current* entry, you can use the value of the variable
14215 `org-scanner-tags' which will be much faster than getting the value
14216 with `org-get-tags-at'. If your function gets properties with
14217 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14218 to t around the call to `org-entry-properties' to get the same speedup.
14219 Note that if your function moves around to retrieve tags and properties at
14220 a *different* entry, you cannot use these techniques."
14221 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14222 (not (org-region-active-p)))
14223 (let* ((org-agenda-archives-mode nil) ; just to make sure
14224 (org-agenda-skip-archived-trees (memq 'archive skip))
14225 (org-agenda-skip-comment-trees (memq 'comment skip))
14226 (org-agenda-skip-function
14227 (car (org-delete-all '(comment archive) skip)))
14228 (org-tags-match-list-sublevels t)
14229 (start-level (eq scope 'region-start-level))
14230 matcher file res
14231 org-todo-keywords-for-agenda
14232 org-done-keywords-for-agenda
14233 org-todo-keyword-alist-for-agenda
14234 org-drawers-for-agenda
14235 org-tag-alist-for-agenda
14236 todo-only)
14238 (cond
14239 ((eq match t) (setq matcher t))
14240 ((eq match nil) (setq matcher t))
14241 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14243 (save-excursion
14244 (save-restriction
14245 (cond ((eq scope 'tree)
14246 (org-back-to-heading t)
14247 (org-narrow-to-subtree)
14248 (setq scope nil))
14249 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14250 (org-region-active-p))
14251 ;; If needed, set start-level to a string like "2"
14252 (when start-level
14253 (save-excursion
14254 (goto-char (region-beginning))
14255 (unless (org-at-heading-p) (outline-next-heading))
14256 (setq start-level (org-current-level))))
14257 (narrow-to-region (region-beginning)
14258 (save-excursion
14259 (goto-char (region-end))
14260 (unless (and (bolp) (org-at-heading-p))
14261 (outline-next-heading))
14262 (point)))
14263 (setq scope nil)))
14265 (if (not scope)
14266 (progn
14267 (org-agenda-prepare-buffers
14268 (list (buffer-file-name (current-buffer))))
14269 (setq res (org-scan-tags func matcher todo-only start-level)))
14270 ;; Get the right scope
14271 (cond
14272 ((and scope (listp scope) (symbolp (car scope)))
14273 (setq scope (eval scope)))
14274 ((eq scope 'agenda)
14275 (setq scope (org-agenda-files t)))
14276 ((eq scope 'agenda-with-archives)
14277 (setq scope (org-agenda-files t))
14278 (setq scope (org-add-archive-files scope)))
14279 ((eq scope 'file)
14280 (setq scope (list (buffer-file-name))))
14281 ((eq scope 'file-with-archives)
14282 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14283 (org-agenda-prepare-buffers scope)
14284 (while (setq file (pop scope))
14285 (with-current-buffer (org-find-base-buffer-visiting file)
14286 (save-excursion
14287 (save-restriction
14288 (widen)
14289 (goto-char (point-min))
14290 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14291 res)))
14293 ;;;; Properties
14295 ;;; Setting and retrieving properties
14297 (defconst org-special-properties
14298 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14299 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14300 "The special properties valid in Org-mode.
14302 These are properties that are not defined in the property drawer,
14303 but in some other way.")
14305 (defconst org-default-properties
14306 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14307 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14308 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14309 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14310 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14311 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14312 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14313 "Some properties that are used by Org-mode for various purposes.
14314 Being in this list makes sure that they are offered for completion.")
14316 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14317 "Regular expression matching the first line of a property drawer.")
14319 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14320 "Regular expression matching the last line of a property drawer.")
14322 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14323 "Regular expression matching the first line of a property drawer.")
14325 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14326 "Regular expression matching the first line of a property drawer.")
14328 (defconst org-property-drawer-re
14329 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14330 org-property-end-re "\\)\n?")
14331 "Matches an entire property drawer.")
14333 (defconst org-clock-drawer-re
14334 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14335 org-property-end-re "\\)\n?")
14336 "Matches an entire clock drawer.")
14338 (defsubst org-re-property (property)
14339 "Return a regexp matching a PROPERTY line.
14340 Match group 1 will be set to the value."
14341 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14343 (defsubst org-re-property-keyword (property)
14344 "Return a regexp matching a PROPERTY line, possibly with no
14345 value for the property."
14346 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14348 (defun org-property-action ()
14349 "Do an action on properties."
14350 (interactive)
14351 (let (c)
14352 (org-at-property-p)
14353 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14354 (setq c (read-char-exclusive))
14355 (cond
14356 ((equal c ?s)
14357 (call-interactively 'org-set-property))
14358 ((equal c ?d)
14359 (call-interactively 'org-delete-property))
14360 ((equal c ?D)
14361 (call-interactively 'org-delete-property-globally))
14362 ((equal c ?c)
14363 (call-interactively 'org-compute-property-at-point))
14364 (t (error "No such property action %c" c)))))
14366 (defun org-inc-effort ()
14367 "Increment the value of the effort property in the current entry."
14368 (interactive)
14369 (org-set-effort nil t))
14371 (defun org-set-effort (&optional value increment)
14372 "Set the effort property of the current entry.
14373 With numerical prefix arg, use the nth allowed value, 0 stands for the
14374 10th allowed value.
14376 When INCREMENT is non-nil, set the property to the next allowed value."
14377 (interactive "P")
14378 (if (equal value 0) (setq value 10))
14379 (let* ((completion-ignore-case t)
14380 (prop org-effort-property)
14381 (cur (org-entry-get nil prop))
14382 (allowed (org-property-get-allowed-values nil prop 'table))
14383 (existing (mapcar 'list (org-property-values prop)))
14385 (val (cond
14386 ((stringp value) value)
14387 ((and allowed (integerp value))
14388 (or (car (nth (1- value) allowed))
14389 (car (org-last allowed))))
14390 ((and allowed increment)
14391 (or (caadr (member (list cur) allowed))
14392 (error "Allowed effort values are not set")))
14393 (allowed
14394 (message "Select 1-9,0, [RET%s]: %s"
14395 (if cur (concat "=" cur) "")
14396 (mapconcat 'car allowed " "))
14397 (setq rpl (read-char-exclusive))
14398 (if (equal rpl ?\r)
14400 (setq rpl (- rpl ?0))
14401 (if (equal rpl 0) (setq rpl 10))
14402 (if (and (> rpl 0) (<= rpl (length allowed)))
14403 (car (nth (1- rpl) allowed))
14404 (org-completing-read "Effort: " allowed nil))))
14406 (let (org-completion-use-ido org-completion-use-iswitchb)
14407 (org-completing-read
14408 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14409 (concat "[" cur "]") "")
14410 ": ")
14411 existing nil nil "" nil cur))))))
14412 (unless (equal (org-entry-get nil prop) val)
14413 (org-entry-put nil prop val))
14414 (message "%s is now %s" prop val)))
14416 (defun org-at-property-p ()
14417 "Is cursor inside a property drawer?"
14418 (save-excursion
14419 (beginning-of-line 1)
14420 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14421 (save-match-data ;; Used by calling procedures
14422 (let ((p (point))
14423 (range (unless (org-before-first-heading-p)
14424 (org-get-property-block))))
14425 (and range (<= (car range) p) (< p (cdr range))))))))
14427 (defun org-get-property-block (&optional beg end force)
14428 "Return the (beg . end) range of the body of the property drawer.
14429 BEG and END are the beginning and end of the current subtree, or of
14430 the part before the first headline. If they are not given, they will
14431 be found. If the drawer does not exist and FORCE is non-nil, create
14432 the drawer."
14433 (catch 'exit
14434 (save-excursion
14435 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14436 (progn (org-back-to-heading t) (point))))
14437 (end (or end (and (not (outline-next-heading)) (point-max))
14438 (point))))
14439 (goto-char beg)
14440 (if (re-search-forward org-property-start-re end t)
14441 (setq beg (1+ (match-end 0)))
14442 (if force
14443 (save-excursion
14444 (org-insert-property-drawer)
14445 (setq end (progn (outline-next-heading) (point))))
14446 (throw 'exit nil))
14447 (goto-char beg)
14448 (if (re-search-forward org-property-start-re end t)
14449 (setq beg (1+ (match-end 0)))))
14450 (if (re-search-forward org-property-end-re end t)
14451 (setq end (match-beginning 0))
14452 (or force (throw 'exit nil))
14453 (goto-char beg)
14454 (setq end beg)
14455 (org-indent-line)
14456 (insert ":END:\n"))
14457 (cons beg end)))))
14459 (defun org-entry-properties (&optional pom which specific)
14460 "Get all properties of the entry at point-or-marker POM.
14461 This includes the TODO keyword, the tags, time strings for deadline,
14462 scheduled, and clocking, and any additional properties defined in the
14463 entry. The return value is an alist, keys may occur multiple times
14464 if the property key was used several times.
14465 POM may also be nil, in which case the current entry is used.
14466 If WHICH is nil or `all', get all properties. If WHICH is
14467 `special' or `standard', only get that subclass. If WHICH
14468 is a string only get exactly this property. SPECIFIC can be a string, the
14469 specific property we are interested in. Specifying it can speed
14470 things up because then unnecessary parsing is avoided."
14471 (setq which (or which 'all))
14472 (org-with-point-at pom
14473 (let ((clockstr (substring org-clock-string 0 -1))
14474 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14475 (case-fold-search nil)
14476 beg end range props sum-props key key1 value string clocksum clocksumt)
14477 (save-excursion
14478 (when (condition-case nil
14479 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14480 (error nil))
14481 (setq beg (point))
14482 (setq sum-props (get-text-property (point) 'org-summaries))
14483 (setq clocksum (get-text-property (point) :org-clock-minutes)
14484 clocksumt (get-text-property (point) :org-clock-minutes-today))
14485 (outline-next-heading)
14486 (setq end (point))
14487 (when (memq which '(all special))
14488 ;; Get the special properties, like TODO and tags
14489 (goto-char beg)
14490 (when (and (or (not specific) (string= specific "TODO"))
14491 (looking-at org-todo-line-regexp) (match-end 2))
14492 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14493 (when (and (or (not specific) (string= specific "PRIORITY"))
14494 (looking-at org-priority-regexp))
14495 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14496 (when (or (not specific) (string= specific "FILE"))
14497 (push (cons "FILE" buffer-file-name) props))
14498 (when (and (or (not specific) (string= specific "TAGS"))
14499 (setq value (org-get-tags-string))
14500 (string-match "\\S-" value))
14501 (push (cons "TAGS" value) props))
14502 (when (and (or (not specific) (string= specific "ALLTAGS"))
14503 (setq value (org-get-tags-at)))
14504 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14505 ":"))
14506 props))
14507 (when (or (not specific) (string= specific "BLOCKED"))
14508 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14509 (when (or (not specific)
14510 (member specific
14511 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14512 "TIMESTAMP" "TIMESTAMP_IA")))
14513 (catch 'match
14514 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14515 (setq key (if (match-end 1)
14516 (substring (org-match-string-no-properties 1)
14517 0 -1))
14518 string (if (equal key clockstr)
14519 (org-trim
14520 (buffer-substring-no-properties
14521 (match-beginning 3) (goto-char
14522 (point-at-eol))))
14523 (substring (org-match-string-no-properties 3)
14524 1 -1)))
14525 ;; Get the correct property name from the key. This is
14526 ;; necessary if the user has configured time keywords.
14527 (setq key1 (concat key ":"))
14528 (cond
14529 ((not key)
14530 (setq key
14531 (if (= (char-after (match-beginning 3)) ?\[)
14532 "TIMESTAMP_IA" "TIMESTAMP")))
14533 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14534 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14535 ((equal key1 org-closed-string) (setq key "CLOSED"))
14536 ((equal key1 org-clock-string) (setq key "CLOCK")))
14537 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14538 (progn
14539 (push (cons key string) props)
14540 ;; no need to search further if match is found
14541 (throw 'match t))
14542 (when (or (equal key "CLOCK") (not (assoc key props)))
14543 (push (cons key string) props)))))))
14545 (when (memq which '(all standard))
14546 ;; Get the standard properties, like :PROP: ...
14547 (setq range (org-get-property-block beg end))
14548 (when range
14549 (goto-char (car range))
14550 (while (re-search-forward
14551 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14552 (cdr range) t)
14553 (setq key (org-match-string-no-properties 1)
14554 value (org-trim (or (org-match-string-no-properties 2) "")))
14555 (unless (member key excluded)
14556 (push (cons key (or value "")) props)))))
14557 (if clocksum
14558 (push (cons "CLOCKSUM"
14559 (org-columns-number-to-string (/ (float clocksum) 60.)
14560 'add_times))
14561 props))
14562 (if clocksumt
14563 (push (cons "CLOCKSUM_T"
14564 (org-columns-number-to-string (/ (float clocksumt) 60.)
14565 'add_times))
14566 props))
14567 (unless (assoc "CATEGORY" props)
14568 (push (cons "CATEGORY" (org-get-category)) props))
14569 (append sum-props (nreverse props)))))))
14571 (defun org-entry-get (pom property &optional inherit literal-nil)
14572 "Get value of PROPERTY for entry or content at point-or-marker POM.
14573 If INHERIT is non-nil and the entry does not have the property,
14574 then also check higher levels of the hierarchy.
14575 If INHERIT is the symbol `selective', use inheritance only if the setting
14576 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14577 If the property is present but empty, the return value is the empty string.
14578 If the property is not present at all, nil is returned.
14580 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14581 do not interpret it as the list atom nil. This is used for inheritance
14582 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14583 (org-with-point-at pom
14584 (if (and inherit (if (eq inherit 'selective)
14585 (org-property-inherit-p property)
14587 (org-entry-get-with-inheritance property literal-nil)
14588 (if (member property org-special-properties)
14589 ;; We need a special property. Use `org-entry-properties' to
14590 ;; retrieve it, but specify the wanted property
14591 (cdr (assoc property (org-entry-properties nil 'special property)))
14592 (let* ((range (org-get-property-block))
14593 (props (list (or (assoc property org-file-properties)
14594 (assoc property org-global-properties)
14595 (assoc property org-global-properties-fixed))))
14596 (ap (lambda (key)
14597 (when (re-search-forward
14598 (org-re-property key) (cdr range) t)
14599 (setq props
14600 (org-update-property-plist
14602 (if (match-end 1)
14603 (org-match-string-no-properties 1) "")
14604 props)))))
14605 val)
14606 (when (and range (goto-char (car range)))
14607 (funcall ap property)
14608 (goto-char (car range))
14609 (while (funcall ap (concat property "+")))
14610 (setq val (cdr (assoc property props)))
14611 (when val (if literal-nil val (org-not-nil val)))))))))
14613 (defun org-property-or-variable-value (var &optional inherit)
14614 "Check if there is a property fixing the value of VAR.
14615 If yes, return this value. If not, return the current value of the variable."
14616 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14617 (if (and prop (stringp prop) (string-match "\\S-" prop))
14618 (read prop)
14619 (symbol-value var))))
14621 (defun org-entry-delete (pom property)
14622 "Delete the property PROPERTY from entry at point-or-marker POM."
14623 (org-with-point-at pom
14624 (if (member property org-special-properties)
14625 nil ; cannot delete these properties.
14626 (let ((range (org-get-property-block)))
14627 (if (and range
14628 (goto-char (car range))
14629 (re-search-forward
14630 (org-re-property property)
14631 (cdr range) t))
14632 (progn
14633 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14635 nil)))))
14637 ;; Multi-values properties are properties that contain multiple values
14638 ;; These values are assumed to be single words, separated by whitespace.
14639 (defun org-entry-add-to-multivalued-property (pom property value)
14640 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14641 (let* ((old (org-entry-get pom property))
14642 (values (and old (org-split-string old "[ \t]"))))
14643 (setq value (org-entry-protect-space value))
14644 (unless (member value values)
14645 (setq values (cons value values))
14646 (org-entry-put pom property
14647 (mapconcat 'identity values " ")))))
14649 (defun org-entry-remove-from-multivalued-property (pom property value)
14650 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14651 (let* ((old (org-entry-get pom property))
14652 (values (and old (org-split-string old "[ \t]"))))
14653 (setq value (org-entry-protect-space value))
14654 (when (member value values)
14655 (setq values (delete value values))
14656 (org-entry-put pom property
14657 (mapconcat 'identity values " ")))))
14659 (defun org-entry-member-in-multivalued-property (pom property value)
14660 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14661 (let* ((old (org-entry-get pom property))
14662 (values (and old (org-split-string old "[ \t]"))))
14663 (setq value (org-entry-protect-space value))
14664 (member value values)))
14666 (defun org-entry-get-multivalued-property (pom property)
14667 "Return a list of values in a multivalued property."
14668 (let* ((value (org-entry-get pom property))
14669 (values (and value (org-split-string value "[ \t]"))))
14670 (mapcar 'org-entry-restore-space values)))
14672 (defun org-entry-put-multivalued-property (pom property &rest values)
14673 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14674 VALUES should be a list of strings. Spaces will be protected."
14675 (org-entry-put pom property
14676 (mapconcat 'org-entry-protect-space values " "))
14677 (let* ((value (org-entry-get pom property))
14678 (values (and value (org-split-string value "[ \t]"))))
14679 (mapcar 'org-entry-restore-space values)))
14681 (defun org-entry-protect-space (s)
14682 "Protect spaces and newline in string S."
14683 (while (string-match " " s)
14684 (setq s (replace-match "%20" t t s)))
14685 (while (string-match "\n" s)
14686 (setq s (replace-match "%0A" t t s)))
14689 (defun org-entry-restore-space (s)
14690 "Restore spaces and newline in string S."
14691 (while (string-match "%20" s)
14692 (setq s (replace-match " " t t s)))
14693 (while (string-match "%0A" s)
14694 (setq s (replace-match "\n" t t s)))
14697 (defvar org-entry-property-inherited-from (make-marker)
14698 "Marker pointing to the entry from where a property was inherited.
14699 Each call to `org-entry-get-with-inheritance' will set this marker to the
14700 location of the entry where the inheritance search matched. If there was
14701 no match, the marker will point nowhere.
14702 Note that also `org-entry-get' calls this function, if the INHERIT flag
14703 is set.")
14705 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14706 "Get PROPERTY of entry or content at point, search higher levels if needed.
14707 The search will stop at the first ancestor which has the property defined.
14708 If the value found is \"nil\", return nil to show that the property
14709 should be considered as undefined (this is the meaning of nil here).
14710 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14711 (move-marker org-entry-property-inherited-from nil)
14712 (let (tmp)
14713 (save-excursion
14714 (save-restriction
14715 (widen)
14716 (catch 'ex
14717 (while t
14718 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14719 (or (ignore-errors (org-back-to-heading t))
14720 (goto-char (point-min)))
14721 (move-marker org-entry-property-inherited-from (point))
14722 (throw 'ex tmp))
14723 (or (ignore-errors (org-up-heading-safe))
14724 (throw 'ex nil))))))
14725 (setq tmp (or tmp
14726 (cdr (assoc property org-file-properties))
14727 (cdr (assoc property org-global-properties))
14728 (cdr (assoc property org-global-properties-fixed))))
14729 (if literal-nil tmp (org-not-nil tmp))))
14731 (defvar org-property-changed-functions nil
14732 "Hook called when the value of a property has changed.
14733 Each hook function should accept two arguments, the name of the property
14734 and the new value.")
14736 (defun org-entry-put (pom property value)
14737 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14738 (org-with-point-at pom
14739 (org-back-to-heading t)
14740 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14741 range)
14742 (cond
14743 ((equal property "TODO")
14744 (when (and (stringp value) (string-match "\\S-" value)
14745 (not (member value org-todo-keywords-1)))
14746 (error "\"%s\" is not a valid TODO state" value))
14747 (if (or (not value)
14748 (not (string-match "\\S-" value)))
14749 (setq value 'none))
14750 (org-todo value)
14751 (org-set-tags nil 'align))
14752 ((equal property "PRIORITY")
14753 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14754 (string-to-char value) ?\ ))
14755 (org-set-tags nil 'align))
14756 ((equal property "SCHEDULED")
14757 (if (re-search-forward org-scheduled-time-regexp end t)
14758 (cond
14759 ((eq value 'earlier) (org-timestamp-change -1 'day))
14760 ((eq value 'later) (org-timestamp-change 1 'day))
14761 (t (call-interactively 'org-schedule)))
14762 (call-interactively 'org-schedule)))
14763 ((equal property "DEADLINE")
14764 (if (re-search-forward org-deadline-time-regexp end t)
14765 (cond
14766 ((eq value 'earlier) (org-timestamp-change -1 'day))
14767 ((eq value 'later) (org-timestamp-change 1 'day))
14768 (t (call-interactively 'org-deadline)))
14769 (call-interactively 'org-deadline)))
14770 ((member property org-special-properties)
14771 (error "The %s property can not yet be set with `org-entry-put'"
14772 property))
14773 (t ; a non-special property
14774 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14775 (setq range (org-get-property-block beg end 'force))
14776 (goto-char (car range))
14777 (if (re-search-forward
14778 (org-re-property-keyword property) (cdr range) t)
14779 (progn
14780 (delete-region (match-beginning 0) (match-end 0))
14781 (goto-char (match-beginning 0)))
14782 (goto-char (cdr range))
14783 (insert "\n")
14784 (backward-char 1)
14785 (org-indent-line))
14786 (insert ":" property ":")
14787 (and value (insert " " value))
14788 (org-indent-line)))))
14789 (run-hook-with-args 'org-property-changed-functions property value)))
14791 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14792 "Get all property keys in the current buffer.
14793 With INCLUDE-SPECIALS, also list the special properties that reflect things
14794 like tags and TODO state.
14795 With INCLUDE-DEFAULTS, also include properties that has special meaning
14796 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14797 and others.
14798 With INCLUDE-COLUMNS, also include property names given in COLUMN
14799 formats in the current buffer."
14800 (let (rtn range cfmt s p)
14801 (save-excursion
14802 (save-restriction
14803 (widen)
14804 (goto-char (point-min))
14805 (while (re-search-forward org-property-start-re nil t)
14806 (setq range (org-get-property-block))
14807 (goto-char (car range))
14808 (while (re-search-forward
14809 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14810 (cdr range) t)
14811 (add-to-list 'rtn (org-match-string-no-properties 1)))
14812 (outline-next-heading))))
14814 (when include-specials
14815 (setq rtn (append org-special-properties rtn)))
14817 (when include-defaults
14818 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14819 (add-to-list 'rtn org-effort-property))
14821 (when include-columns
14822 (save-excursion
14823 (save-restriction
14824 (widen)
14825 (goto-char (point-min))
14826 (while (re-search-forward
14827 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14828 nil t)
14829 (setq cfmt (match-string 2) s 0)
14830 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14831 cfmt s)
14832 (setq s (match-end 0)
14833 p (match-string 1 cfmt))
14834 (unless (or (equal p "ITEM")
14835 (member p org-special-properties))
14836 (add-to-list 'rtn (match-string 1 cfmt))))))))
14838 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14840 (defun org-property-values (key)
14841 "Return a list of all values of property KEY in the current buffer."
14842 (save-excursion
14843 (save-restriction
14844 (widen)
14845 (goto-char (point-min))
14846 (let ((re (org-re-property key))
14847 values)
14848 (while (re-search-forward re nil t)
14849 (add-to-list 'values (org-trim (match-string 1))))
14850 (delete "" values)))))
14852 (defun org-insert-property-drawer ()
14853 "Insert a property drawer into the current entry."
14854 (org-back-to-heading t)
14855 (looking-at org-outline-regexp)
14856 (let ((indent (if org-adapt-indentation
14857 (- (match-end 0) (match-beginning 0))
14859 (beg (point))
14860 (re (concat "^[ \t]*" org-keyword-time-regexp))
14861 end hiddenp)
14862 (outline-next-heading)
14863 (setq end (point))
14864 (goto-char beg)
14865 (while (re-search-forward re end t))
14866 (setq hiddenp (outline-invisible-p))
14867 (end-of-line 1)
14868 (and (equal (char-after) ?\n) (forward-char 1))
14869 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14870 (if (member (match-string 1) '("CLOCK:" ":END:"))
14871 ;; just skip this line
14872 (beginning-of-line 2)
14873 ;; Drawer start, find the end
14874 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14875 (beginning-of-line 1)))
14876 (org-skip-over-state-notes)
14877 (skip-chars-backward " \t\n\r")
14878 (if (eq (char-before) ?*) (forward-char 1))
14879 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14880 (beginning-of-line 0)
14881 (org-indent-to-column indent)
14882 (beginning-of-line 2)
14883 (org-indent-to-column indent)
14884 (beginning-of-line 0)
14885 (if hiddenp
14886 (save-excursion
14887 (org-back-to-heading t)
14888 (hide-entry))
14889 (org-flag-drawer t))))
14891 (defun org-insert-drawer (&optional arg drawer)
14892 "Insert a drawer at point.
14894 Optional argument DRAWER, when non-nil, is a string representing
14895 drawer's name. Otherwise, the user is prompted for a name.
14897 If a region is active, insert the drawer around that region
14898 instead.
14900 Point is left between drawer's boundaries."
14901 (interactive "P")
14902 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14903 "LOGBOOK"))
14904 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14905 ;; internally by Org. They are meant to be inserted
14906 ;; automatically.
14907 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14908 ;; Remove system drawers from list. Note: For some reason,
14909 ;; `org-completing-read' ignores the predicate while
14910 ;; `completing-read' handles it fine.
14911 (drawer (if arg "PROPERTIES"
14912 (or drawer
14913 (completing-read
14914 "Drawer: " org-drawers
14915 (lambda (d) (not (member d system-drawers))))))))
14916 (cond
14917 ;; With C-u, fall back on `org-insert-property-drawer'
14918 (arg (org-insert-property-drawer))
14919 ;; With an active region, insert a drawer at point.
14920 ((not (org-region-active-p))
14921 (progn
14922 (unless (bolp) (insert "\n"))
14923 (insert (format ":%s:\n\n:END:\n" drawer))
14924 (forward-line -2)))
14925 ;; Otherwise, insert the drawer at point
14927 (let ((rbeg (region-beginning))
14928 (rend (copy-marker (region-end))))
14929 (unwind-protect
14930 (progn
14931 (goto-char rbeg)
14932 (beginning-of-line)
14933 (when (save-excursion
14934 (re-search-forward org-outline-regexp-bol rend t))
14935 (error "Drawers cannot contain headlines"))
14936 ;; Position point at the beginning of the first
14937 ;; non-blank line in region. Insert drawer's opening
14938 ;; there, then indent it.
14939 (org-skip-whitespace)
14940 (beginning-of-line)
14941 (insert ":" drawer ":\n")
14942 (forward-line -1)
14943 (indent-for-tab-command)
14944 ;; Move point to the beginning of the first blank line
14945 ;; after the last non-blank line in region. Insert
14946 ;; drawer's closing, then indent it.
14947 (goto-char rend)
14948 (skip-chars-backward " \r\t\n")
14949 (insert "\n:END:")
14950 (deactivate-mark t)
14951 (indent-for-tab-command)
14952 (unless (eolp) (insert "\n")))
14953 ;; Clear marker, whatever the outcome of insertion is.
14954 (set-marker rend nil)))))))
14956 (defvar org-property-set-functions-alist nil
14957 "Property set function alist.
14958 Each entry should have the following format:
14960 (PROPERTY . READ-FUNCTION)
14962 The read function will be called with the same argument as
14963 `org-completing-read'.")
14965 (defun org-set-property-function (property)
14966 "Get the function that should be used to set PROPERTY.
14967 This is computed according to `org-property-set-functions-alist'."
14968 (or (cdr (assoc property org-property-set-functions-alist))
14969 'org-completing-read))
14971 (defun org-read-property-value (property)
14972 "Read PROPERTY value from user."
14973 (let* ((completion-ignore-case t)
14974 (allowed (org-property-get-allowed-values nil property 'table))
14975 (cur (org-entry-get nil property))
14976 (prompt (concat property " value"
14977 (if (and cur (string-match "\\S-" cur))
14978 (concat " [" cur "]") "") ": "))
14979 (set-function (org-set-property-function property))
14980 (val (if allowed
14981 (funcall set-function prompt allowed nil
14982 (not (get-text-property 0 'org-unrestricted
14983 (caar allowed))))
14984 (let (org-completion-use-ido org-completion-use-iswitchb)
14985 (funcall set-function prompt
14986 (mapcar 'list (org-property-values property))
14987 nil nil "" nil cur)))))
14988 (if (equal val "")
14990 val)))
14992 (defvar org-last-set-property nil)
14993 (defun org-read-property-name ()
14994 "Read a property name."
14995 (let* ((completion-ignore-case t)
14996 (keys (org-buffer-property-keys nil t t))
14997 (default-prop (or (save-excursion
14998 (save-match-data
14999 (beginning-of-line)
15000 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15001 (null (string= (match-string 1) "END"))
15002 (match-string 1))))
15003 org-last-set-property))
15004 (property (org-icompleting-read
15005 (concat "Property"
15006 (if default-prop (concat " [" default-prop "]") "")
15007 ": ")
15008 (mapcar 'list keys)
15009 nil nil nil nil
15010 default-prop
15012 (if (member property keys)
15013 property
15014 (or (cdr (assoc (downcase property)
15015 (mapcar (lambda (x) (cons (downcase x) x))
15016 keys)))
15017 property))))
15019 (defun org-set-property (property value)
15020 "In the current entry, set PROPERTY to VALUE.
15021 When called interactively, this will prompt for a property name, offering
15022 completion on existing and default properties. And then it will prompt
15023 for a value, offering completion either on allowed values (via an inherited
15024 xxx_ALL property) or on existing values in other instances of this property
15025 in the current file."
15026 (interactive (list nil nil))
15027 (let* ((property (or property (org-read-property-name)))
15028 (value (or value (org-read-property-value property)))
15029 (fn (cdr (assoc property org-properties-postprocess-alist))))
15030 (setq org-last-set-property property)
15031 ;; Possibly postprocess the inserted value:
15032 (when fn (setq value (funcall fn value)))
15033 (unless (equal (org-entry-get nil property) value)
15034 (org-entry-put nil property value))))
15036 (defun org-delete-property (property)
15037 "In the current entry, delete PROPERTY."
15038 (interactive
15039 (let* ((completion-ignore-case t)
15040 (prop (org-icompleting-read "Property: "
15041 (org-entry-properties nil 'standard))))
15042 (list prop)))
15043 (message "Property %s %s" property
15044 (if (org-entry-delete nil property)
15045 "deleted"
15046 "was not present in the entry")))
15048 (defun org-delete-property-globally (property)
15049 "Remove PROPERTY globally, from all entries."
15050 (interactive
15051 (let* ((completion-ignore-case t)
15052 (prop (org-icompleting-read
15053 "Globally remove property: "
15054 (mapcar 'list (org-buffer-property-keys)))))
15055 (list prop)))
15056 (save-excursion
15057 (save-restriction
15058 (widen)
15059 (goto-char (point-min))
15060 (let ((cnt 0))
15061 (while (re-search-forward
15062 (org-re-property property)
15063 nil t)
15064 (setq cnt (1+ cnt))
15065 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15066 (message "Property \"%s\" removed from %d entries" property cnt)))))
15068 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15070 (defun org-compute-property-at-point ()
15071 "Compute the property at point.
15072 This looks for an enclosing column format, extracts the operator and
15073 then applies it to the property in the column format's scope."
15074 (interactive)
15075 (unless (org-at-property-p)
15076 (error "Not at a property"))
15077 (let ((prop (org-match-string-no-properties 2)))
15078 (org-columns-get-format-and-top-level)
15079 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15080 (error "No operator defined for property %s" prop))
15081 (org-columns-compute prop)))
15083 (defvar org-property-allowed-value-functions nil
15084 "Hook for functions supplying allowed values for a specific property.
15085 The functions must take a single argument, the name of the property, and
15086 return a flat list of allowed values. If \":ETC\" is one of
15087 the values, this means that these values are intended as defaults for
15088 completion, but that other values should be allowed too.
15089 The functions must return nil if they are not responsible for this
15090 property.")
15092 (defun org-property-get-allowed-values (pom property &optional table)
15093 "Get allowed values for the property PROPERTY.
15094 When TABLE is non-nil, return an alist that can directly be used for
15095 completion."
15096 (let (vals)
15097 (cond
15098 ((equal property "TODO")
15099 (setq vals (org-with-point-at pom
15100 (append org-todo-keywords-1 '("")))))
15101 ((equal property "PRIORITY")
15102 (let ((n org-lowest-priority))
15103 (while (>= n org-highest-priority)
15104 (push (char-to-string n) vals)
15105 (setq n (1- n)))))
15106 ((member property org-special-properties))
15107 ((setq vals (run-hook-with-args-until-success
15108 'org-property-allowed-value-functions property)))
15110 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15111 (when (and vals (string-match "\\S-" vals))
15112 (setq vals (car (read-from-string (concat "(" vals ")"))))
15113 (setq vals (mapcar (lambda (x)
15114 (cond ((stringp x) x)
15115 ((numberp x) (number-to-string x))
15116 ((symbolp x) (symbol-name x))
15117 (t "???")))
15118 vals)))))
15119 (when (member ":ETC" vals)
15120 (setq vals (remove ":ETC" vals))
15121 (org-add-props (car vals) '(org-unrestricted t)))
15122 (if table (mapcar 'list vals) vals)))
15124 (defun org-property-previous-allowed-value (&optional previous)
15125 "Switch to the next allowed value for this property."
15126 (interactive)
15127 (org-property-next-allowed-value t))
15129 (defun org-property-next-allowed-value (&optional previous)
15130 "Switch to the next allowed value for this property."
15131 (interactive)
15132 (unless (org-at-property-p)
15133 (error "Not at a property"))
15134 (let* ((key (match-string 2))
15135 (value (match-string 3))
15136 (allowed (or (org-property-get-allowed-values (point) key)
15137 (and (member value '("[ ]" "[-]" "[X]"))
15138 '("[ ]" "[X]"))))
15139 nval)
15140 (unless allowed
15141 (error "Allowed values for this property have not been defined"))
15142 (if previous (setq allowed (reverse allowed)))
15143 (if (member value allowed)
15144 (setq nval (car (cdr (member value allowed)))))
15145 (setq nval (or nval (car allowed)))
15146 (if (equal nval value)
15147 (error "Only one allowed value for this property"))
15148 (org-at-property-p)
15149 (replace-match (concat " :" key ": " nval) t t)
15150 (org-indent-line)
15151 (beginning-of-line 1)
15152 (skip-chars-forward " \t")
15153 (run-hook-with-args 'org-property-changed-functions key nval)))
15155 (defun org-find-olp (path &optional this-buffer)
15156 "Return a marker pointing to the entry at outline path OLP.
15157 If anything goes wrong, throw an error.
15158 You can wrap this call to catch the error like this:
15160 (condition-case msg
15161 (org-mobile-locate-entry (match-string 4))
15162 (error (nth 1 msg)))
15164 The return value will then be either a string with the error message,
15165 or a marker if everything is OK.
15167 If THIS-BUFFER is set, the outline path does not contain a file,
15168 only headings."
15169 (let* ((file (if this-buffer buffer-file-name (pop path)))
15170 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15171 (level 1)
15172 (lmin 1)
15173 (lmax 1)
15174 limit re end found pos heading cnt flevel)
15175 (unless buffer (error "File not found :%s" file))
15176 (with-current-buffer buffer
15177 (save-excursion
15178 (save-restriction
15179 (widen)
15180 (setq limit (point-max))
15181 (goto-char (point-min))
15182 (while (setq heading (pop path))
15183 (setq re (format org-complex-heading-regexp-format
15184 (regexp-quote heading)))
15185 (setq cnt 0 pos (point))
15186 (while (re-search-forward re end t)
15187 (setq level (- (match-end 1) (match-beginning 1)))
15188 (if (and (>= level lmin) (<= level lmax))
15189 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15190 (when (= cnt 0) (error "Heading not found on level %d: %s"
15191 lmax heading))
15192 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15193 lmax heading))
15194 (goto-char found)
15195 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15196 (setq end (save-excursion (org-end-of-subtree t t))))
15197 (when (org-at-heading-p)
15198 (move-marker (make-marker) (point))))))))
15200 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15201 "Find node HEADING in BUFFER.
15202 Return a marker to the heading if it was found, or nil if not.
15203 If POS-ONLY is set, return just the position instead of a marker.
15205 The heading text must match exact, but it may have a TODO keyword,
15206 a priority cookie and tags in the standard locations."
15207 (with-current-buffer (or buffer (current-buffer))
15208 (save-excursion
15209 (save-restriction
15210 (widen)
15211 (goto-char (point-min))
15212 (let (case-fold-search)
15213 (if (re-search-forward
15214 (format org-complex-heading-regexp-format
15215 (regexp-quote heading)) nil t)
15216 (if pos-only
15217 (match-beginning 0)
15218 (move-marker (make-marker) (match-beginning 0)))))))))
15220 (defun org-find-exact-heading-in-directory (heading &optional dir)
15221 "Find Org node headline HEADING in all .org files in directory DIR.
15222 When the target headline is found, return a marker to this location."
15223 (let ((files (directory-files (or dir default-directory)
15224 nil "\\`[^.#].*\\.org\\'"))
15225 file visiting m buffer)
15226 (catch 'found
15227 (while (setq file (pop files))
15228 (message "trying %s" file)
15229 (setq visiting (org-find-base-buffer-visiting file))
15230 (setq buffer (or visiting (find-file-noselect file)))
15231 (setq m (org-find-exact-headline-in-buffer
15232 heading buffer))
15233 (when (and (not m) (not visiting)) (kill-buffer buffer))
15234 (and m (throw 'found m))))))
15236 (defun org-find-entry-with-id (ident)
15237 "Locate the entry that contains the ID property with exact value IDENT.
15238 IDENT can be a string, a symbol or a number, this function will search for
15239 the string representation of it.
15240 Return the position where this entry starts, or nil if there is no such entry."
15241 (interactive "sID: ")
15242 (let ((id (cond
15243 ((stringp ident) ident)
15244 ((symbol-name ident) (symbol-name ident))
15245 ((numberp ident) (number-to-string ident))
15246 (t (error "IDENT %s must be a string, symbol or number" ident))))
15247 (case-fold-search nil))
15248 (save-excursion
15249 (save-restriction
15250 (widen)
15251 (goto-char (point-min))
15252 (when (re-search-forward
15253 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15254 nil t)
15255 (org-back-to-heading t)
15256 (point))))))
15258 ;;;; Timestamps
15260 (defvar org-last-changed-timestamp nil)
15261 (defvar org-last-inserted-timestamp nil
15262 "The last time stamp inserted with `org-insert-time-stamp'.")
15263 (defvar org-time-was-given) ; dynamically scoped parameter
15264 (defvar org-end-time-was-given) ; dynamically scoped parameter
15265 (defvar org-ts-what) ; dynamically scoped parameter
15267 (defun org-time-stamp (arg &optional inactive)
15268 "Prompt for a date/time and insert a time stamp.
15269 If the user specifies a time like HH:MM or if this command is
15270 called with at least one prefix argument, the time stamp contains
15271 the date and the time. Otherwise, only the date is be included.
15273 All parts of a date not specified by the user is filled in from
15274 the current date/time. So if you just press return without
15275 typing anything, the time stamp will represent the current
15276 date/time.
15278 If there is already a timestamp at the cursor, it will be
15279 modified.
15281 With two universal prefix arguments, insert an active timestamp
15282 with the current time without prompting the user."
15283 (interactive "P")
15284 (let* ((ts nil)
15285 (default-time
15286 ;; Default time is either today, or, when entering a range,
15287 ;; the range start.
15288 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15289 (save-excursion
15290 (re-search-backward
15291 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15292 (- (point) 20) t)))
15293 (apply 'encode-time (org-parse-time-string (match-string 1)))
15294 (current-time)))
15295 (default-input (and ts (org-get-compact-tod ts)))
15296 (repeater (save-excursion
15297 (save-match-data
15298 (beginning-of-line)
15299 (when (re-search-forward
15300 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15301 (save-excursion (progn (end-of-line) (point))) t)
15302 (match-string 0)))))
15303 org-time-was-given org-end-time-was-given time)
15304 (cond
15305 ((and (org-at-timestamp-p t)
15306 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15307 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15308 (insert "--")
15309 (setq time (let ((this-command this-command))
15310 (org-read-date arg 'totime nil nil
15311 default-time default-input inactive)))
15312 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15313 ((org-at-timestamp-p t)
15314 (setq time (let ((this-command this-command))
15315 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15316 (when (org-at-timestamp-p t) ; just to get the match data
15317 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15318 (replace-match "")
15319 (setq org-last-changed-timestamp
15320 (org-insert-time-stamp
15321 time (or org-time-was-given arg)
15322 inactive nil nil (list org-end-time-was-given)))
15323 (when repeater (goto-char (1- (point))) (insert " " repeater)
15324 (setq org-last-changed-timestamp
15325 (concat (substring org-last-inserted-timestamp 0 -1)
15326 " " repeater ">"))))
15327 (message "Timestamp updated"))
15328 ((equal arg '(16))
15329 (org-insert-time-stamp (current-time) t))
15331 (setq time (let ((this-command this-command))
15332 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15333 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15334 nil nil (list org-end-time-was-given))))))
15336 ;; FIXME: can we use this for something else, like computing time differences?
15337 (defun org-get-compact-tod (s)
15338 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15339 (let* ((t1 (match-string 1 s))
15340 (h1 (string-to-number (match-string 2 s)))
15341 (m1 (string-to-number (match-string 3 s)))
15342 (t2 (and (match-end 4) (match-string 5 s)))
15343 (h2 (and t2 (string-to-number (match-string 6 s))))
15344 (m2 (and t2 (string-to-number (match-string 7 s))))
15345 dh dm)
15346 (if (not t2)
15348 (setq dh (- h2 h1) dm (- m2 m1))
15349 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15350 (concat t1 "+" (number-to-string dh)
15351 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15353 (defun org-time-stamp-inactive (&optional arg)
15354 "Insert an inactive time stamp.
15355 An inactive time stamp is enclosed in square brackets instead of angle
15356 brackets. It is inactive in the sense that it does not trigger agenda entries,
15357 does not link to the calendar and cannot be changed with the S-cursor keys.
15358 So these are more for recording a certain time/date."
15359 (interactive "P")
15360 (org-time-stamp arg 'inactive))
15362 (defvar org-date-ovl (make-overlay 1 1))
15363 (overlay-put org-date-ovl 'face 'org-date-selected)
15364 (org-detach-overlay org-date-ovl)
15366 (defvar org-ans1) ; dynamically scoped parameter
15367 (defvar org-ans2) ; dynamically scoped parameter
15369 (defvar org-plain-time-of-day-regexp) ; defined below
15371 (defvar org-overriding-default-time nil) ; dynamically scoped
15372 (defvar org-read-date-overlay nil)
15373 (defvar org-dcst nil) ; dynamically scoped
15374 (defvar org-read-date-history nil)
15375 (defvar org-read-date-final-answer nil)
15376 (defvar org-read-date-analyze-futurep nil)
15377 (defvar org-read-date-analyze-forced-year nil)
15378 (defvar org-read-date-inactive)
15380 (defun org-read-date (&optional org-with-time to-time from-string prompt
15381 default-time default-input inactive)
15382 "Read a date, possibly a time, and make things smooth for the user.
15383 The prompt will suggest to enter an ISO date, but you can also enter anything
15384 which will at least partially be understood by `parse-time-string'.
15385 Unrecognized parts of the date will default to the current day, month, year,
15386 hour and minute. If this command is called to replace a timestamp at point,
15387 or to enter the second timestamp of a range, the default time is taken
15388 from the existing stamp. Furthermore, the command prefers the future,
15389 so if you are giving a date where the year is not given, and the day-month
15390 combination is already past in the current year, it will assume you
15391 mean next year. For details, see the manual. A few examples:
15393 3-2-5 --> 2003-02-05
15394 feb 15 --> currentyear-02-15
15395 2/15 --> currentyear-02-15
15396 sep 12 9 --> 2009-09-12
15397 12:45 --> today 12:45
15398 22 sept 0:34 --> currentyear-09-22 0:34
15399 12 --> currentyear-currentmonth-12
15400 Fri --> nearest Friday (today or later)
15401 etc.
15403 Furthermore you can specify a relative date by giving, as the *first* thing
15404 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15405 change in days weeks, months, years.
15406 With a single plus or minus, the date is relative to today. With a double
15407 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15408 +4d --> four days from today
15409 +4 --> same as above
15410 +2w --> two weeks from today
15411 ++5 --> five days from default date
15413 The function understands only English month and weekday abbreviations.
15415 While prompting, a calendar is popped up - you can also select the
15416 date with the mouse (button 1). The calendar shows a period of three
15417 months. To scroll it to other months, use the keys `>' and `<'.
15418 If you don't like the calendar, turn it off with
15419 \(setq org-read-date-popup-calendar nil)
15421 With optional argument TO-TIME, the date will immediately be converted
15422 to an internal time.
15423 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15424 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15425 still enter a time, and this function will inform the calling routine
15426 about this change. The calling routine may then choose to change the
15427 format used to insert the time stamp into the buffer to include the time.
15428 With optional argument FROM-STRING, read from this string instead from
15429 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15430 the time/date that is used for everything that is not specified by the
15431 user."
15432 (require 'parse-time)
15433 (let* ((org-time-stamp-rounding-minutes
15434 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15435 (org-dcst org-display-custom-times)
15436 (ct (org-current-time))
15437 (org-def (or org-overriding-default-time default-time ct))
15438 (org-defdecode (decode-time org-def))
15439 (dummy (progn
15440 (when (< (nth 2 org-defdecode) org-extend-today-until)
15441 (setcar (nthcdr 2 org-defdecode) -1)
15442 (setcar (nthcdr 1 org-defdecode) 59)
15443 (setq org-def (apply 'encode-time org-defdecode)
15444 org-defdecode (decode-time org-def)))))
15445 (calendar-frame-setup nil)
15446 (calendar-setup nil)
15447 (calendar-move-hook nil)
15448 (calendar-view-diary-initially-flag nil)
15449 (calendar-view-holidays-initially-flag nil)
15450 (timestr (format-time-string
15451 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15452 (prompt (concat (if prompt (concat prompt " ") "")
15453 (format "Date+time [%s]: " timestr)))
15454 ans (org-ans0 "") org-ans1 org-ans2 final)
15456 (cond
15457 (from-string (setq ans from-string))
15458 (org-read-date-popup-calendar
15459 (save-excursion
15460 (save-window-excursion
15461 (calendar)
15462 (org-eval-in-calendar '(setq cursor-type nil) t)
15463 (unwind-protect
15464 (progn
15465 (calendar-forward-day (- (time-to-days org-def)
15466 (calendar-absolute-from-gregorian
15467 (calendar-current-date))))
15468 (org-eval-in-calendar nil t)
15469 (let* ((old-map (current-local-map))
15470 (map (copy-keymap calendar-mode-map))
15471 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15472 (org-defkey map (kbd "RET") 'org-calendar-select)
15473 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15474 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15475 (org-defkey minibuffer-local-map [(meta shift left)]
15476 (lambda () (interactive)
15477 (org-eval-in-calendar '(calendar-backward-month 1))))
15478 (org-defkey minibuffer-local-map [(meta shift right)]
15479 (lambda () (interactive)
15480 (org-eval-in-calendar '(calendar-forward-month 1))))
15481 (org-defkey minibuffer-local-map [(meta shift up)]
15482 (lambda () (interactive)
15483 (org-eval-in-calendar '(calendar-backward-year 1))))
15484 (org-defkey minibuffer-local-map [(meta shift down)]
15485 (lambda () (interactive)
15486 (org-eval-in-calendar '(calendar-forward-year 1))))
15487 (org-defkey minibuffer-local-map [?\e (shift left)]
15488 (lambda () (interactive)
15489 (org-eval-in-calendar '(calendar-backward-month 1))))
15490 (org-defkey minibuffer-local-map [?\e (shift right)]
15491 (lambda () (interactive)
15492 (org-eval-in-calendar '(calendar-forward-month 1))))
15493 (org-defkey minibuffer-local-map [?\e (shift up)]
15494 (lambda () (interactive)
15495 (org-eval-in-calendar '(calendar-backward-year 1))))
15496 (org-defkey minibuffer-local-map [?\e (shift down)]
15497 (lambda () (interactive)
15498 (org-eval-in-calendar '(calendar-forward-year 1))))
15499 (org-defkey minibuffer-local-map [(shift up)]
15500 (lambda () (interactive)
15501 (org-eval-in-calendar '(calendar-backward-week 1))))
15502 (org-defkey minibuffer-local-map [(shift down)]
15503 (lambda () (interactive)
15504 (org-eval-in-calendar '(calendar-forward-week 1))))
15505 (org-defkey minibuffer-local-map [(shift left)]
15506 (lambda () (interactive)
15507 (org-eval-in-calendar '(calendar-backward-day 1))))
15508 (org-defkey minibuffer-local-map [(shift right)]
15509 (lambda () (interactive)
15510 (org-eval-in-calendar '(calendar-forward-day 1))))
15511 (org-defkey minibuffer-local-map ">"
15512 (lambda () (interactive)
15513 (org-eval-in-calendar '(scroll-calendar-left 1))))
15514 (org-defkey minibuffer-local-map "<"
15515 (lambda () (interactive)
15516 (org-eval-in-calendar '(scroll-calendar-right 1))))
15517 (org-defkey minibuffer-local-map "\C-v"
15518 (lambda () (interactive)
15519 (org-eval-in-calendar
15520 '(calendar-scroll-left-three-months 1))))
15521 (org-defkey minibuffer-local-map "\M-v"
15522 (lambda () (interactive)
15523 (org-eval-in-calendar
15524 '(calendar-scroll-right-three-months 1))))
15525 (run-hooks 'org-read-date-minibuffer-setup-hook)
15526 (unwind-protect
15527 (progn
15528 (use-local-map map)
15529 (setq org-read-date-inactive inactive)
15530 (add-hook 'post-command-hook 'org-read-date-display)
15531 (setq org-ans0 (read-string prompt default-input
15532 'org-read-date-history nil))
15533 ;; org-ans0: from prompt
15534 ;; org-ans1: from mouse click
15535 ;; org-ans2: from calendar motion
15536 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15537 (remove-hook 'post-command-hook 'org-read-date-display)
15538 (use-local-map old-map)
15539 (when org-read-date-overlay
15540 (delete-overlay org-read-date-overlay)
15541 (setq org-read-date-overlay nil)))))
15542 (bury-buffer "*Calendar*")))))
15544 (t ; Naked prompt only
15545 (unwind-protect
15546 (setq ans (read-string prompt default-input
15547 'org-read-date-history timestr))
15548 (when org-read-date-overlay
15549 (delete-overlay org-read-date-overlay)
15550 (setq org-read-date-overlay nil)))))
15552 (setq final (org-read-date-analyze ans org-def org-defdecode))
15554 (when org-read-date-analyze-forced-year
15555 (message "Year was forced into %s"
15556 (if org-read-date-force-compatible-dates
15557 "compatible range (1970-2037)"
15558 "range representable on this machine"))
15559 (ding))
15561 ;; One round trip to get rid of 34th of August and stuff like that....
15562 (setq final (decode-time (apply 'encode-time final)))
15564 (setq org-read-date-final-answer ans)
15566 (if to-time
15567 (apply 'encode-time final)
15568 (if (and (boundp 'org-time-was-given) org-time-was-given)
15569 (format "%04d-%02d-%02d %02d:%02d"
15570 (nth 5 final) (nth 4 final) (nth 3 final)
15571 (nth 2 final) (nth 1 final))
15572 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15574 (defvar org-def)
15575 (defvar org-defdecode)
15576 (defvar org-with-time)
15577 (defun org-read-date-display ()
15578 "Display the current date prompt interpretation in the minibuffer."
15579 (when org-read-date-display-live
15580 (when org-read-date-overlay
15581 (delete-overlay org-read-date-overlay))
15582 (when (minibufferp (current-buffer))
15583 (save-excursion
15584 (end-of-line 1)
15585 (while (not (equal (buffer-substring
15586 (max (point-min) (- (point) 4)) (point))
15587 " "))
15588 (insert " ")))
15589 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15590 " " (or org-ans1 org-ans2)))
15591 (org-end-time-was-given nil)
15592 (f (org-read-date-analyze ans org-def org-defdecode))
15593 (fmts (if org-dcst
15594 org-time-stamp-custom-formats
15595 org-time-stamp-formats))
15596 (fmt (if (or org-with-time
15597 (and (boundp 'org-time-was-given) org-time-was-given))
15598 (cdr fmts)
15599 (car fmts)))
15600 (txt (format-time-string fmt (apply 'encode-time f)))
15601 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15602 (txt (concat "=> " txt)))
15603 (when (and org-end-time-was-given
15604 (string-match org-plain-time-of-day-regexp txt))
15605 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15606 org-end-time-was-given
15607 (substring txt (match-end 0)))))
15608 (when org-read-date-analyze-futurep
15609 (setq txt (concat txt " (=>F)")))
15610 (setq org-read-date-overlay
15611 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15612 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15614 (defun org-read-date-analyze (ans org-def org-defdecode)
15615 "Analyze the combined answer of the date prompt."
15616 ;; FIXME: cleanup and comment
15617 (let ((nowdecode (decode-time (current-time)))
15618 delta deltan deltaw deltadef year month day
15619 hour minute second wday pm h2 m2 tl wday1
15620 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15621 (setq org-read-date-analyze-futurep nil
15622 org-read-date-analyze-forced-year nil)
15623 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15624 (setq ans "+0"))
15626 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15627 (setq ans (replace-match "" t t ans)
15628 deltan (car delta)
15629 deltaw (nth 1 delta)
15630 deltadef (nth 2 delta)))
15632 ;; Check if there is an iso week date in there. If yes, store the
15633 ;; info and postpone interpreting it until the rest of the parsing
15634 ;; is done.
15635 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15636 (setq iso-year (if (match-end 1)
15637 (org-small-year-to-year
15638 (string-to-number (match-string 1 ans))))
15639 iso-weekday (if (match-end 3)
15640 (string-to-number (match-string 3 ans)))
15641 iso-week (string-to-number (match-string 2 ans)))
15642 (setq ans (replace-match "" t t ans)))
15644 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15645 (when (string-match
15646 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15647 (setq year (if (match-end 2)
15648 (string-to-number (match-string 2 ans))
15649 (progn (setq kill-year t)
15650 (string-to-number (format-time-string "%Y"))))
15651 month (string-to-number (match-string 3 ans))
15652 day (string-to-number (match-string 4 ans)))
15653 (if (< year 100) (setq year (+ 2000 year)))
15654 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15655 t nil ans)))
15657 ;; Help matching dotted european dates
15658 (when (string-match
15659 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15660 (setq year (if (match-end 3)
15661 (string-to-number (match-string 3 ans))
15662 (progn (setq kill-year t)
15663 (string-to-number (format-time-string "%Y"))))
15664 day (string-to-number (match-string 1 ans))
15665 month (string-to-number (match-string 2 ans))
15666 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15667 t nil ans)))
15669 ;; Help matching american dates, like 5/30 or 5/30/7
15670 (when (string-match
15671 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15672 (setq year (if (match-end 4)
15673 (string-to-number (match-string 4 ans))
15674 (progn (setq kill-year t)
15675 (string-to-number (format-time-string "%Y"))))
15676 month (string-to-number (match-string 1 ans))
15677 day (string-to-number (match-string 2 ans)))
15678 (if (< year 100) (setq year (+ 2000 year)))
15679 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15680 t nil ans)))
15681 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15682 ;; If there is a time with am/pm, and *no* time without it, we convert
15683 ;; so that matching will be successful.
15684 (loop for i from 1 to 2 do ; twice, for end time as well
15685 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15686 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15687 (setq hour (string-to-number (match-string 1 ans))
15688 minute (if (match-end 3)
15689 (string-to-number (match-string 3 ans))
15691 pm (equal ?p
15692 (string-to-char (downcase (match-string 4 ans)))))
15693 (if (and (= hour 12) (not pm))
15694 (setq hour 0)
15695 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15696 (setq ans (replace-match (format "%02d:%02d" hour minute)
15697 t t ans))))
15699 ;; Check if a time range is given as a duration
15700 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15701 (setq hour (string-to-number (match-string 1 ans))
15702 h2 (+ hour (string-to-number (match-string 3 ans)))
15703 minute (string-to-number (match-string 2 ans))
15704 m2 (+ minute (if (match-end 5) (string-to-number
15705 (match-string 5 ans))0)))
15706 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15707 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15708 t t ans)))
15710 ;; Check if there is a time range
15711 (when (boundp 'org-end-time-was-given)
15712 (setq org-time-was-given nil)
15713 (when (and (string-match org-plain-time-of-day-regexp ans)
15714 (match-end 8))
15715 (setq org-end-time-was-given (match-string 8 ans))
15716 (setq ans (concat (substring ans 0 (match-beginning 7))
15717 (substring ans (match-end 7))))))
15719 (setq tl (parse-time-string ans)
15720 day (or (nth 3 tl) (nth 3 org-defdecode))
15721 month (or (nth 4 tl)
15722 (if (and org-read-date-prefer-future
15723 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15724 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15725 (nth 4 org-defdecode)))
15726 year (or (and (not kill-year) (nth 5 tl))
15727 (if (and org-read-date-prefer-future
15728 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15729 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15730 (nth 5 org-defdecode)))
15731 hour (or (nth 2 tl) (nth 2 org-defdecode))
15732 minute (or (nth 1 tl) (nth 1 org-defdecode))
15733 second (or (nth 0 tl) 0)
15734 wday (nth 6 tl))
15736 (when (and (eq org-read-date-prefer-future 'time)
15737 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15738 (equal day (nth 3 nowdecode))
15739 (equal month (nth 4 nowdecode))
15740 (equal year (nth 5 nowdecode))
15741 (nth 2 tl)
15742 (or (< (nth 2 tl) (nth 2 nowdecode))
15743 (and (= (nth 2 tl) (nth 2 nowdecode))
15744 (nth 1 tl)
15745 (< (nth 1 tl) (nth 1 nowdecode)))))
15746 (setq day (1+ day)
15747 futurep t))
15749 ;; Special date definitions below
15750 (cond
15751 (iso-week
15752 ;; There was an iso week
15753 (require 'cal-iso)
15754 (setq futurep nil)
15755 (setq year (or iso-year year)
15756 day (or iso-weekday wday 1)
15757 wday nil ; to make sure that the trigger below does not match
15758 iso-date (calendar-gregorian-from-absolute
15759 (calendar-absolute-from-iso
15760 (list iso-week day year))))
15761 ; FIXME: Should we also push ISO weeks into the future?
15762 ; (when (and org-read-date-prefer-future
15763 ; (not iso-year)
15764 ; (< (calendar-absolute-from-gregorian iso-date)
15765 ; (time-to-days (current-time))))
15766 ; (setq year (1+ year)
15767 ; iso-date (calendar-gregorian-from-absolute
15768 ; (calendar-absolute-from-iso
15769 ; (list iso-week day year)))))
15770 (setq month (car iso-date)
15771 year (nth 2 iso-date)
15772 day (nth 1 iso-date)))
15773 (deltan
15774 (setq futurep nil)
15775 (unless deltadef
15776 (let ((now (decode-time (current-time))))
15777 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15778 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15779 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15780 ((equal deltaw "m") (setq month (+ month deltan)))
15781 ((equal deltaw "y") (setq year (+ year deltan)))))
15782 ((and wday (not (nth 3 tl)))
15783 ;; Weekday was given, but no day, so pick that day in the week
15784 ;; on or after the derived date.
15785 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15786 (unless (equal wday wday1)
15787 (setq day (+ day (% (- wday wday1 -7) 7))))))
15788 (if (and (boundp 'org-time-was-given)
15789 (nth 2 tl))
15790 (setq org-time-was-given t))
15791 (if (< year 100) (setq year (+ 2000 year)))
15792 ;; Check of the date is representable
15793 (if org-read-date-force-compatible-dates
15794 (progn
15795 (if (< year 1970)
15796 (setq year 1970 org-read-date-analyze-forced-year t))
15797 (if (> year 2037)
15798 (setq year 2037 org-read-date-analyze-forced-year t)))
15799 (condition-case nil
15800 (ignore (encode-time second minute hour day month year))
15801 (error
15802 (setq year (nth 5 org-defdecode))
15803 (setq org-read-date-analyze-forced-year t))))
15804 (setq org-read-date-analyze-futurep futurep)
15805 (list second minute hour day month year)))
15807 (defvar parse-time-weekdays)
15808 (defun org-read-date-get-relative (s today default)
15809 "Check string S for special relative date string.
15810 TODAY and DEFAULT are internal times, for today and for a default.
15811 Return shift list (N what def-flag)
15812 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15813 N is the number of WHATs to shift.
15814 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15815 the DEFAULT date rather than TODAY."
15816 (require 'parse-time)
15817 (when (and
15818 (string-match
15819 (concat
15820 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15821 "\\([0-9]+\\)?"
15822 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15823 "\\([ \t]\\|$\\)") s)
15824 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15825 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15826 (string-to-char (substring (match-string 1 s) -1))
15827 ?+))
15828 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15829 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15830 (what (if (match-end 3) (match-string 3 s) "d"))
15831 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15832 (date (if rel default today))
15833 (wday (nth 6 (decode-time date)))
15834 delta)
15835 (if wday1
15836 (progn
15837 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15838 (if (= dir ?-) (setq delta (- delta 7)))
15839 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15840 (list delta "d" rel))
15841 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15843 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15844 "Turn a user-specified date into the internal representation.
15845 The internal representation needed by the calendar is (month day year).
15846 This is a wrapper to handle the brain-dead convention in calendar that
15847 user function argument order change dependent on argument order."
15848 (if (boundp 'calendar-date-style)
15849 (cond
15850 ((eq calendar-date-style 'american)
15851 (list arg1 arg2 arg3))
15852 ((eq calendar-date-style 'european)
15853 (list arg2 arg1 arg3))
15854 ((eq calendar-date-style 'iso)
15855 (list arg2 arg3 arg1)))
15856 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15857 (if (org-bound-and-true-p european-calendar-style)
15858 (list arg2 arg1 arg3)
15859 (list arg1 arg2 arg3)))))
15861 (defun org-eval-in-calendar (form &optional keepdate)
15862 "Eval FORM in the calendar window and return to current window.
15863 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15864 otherwise stick to the current value of `org-ans2'."
15865 (let ((sf (selected-frame))
15866 (sw (selected-window)))
15867 (select-window (get-buffer-window "*Calendar*" t))
15868 (eval form)
15869 (when (and (not keepdate) (calendar-cursor-to-date))
15870 (let* ((date (calendar-cursor-to-date))
15871 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15872 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15873 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15874 (select-window sw)
15875 (org-select-frame-set-input-focus sf)))
15877 (defun org-calendar-select ()
15878 "Return to `org-read-date' with the date currently selected.
15879 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15880 (interactive)
15881 (when (calendar-cursor-to-date)
15882 (let* ((date (calendar-cursor-to-date))
15883 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15884 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15885 (if (active-minibuffer-window) (exit-minibuffer))))
15887 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15888 "Insert a date stamp for the date given by the internal TIME.
15889 WITH-HM means use the stamp format that includes the time of the day.
15890 INACTIVE means use square brackets instead of angular ones, so that the
15891 stamp will not contribute to the agenda.
15892 PRE and POST are optional strings to be inserted before and after the
15893 stamp.
15894 The command returns the inserted time stamp."
15895 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15896 stamp)
15897 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15898 (insert-before-markers (or pre ""))
15899 (when (listp extra)
15900 (setq extra (car extra))
15901 (if (and (stringp extra)
15902 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15903 (setq extra (format "-%02d:%02d"
15904 (string-to-number (match-string 1 extra))
15905 (string-to-number (match-string 2 extra))))
15906 (setq extra nil)))
15907 (when extra
15908 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15909 (insert-before-markers (setq stamp (format-time-string fmt time)))
15910 (insert-before-markers (or post ""))
15911 (setq org-last-inserted-timestamp stamp)))
15913 (defun org-toggle-time-stamp-overlays ()
15914 "Toggle the use of custom time stamp formats."
15915 (interactive)
15916 (setq org-display-custom-times (not org-display-custom-times))
15917 (unless org-display-custom-times
15918 (let ((p (point-min)) (bmp (buffer-modified-p)))
15919 (while (setq p (next-single-property-change p 'display))
15920 (if (and (get-text-property p 'display)
15921 (eq (get-text-property p 'face) 'org-date))
15922 (remove-text-properties
15923 p (setq p (next-single-property-change p 'display))
15924 '(display t))))
15925 (set-buffer-modified-p bmp)))
15926 (if (featurep 'xemacs)
15927 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15928 (org-restart-font-lock)
15929 (setq org-table-may-need-update t)
15930 (if org-display-custom-times
15931 (message "Time stamps are overlaid with custom format")
15932 (message "Time stamp overlays removed")))
15934 (defun org-display-custom-time (beg end)
15935 "Overlay modified time stamp format over timestamp between BEG and END."
15936 (let* ((ts (buffer-substring beg end))
15937 t1 w1 with-hm tf time str w2 (off 0))
15938 (save-match-data
15939 (setq t1 (org-parse-time-string ts t))
15940 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15941 (setq off (- (match-end 0) (match-beginning 0)))))
15942 (setq end (- end off))
15943 (setq w1 (- end beg)
15944 with-hm (and (nth 1 t1) (nth 2 t1))
15945 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15946 time (org-fix-decoded-time t1)
15947 str (org-add-props
15948 (format-time-string
15949 (substring tf 1 -1) (apply 'encode-time time))
15950 nil 'mouse-face 'highlight)
15951 w2 (length str))
15952 (if (not (= w2 w1))
15953 (add-text-properties (1+ beg) (+ 2 beg)
15954 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15955 (if (featurep 'xemacs)
15956 (progn
15957 (put-text-property beg end 'invisible t)
15958 (put-text-property beg end 'end-glyph (make-glyph str)))
15959 (put-text-property beg end 'display str))))
15961 (defun org-translate-time (string)
15962 "Translate all timestamps in STRING to custom format.
15963 But do this only if the variable `org-display-custom-times' is set."
15964 (when org-display-custom-times
15965 (save-match-data
15966 (let* ((start 0)
15967 (re org-ts-regexp-both)
15968 t1 with-hm inactive tf time str beg end)
15969 (while (setq start (string-match re string start))
15970 (setq beg (match-beginning 0)
15971 end (match-end 0)
15972 t1 (save-match-data
15973 (org-parse-time-string (substring string beg end) t))
15974 with-hm (and (nth 1 t1) (nth 2 t1))
15975 inactive (equal (substring string beg (1+ beg)) "[")
15976 tf (funcall (if with-hm 'cdr 'car)
15977 org-time-stamp-custom-formats)
15978 time (org-fix-decoded-time t1)
15979 str (format-time-string
15980 (concat
15981 (if inactive "[" "<") (substring tf 1 -1)
15982 (if inactive "]" ">"))
15983 (apply 'encode-time time))
15984 string (replace-match str t t string)
15985 start (+ start (length str)))))))
15986 string)
15988 (defun org-fix-decoded-time (time)
15989 "Set 0 instead of nil for the first 6 elements of time.
15990 Don't touch the rest."
15991 (let ((n 0))
15992 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15994 (defun org-days-to-time (timestamp-string)
15995 "Difference between TIMESTAMP-STRING and now in days."
15996 (- (time-to-days (org-time-string-to-time timestamp-string))
15997 (time-to-days (current-time))))
15999 (defun org-deadline-close (timestamp-string &optional ndays)
16000 "Is the time in TIMESTAMP-STRING close to the current date?"
16001 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16002 (and (< (org-days-to-time timestamp-string) ndays)
16003 (not (org-entry-is-done-p))))
16005 (defun org-get-wdays (ts)
16006 "Get the deadline lead time appropriate for timestring TS."
16007 (cond
16008 ((<= org-deadline-warning-days 0)
16009 ;; 0 or negative, enforce this value no matter what
16010 (- org-deadline-warning-days))
16011 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16012 ;; lead time is specified.
16013 (floor (* (string-to-number (match-string 1 ts))
16014 (cdr (assoc (match-string 2 ts)
16015 '(("d" . 1) ("w" . 7)
16016 ("m" . 30.4) ("y" . 365.25)))))))
16017 ;; go for the default.
16018 (t org-deadline-warning-days)))
16020 (defun org-calendar-select-mouse (ev)
16021 "Return to `org-read-date' with the date currently selected.
16022 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16023 (interactive "e")
16024 (mouse-set-point ev)
16025 (when (calendar-cursor-to-date)
16026 (let* ((date (calendar-cursor-to-date))
16027 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16028 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16029 (if (active-minibuffer-window) (exit-minibuffer))))
16031 (defun org-check-deadlines (ndays)
16032 "Check if there are any deadlines due or past due.
16033 A deadline is considered due if it happens within `org-deadline-warning-days'
16034 days from today's date. If the deadline appears in an entry marked DONE,
16035 it is not shown. The prefix arg NDAYS can be used to test that many
16036 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16037 (interactive "P")
16038 (let* ((org-warn-days
16039 (cond
16040 ((equal ndays '(4)) 100000)
16041 (ndays (prefix-numeric-value ndays))
16042 (t (abs org-deadline-warning-days))))
16043 (case-fold-search nil)
16044 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16045 (callback
16046 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16048 (message "%d deadlines past-due or due within %d days"
16049 (org-occur regexp nil callback)
16050 org-warn-days)))
16052 (defsubst org-re-timestamp (type)
16053 "Return a regexp for timestamp TYPE.
16054 Allowed values for TYPE are:
16056 all: all timestamps
16057 active: only active timestamps (<...>)
16058 inactive: only inactive timestamps ([...])
16059 scheduled: only scheduled timestamps
16060 deadline: only deadline timestamps
16062 When TYPE is nil, fall back on returning a regexp that matches
16063 both scheduled and deadline timestamps."
16064 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16065 ((eq type 'active) org-ts-regexp)
16066 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16067 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16068 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16069 ((eq type 'scheduled-or-deadline)
16070 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16072 (defun org-check-before-date (date)
16073 "Check if there are deadlines or scheduled entries before DATE."
16074 (interactive (list (org-read-date)))
16075 (let ((case-fold-search nil)
16076 (regexp (org-re-timestamp org-ts-type))
16077 (callback
16078 (lambda () (time-less-p
16079 (org-time-string-to-time (match-string 1))
16080 (org-time-string-to-time date)))))
16081 (message "%d entries before %s"
16082 (org-occur regexp nil callback) date)))
16084 (defun org-check-after-date (date)
16085 "Check if there are deadlines or scheduled entries after DATE."
16086 (interactive (list (org-read-date)))
16087 (let ((case-fold-search nil)
16088 (regexp (org-re-timestamp org-ts-type))
16089 (callback
16090 (lambda () (not
16091 (time-less-p
16092 (org-time-string-to-time (match-string 1))
16093 (org-time-string-to-time date))))))
16094 (message "%d entries after %s"
16095 (org-occur regexp nil callback) date)))
16097 (defun org-check-dates-range (start-date end-date)
16098 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16099 (interactive (list (org-read-date nil nil nil "Range starts")
16100 (org-read-date nil nil nil "Range end")))
16101 (let ((case-fold-search nil)
16102 (regexp (org-re-timestamp org-ts-type))
16103 (callback
16104 (lambda ()
16105 (let ((match (match-string 1)))
16106 (and
16107 (not (time-less-p
16108 (org-time-string-to-time match)
16109 (org-time-string-to-time start-date)))
16110 (time-less-p
16111 (org-time-string-to-time match)
16112 (org-time-string-to-time end-date)))))))
16113 (message "%d entries between %s and %s"
16114 (org-occur regexp nil callback) start-date end-date)))
16116 (defun org-evaluate-time-range (&optional to-buffer)
16117 "Evaluate a time range by computing the difference between start and end.
16118 Normally the result is just printed in the echo area, but with prefix arg
16119 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16120 If the time range is actually in a table, the result is inserted into the
16121 next column.
16122 For time difference computation, a year is assumed to be exactly 365
16123 days in order to avoid rounding problems."
16124 (interactive "P")
16126 (org-clock-update-time-maybe)
16127 (save-excursion
16128 (unless (org-at-date-range-p t)
16129 (goto-char (point-at-bol))
16130 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16131 (if (not (org-at-date-range-p t))
16132 (error "Not at a time-stamp range, and none found in current line")))
16133 (let* ((ts1 (match-string 1))
16134 (ts2 (match-string 2))
16135 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16136 (match-end (match-end 0))
16137 (time1 (org-time-string-to-time ts1))
16138 (time2 (org-time-string-to-time ts2))
16139 (t1 (org-float-time time1))
16140 (t2 (org-float-time time2))
16141 (diff (abs (- t2 t1)))
16142 (negative (< (- t2 t1) 0))
16143 ;; (ys (floor (* 365 24 60 60)))
16144 (ds (* 24 60 60))
16145 (hs (* 60 60))
16146 (fy "%dy %dd %02d:%02d")
16147 (fy1 "%dy %dd")
16148 (fd "%dd %02d:%02d")
16149 (fd1 "%dd")
16150 (fh "%02d:%02d")
16151 y d h m align)
16152 (if havetime
16153 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16155 d (floor (/ diff ds)) diff (mod diff ds)
16156 h (floor (/ diff hs)) diff (mod diff hs)
16157 m (floor (/ diff 60)))
16158 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16160 d (floor (+ (/ diff ds) 0.5))
16161 h 0 m 0))
16162 (if (not to-buffer)
16163 (message "%s" (org-make-tdiff-string y d h m))
16164 (if (org-at-table-p)
16165 (progn
16166 (goto-char match-end)
16167 (setq align t)
16168 (and (looking-at " *|") (goto-char (match-end 0))))
16169 (goto-char match-end))
16170 (if (looking-at
16171 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16172 (replace-match ""))
16173 (if negative (insert " -"))
16174 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16175 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16176 (insert " " (format fh h m))))
16177 (if align (org-table-align))
16178 (message "Time difference inserted")))))
16180 (defun org-make-tdiff-string (y d h m)
16181 (let ((fmt "")
16182 (l nil))
16183 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16184 l (push y l)))
16185 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16186 l (push d l)))
16187 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16188 l (push h l)))
16189 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16190 l (push m l)))
16191 (apply 'format fmt (nreverse l))))
16193 (defun org-time-string-to-time (s &optional buffer pos)
16194 "Convert a timestamp string into internal time."
16195 (condition-case errdata
16196 (apply 'encode-time (org-parse-time-string s))
16197 (error (error "Bad timestamp `%s'%s\nError was: %s"
16198 s (if (not (and buffer pos))
16200 (format " at %d in buffer `%s'" pos buffer))
16201 (cdr errdata)))))
16203 (defun org-time-string-to-seconds (s)
16204 "Convert a timestamp string to a number of seconds."
16205 (org-float-time (org-time-string-to-time s)))
16207 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16208 "Convert a time stamp to an absolute day number.
16209 If there is a specifier for a cyclic time stamp, get the closest date to
16210 DAYNR.
16211 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16212 The variable date is bound by the calendar when this is called."
16213 (cond
16214 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16215 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16216 daynr
16217 (+ daynr 1000)))
16218 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16219 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16220 (time-to-days (current-time))) (match-string 0 s)
16221 prefer show-all))
16222 (t (time-to-days
16223 (condition-case errdata
16224 (apply 'encode-time (org-parse-time-string s))
16225 (error (error "Bad timestamp `%s'%s\nError was: %s"
16226 s (if (not (and buffer pos))
16228 (format " at %d in buffer `%s'" pos buffer))
16229 (cdr errdata))))))))
16231 (defun org-days-to-iso-week (days)
16232 "Return the iso week number."
16233 (require 'cal-iso)
16234 (car (calendar-iso-from-absolute days)))
16236 (defun org-small-year-to-year (year)
16237 "Convert 2-digit years into 4-digit years.
16238 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16239 The year 2000 cannot be abbreviated. Any year larger than 99
16240 is returned unchanged."
16241 (if (< year 38)
16242 (setq year (+ 2000 year))
16243 (if (< year 100)
16244 (setq year (+ 1900 year))))
16245 year)
16247 (defun org-time-from-absolute (d)
16248 "Return the time corresponding to date D.
16249 D may be an absolute day number, or a calendar-type list (month day year)."
16250 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16251 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16253 (defun org-calendar-holiday ()
16254 "List of holidays, for Diary display in Org-mode."
16255 (require 'holidays)
16256 (let ((hl (funcall
16257 (if (fboundp 'calendar-check-holidays)
16258 'calendar-check-holidays 'check-calendar-holidays) date)))
16259 (if hl (mapconcat 'identity hl "; "))))
16261 (defun org-diary-sexp-entry (sexp entry date)
16262 "Process a SEXP diary ENTRY for DATE."
16263 (require 'diary-lib)
16264 (let ((result (if calendar-debug-sexp
16265 (let ((stack-trace-on-error t))
16266 (eval (car (read-from-string sexp))))
16267 (condition-case nil
16268 (eval (car (read-from-string sexp)))
16269 (error
16270 (beep)
16271 (message "Bad sexp at line %d in %s: %s"
16272 (org-current-line)
16273 (buffer-file-name) sexp)
16274 (sleep-for 2))))))
16275 (cond ((stringp result) (split-string result "; "))
16276 ((and (consp result)
16277 (not (consp (cdr result)))
16278 (stringp (cdr result))) (cdr result))
16279 ((and (consp result)
16280 (stringp (car result))) result)
16281 (result entry))))
16283 (defun org-diary-to-ical-string (frombuf)
16284 "Get iCalendar entries from diary entries in buffer FROMBUF.
16285 This uses the icalendar.el library."
16286 (let* ((tmpdir (if (featurep 'xemacs)
16287 (temp-directory)
16288 temporary-file-directory))
16289 (tmpfile (make-temp-name
16290 (expand-file-name "orgics" tmpdir)))
16291 buf rtn b e)
16292 (with-current-buffer frombuf
16293 (icalendar-export-region (point-min) (point-max) tmpfile)
16294 (setq buf (find-buffer-visiting tmpfile))
16295 (set-buffer buf)
16296 (goto-char (point-min))
16297 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16298 (setq b (match-beginning 0)))
16299 (goto-char (point-max))
16300 (if (re-search-backward "^END:VEVENT" nil t)
16301 (setq e (match-end 0)))
16302 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16303 (kill-buffer buf)
16304 (delete-file tmpfile)
16305 rtn))
16307 (defun org-closest-date (start current change prefer show-all)
16308 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16309 When PREFER is `past', return a date that is either CURRENT or past.
16310 When PREFER is `future', return a date that is either CURRENT or future.
16311 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16312 ;; Make the proper lists from the dates
16313 (catch 'exit
16314 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16315 dn dw sday cday n1 n2 n0
16316 d m y y1 y2 date1 date2 nmonths nm ny m2)
16318 (setq start (org-date-to-gregorian start)
16319 current (org-date-to-gregorian
16320 (if show-all
16321 current
16322 (time-to-days (current-time))))
16323 sday (calendar-absolute-from-gregorian start)
16324 cday (calendar-absolute-from-gregorian current))
16326 (if (<= cday sday) (throw 'exit sday))
16328 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16329 (setq dn (string-to-number (match-string 1 change))
16330 dw (cdr (assoc (match-string 2 change) a1)))
16331 (error "Invalid change specifier: %s" change))
16332 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16333 (cond
16334 ((eq dw 'day)
16335 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16336 n2 (+ n1 dn)))
16337 ((eq dw 'year)
16338 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16339 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16340 (setq date1 (list m d y1)
16341 n1 (calendar-absolute-from-gregorian date1)
16342 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16343 n2 (calendar-absolute-from-gregorian date2)))
16344 ((eq dw 'month)
16345 ;; approx number of month between the two dates
16346 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16347 ;; How often does dn fit in there?
16348 (setq d (nth 1 start) m (car start) y (nth 2 start)
16349 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16350 m (+ m nm)
16351 ny (floor (/ m 12))
16352 y (+ y ny)
16353 m (- m (* ny 12)))
16354 (while (> m 12) (setq m (- m 12) y (1+ y)))
16355 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16356 (setq m2 (+ m dn) y2 y)
16357 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16358 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16359 (while (<= n2 cday)
16360 (setq n1 n2 m m2 y y2)
16361 (setq m2 (+ m dn) y2 y)
16362 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16363 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16364 ;; Make sure n1 is the earlier date
16365 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16366 (if show-all
16367 (cond
16368 ((eq prefer 'past) (if (= cday n2) n2 n1))
16369 ((eq prefer 'future) (if (= cday n1) n1 n2))
16370 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16371 (cond
16372 ((eq prefer 'past) (if (= cday n2) n2 n1))
16373 ((eq prefer 'future) (if (= cday n1) n1 n2))
16374 (t (if (= cday n1) n1 n2)))))))
16376 (defun org-date-to-gregorian (date)
16377 "Turn any specification of DATE into a Gregorian date for the calendar."
16378 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16379 ((and (listp date) (= (length date) 3)) date)
16380 ((stringp date)
16381 (setq date (org-parse-time-string date))
16382 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16383 ((listp date)
16384 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16386 (defun org-parse-time-string (s &optional nodefault)
16387 "Parse the standard Org-mode time string.
16388 This should be a lot faster than the normal `parse-time-string'.
16389 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16390 hour and minute fields will be nil if not given."
16391 (if (string-match org-ts-regexp0 s)
16392 (list 0
16393 (if (or (match-beginning 8) (not nodefault))
16394 (string-to-number (or (match-string 8 s) "0")))
16395 (if (or (match-beginning 7) (not nodefault))
16396 (string-to-number (or (match-string 7 s) "0")))
16397 (string-to-number (match-string 4 s))
16398 (string-to-number (match-string 3 s))
16399 (string-to-number (match-string 2 s))
16400 nil nil nil)
16401 (error "Not a standard Org-mode time string: %s" s)))
16403 (defun org-timestamp-up (&optional arg)
16404 "Increase the date item at the cursor by one.
16405 If the cursor is on the year, change the year. If it is on the month,
16406 the day or the time, change that.
16407 With prefix ARG, change by that many units."
16408 (interactive "p")
16409 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16411 (defun org-timestamp-down (&optional arg)
16412 "Decrease the date item at the cursor by one.
16413 If the cursor is on the year, change the year. If it is on the month,
16414 the day or the time, change that.
16415 With prefix ARG, change by that many units."
16416 (interactive "p")
16417 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16419 (defun org-timestamp-up-day (&optional arg)
16420 "Increase the date in the time stamp by one day.
16421 With prefix ARG, change that many days."
16422 (interactive "p")
16423 (if (and (not (org-at-timestamp-p t))
16424 (org-at-heading-p))
16425 (org-todo 'up)
16426 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16428 (defun org-timestamp-down-day (&optional arg)
16429 "Decrease the date in the time stamp by one day.
16430 With prefix ARG, change that many days."
16431 (interactive "p")
16432 (if (and (not (org-at-timestamp-p t))
16433 (org-at-heading-p))
16434 (org-todo 'down)
16435 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16437 (defun org-at-timestamp-p (&optional inactive-ok)
16438 "Determine if the cursor is in or at a timestamp."
16439 (interactive)
16440 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16441 (pos (point))
16442 (ans (or (looking-at tsr)
16443 (save-excursion
16444 (skip-chars-backward "^[<\n\r\t")
16445 (if (> (point) (point-min)) (backward-char 1))
16446 (and (looking-at tsr)
16447 (> (- (match-end 0) pos) -1))))))
16448 (and ans
16449 (boundp 'org-ts-what)
16450 (setq org-ts-what
16451 (cond
16452 ((= pos (match-beginning 0)) 'bracket)
16453 ;; Point is considered to be "on the bracket" whether
16454 ;; it's really on it or right after it.
16455 ((= pos (1- (match-end 0))) 'bracket)
16456 ((= pos (match-end 0)) 'after)
16457 ((org-pos-in-match-range pos 2) 'year)
16458 ((org-pos-in-match-range pos 3) 'month)
16459 ((org-pos-in-match-range pos 7) 'hour)
16460 ((org-pos-in-match-range pos 8) 'minute)
16461 ((or (org-pos-in-match-range pos 4)
16462 (org-pos-in-match-range pos 5)) 'day)
16463 ((and (> pos (or (match-end 8) (match-end 5)))
16464 (< pos (match-end 0)))
16465 (- pos (or (match-end 8) (match-end 5))))
16466 (t 'day))))
16467 ans))
16469 (defun org-toggle-timestamp-type ()
16470 "Toggle the type (<active> or [inactive]) of a time stamp."
16471 (interactive)
16472 (when (org-at-timestamp-p t)
16473 (let ((beg (match-beginning 0)) (end (match-end 0))
16474 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16475 (save-excursion
16476 (goto-char beg)
16477 (while (re-search-forward "[][<>]" end t)
16478 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16479 t t)))
16480 (message "Timestamp is now %sactive"
16481 (if (equal (char-after beg) ?<) "" "in")))))
16483 (defvar org-clock-history) ; defined in org-clock.el
16484 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16485 (defun org-timestamp-change (n &optional what updown)
16486 "Change the date in the time stamp at point.
16487 The date will be changed by N times WHAT. WHAT can be `day', `month',
16488 `year', `minute', `second'. If WHAT is not given, the cursor position
16489 in the timestamp determines what will be changed."
16490 (let ((origin (point)) origin-cat
16491 with-hm inactive
16492 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16493 org-ts-what
16494 extra rem
16495 ts time time0 fixnext clrgx)
16496 (if (not (org-at-timestamp-p t))
16497 (error "Not at a timestamp"))
16498 (if (and (not what) (eq org-ts-what 'bracket))
16499 (org-toggle-timestamp-type)
16500 ;; Point isn't on brackets. Remember the part of the time-stamp
16501 ;; the point was in. Indeed, size of time-stamps may change,
16502 ;; but point must be kept in the same category nonetheless.
16503 (setq origin-cat org-ts-what)
16504 (if (and (not what) (not (eq org-ts-what 'day))
16505 org-display-custom-times
16506 (get-text-property (point) 'display)
16507 (not (get-text-property (1- (point)) 'display)))
16508 (setq org-ts-what 'day))
16509 (setq org-ts-what (or what org-ts-what)
16510 inactive (= (char-after (match-beginning 0)) ?\[)
16511 ts (match-string 0))
16512 (replace-match "")
16513 (if (string-match
16514 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16516 (setq extra (match-string 1 ts)))
16517 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16518 (setq with-hm t))
16519 (setq time0 (org-parse-time-string ts))
16520 (when (and updown
16521 (eq org-ts-what 'minute)
16522 (not current-prefix-arg))
16523 ;; This looks like s-up and s-down. Change by one rounding step.
16524 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16525 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16526 (setcar (cdr time0) (+ (nth 1 time0)
16527 (if (> n 0) (- rem) (- dm rem))))))
16528 (setq time
16529 (encode-time (or (car time0) 0)
16530 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16531 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16532 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16533 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16534 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16535 (nthcdr 6 time0)))
16536 (when (and (member org-ts-what '(hour minute))
16537 extra
16538 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16539 (setq extra (org-modify-ts-extra
16540 extra
16541 (if (eq org-ts-what 'hour) 2 5)
16542 n dm)))
16543 (when (integerp org-ts-what)
16544 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16545 (if (eq what 'calendar)
16546 (let ((cal-date (org-get-date-from-calendar)))
16547 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16548 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16549 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16550 (setcar time0 (or (car time0) 0))
16551 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16552 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16553 (setq time (apply 'encode-time time0))))
16554 ;; Insert the new time-stamp, and ensure point stays in the same
16555 ;; category as before (i.e. not after the last position in that
16556 ;; category).
16557 (let ((pos (point)))
16558 ;; Stay before inserted string. `save-excursion' is of no use.
16559 (setq org-last-changed-timestamp
16560 (org-insert-time-stamp time with-hm inactive nil nil extra))
16561 (goto-char pos))
16562 (save-match-data
16563 (looking-at org-ts-regexp3)
16564 (goto-char (cond
16565 ;; `day' category ends before `hour' if any, or at
16566 ;; the end of the day name.
16567 ((eq origin-cat 'day)
16568 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16569 ((eq origin-cat 'hour) (min (match-end 7) origin))
16570 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16571 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16572 ;; `year' and `month' have both fixed size: point
16573 ;; couldn't have moved into another part.
16574 (t origin))))
16575 ;; Update clock if on a CLOCK line.
16576 (org-clock-update-time-maybe)
16577 ;; Maybe adjust the closest clock in `org-clock-history'
16578 (when org-clock-adjust-closest
16579 (if (not (and (org-at-clock-log-p)
16580 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16581 org-clock-history))))))
16582 (message "No clock to adjust")
16583 (cond ((save-excursion ; fix previous clock?
16584 (re-search-backward org-ts-regexp0 nil t)
16585 (org-looking-back (concat org-clock-string " \\[")))
16586 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16587 ((save-excursion ; fix next clock?
16588 (re-search-backward org-ts-regexp0 nil t)
16589 (looking-at (concat org-ts-regexp0 "\\] =>")))
16590 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16591 (save-window-excursion
16592 ;; Find closest clock to point, adjust the previous/next one in history
16593 (let* ((p (save-excursion (org-back-to-heading t)))
16594 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16595 (clfixnth
16596 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16597 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16598 (if (not clfixpos)
16599 (message "No clock to adjust")
16600 (save-excursion
16601 (org-goto-marker-or-bmk clfixpos)
16602 (org-show-subtree)
16603 (when (re-search-forward clrgx nil t)
16604 (goto-char (match-beginning 1))
16605 (let (org-clock-adjust-closest)
16606 (org-timestamp-change n org-ts-what updown))
16607 (message "Clock adjusted in %s for heading: %s"
16608 (file-name-nondirectory (buffer-file-name))
16609 (org-get-heading t t)))))))))
16610 ;; Try to recenter the calendar window, if any.
16611 (if (and org-calendar-follow-timestamp-change
16612 (get-buffer-window "*Calendar*" t)
16613 (memq org-ts-what '(day month year)))
16614 (org-recenter-calendar (time-to-days time))))))
16616 (defun org-modify-ts-extra (s pos n dm)
16617 "Change the different parts of the lead-time and repeat fields in timestamp."
16618 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16619 ng h m new rem)
16620 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16621 (cond
16622 ((or (org-pos-in-match-range pos 2)
16623 (org-pos-in-match-range pos 3))
16624 (setq m (string-to-number (match-string 3 s))
16625 h (string-to-number (match-string 2 s)))
16626 (if (org-pos-in-match-range pos 2)
16627 (setq h (+ h n))
16628 (setq n (* dm (org-no-warnings (signum n))))
16629 (when (not (= 0 (setq rem (% m dm))))
16630 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16631 (setq m (+ m n)))
16632 (if (< m 0) (setq m (+ m 60) h (1- h)))
16633 (if (> m 59) (setq m (- m 60) h (1+ h)))
16634 (setq h (min 24 (max 0 h)))
16635 (setq ng 1 new (format "-%02d:%02d" h m)))
16636 ((org-pos-in-match-range pos 6)
16637 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16638 ((org-pos-in-match-range pos 5)
16639 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16641 ((org-pos-in-match-range pos 9)
16642 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16643 ((org-pos-in-match-range pos 8)
16644 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16646 (when ng
16647 (setq s (concat
16648 (substring s 0 (match-beginning ng))
16650 (substring s (match-end ng))))))
16653 (defun org-recenter-calendar (date)
16654 "If the calendar is visible, recenter it to DATE."
16655 (let ((cwin (get-buffer-window "*Calendar*" t)))
16656 (when cwin
16657 (let ((calendar-move-hook nil))
16658 (with-selected-window cwin
16659 (calendar-goto-date (if (listp date) date
16660 (calendar-gregorian-from-absolute date))))))))
16662 (defun org-goto-calendar (&optional arg)
16663 "Go to the Emacs calendar at the current date.
16664 If there is a time stamp in the current line, go to that date.
16665 A prefix ARG can be used to force the current date."
16666 (interactive "P")
16667 (let ((tsr org-ts-regexp) diff
16668 (calendar-move-hook nil)
16669 (calendar-view-holidays-initially-flag nil)
16670 (calendar-view-diary-initially-flag nil))
16671 (if (or (org-at-timestamp-p)
16672 (save-excursion
16673 (beginning-of-line 1)
16674 (looking-at (concat ".*" tsr))))
16675 (let ((d1 (time-to-days (current-time)))
16676 (d2 (time-to-days
16677 (org-time-string-to-time (match-string 1)))))
16678 (setq diff (- d2 d1))))
16679 (calendar)
16680 (calendar-goto-today)
16681 (if (and diff (not arg)) (calendar-forward-day diff))))
16683 (defun org-get-date-from-calendar ()
16684 "Return a list (month day year) of date at point in calendar."
16685 (with-current-buffer "*Calendar*"
16686 (save-match-data
16687 (calendar-cursor-to-date))))
16689 (defun org-date-from-calendar ()
16690 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16691 If there is already a time stamp at the cursor position, update it."
16692 (interactive)
16693 (if (org-at-timestamp-p t)
16694 (org-timestamp-change 0 'calendar)
16695 (let ((cal-date (org-get-date-from-calendar)))
16696 (org-insert-time-stamp
16697 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16699 (defun org-minutes-to-hh:mm-string (m)
16700 "Compute H:MM from a number of minutes."
16701 (let ((h (/ m 60)))
16702 (setq m (- m (* 60 h)))
16703 (format org-time-clocksum-format h m)))
16705 (defun org-hh:mm-string-to-minutes (s)
16706 "Convert a string H:MM to a number of minutes.
16707 If the string is just a number, interpret it as minutes.
16708 In fact, the first hh:mm or number in the string will be taken,
16709 there can be extra stuff in the string.
16710 If no number is found, the return value is 0."
16711 (cond
16712 ((integerp s) s)
16713 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16714 (+ (* (string-to-number (match-string 1 s)) 60)
16715 (string-to-number (match-string 2 s))))
16716 ((string-match "\\([0-9]+\\)" s)
16717 (string-to-number (match-string 1 s)))
16718 (t 0)))
16720 (defcustom org-effort-durations
16721 `(("h" . 60)
16722 ("d" . ,(* 60 8))
16723 ("w" . ,(* 60 8 5))
16724 ("m" . ,(* 60 8 5 4))
16725 ("y" . ,(* 60 8 5 40)))
16726 "Conversion factor to minutes for an effort modifier.
16728 Each entry has the form (MODIFIER . MINUTES).
16730 In an effort string, a number followed by MODIFIER is multiplied
16731 by the specified number of MINUTES to obtain an effort in
16732 minutes.
16734 For example, if the value of this variable is ((\"hours\" . 60)), then an
16735 effort string \"2hours\" is equivalent to 120 minutes."
16736 :group 'org-agenda
16737 :version "24.1"
16738 :type '(alist :key-type (string :tag "Modifier")
16739 :value-type (number :tag "Minutes")))
16741 (defun org-duration-string-to-minutes (s &optional output-to-string)
16742 "Convert a duration string S to minutes.
16744 A bare number is interpreted as minutes, modifiers can be set by
16745 customizing `org-effort-durations' (which see).
16747 Entries containing a colon are interpreted as H:MM by
16748 `org-hh:mm-string-to-minutes'."
16749 (let ((result 0)
16750 (re (concat "\\([0-9.]+\\) *\\("
16751 (regexp-opt (mapcar 'car org-effort-durations))
16752 "\\)")))
16753 (while (string-match re s)
16754 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16755 (string-to-number (match-string 1 s))))
16756 (setq s (replace-match "" nil t s)))
16757 (setq result (floor result))
16758 (incf result (org-hh:mm-string-to-minutes s))
16759 (if output-to-string (number-to-string result) result)))
16761 ;;;; Files
16763 (defun org-save-all-org-buffers ()
16764 "Save all Org-mode buffers without user confirmation."
16765 (interactive)
16766 (message "Saving all Org-mode buffers...")
16767 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16768 (when (featurep 'org-id) (org-id-locations-save))
16769 (message "Saving all Org-mode buffers... done"))
16771 (defun org-revert-all-org-buffers ()
16772 "Revert all Org-mode buffers.
16773 Prompt for confirmation when there are unsaved changes.
16774 Be sure you know what you are doing before letting this function
16775 overwrite your changes.
16777 This function is useful in a setup where one tracks org files
16778 with a version control system, to revert on one machine after pulling
16779 changes from another. I believe the procedure must be like this:
16781 1. M-x org-save-all-org-buffers
16782 2. Pull changes from the other machine, resolve conflicts
16783 3. M-x org-revert-all-org-buffers"
16784 (interactive)
16785 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16786 (error "Abort"))
16787 (save-excursion
16788 (save-window-excursion
16789 (mapc
16790 (lambda (b)
16791 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16792 (with-current-buffer b buffer-file-name))
16793 (org-pop-to-buffer-same-window b)
16794 (revert-buffer t 'no-confirm)))
16795 (buffer-list))
16796 (when (and (featurep 'org-id) org-id-track-globally)
16797 (org-id-locations-load)))))
16799 ;;;; Agenda files
16801 ;;;###autoload
16802 (defun org-switchb (&optional arg)
16803 "Switch between Org buffers.
16804 With one prefix argument, restrict available buffers to files.
16805 With two prefix arguments, restrict available buffers to agenda files.
16807 Defaults to `iswitchb' for buffer name completion.
16808 Set `org-completion-use-ido' to make it use ido instead."
16809 (interactive "P")
16810 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16811 ((equal arg '(16)) (org-buffer-list 'agenda))
16812 (t (org-buffer-list))))
16813 (org-completion-use-iswitchb org-completion-use-iswitchb)
16814 (org-completion-use-ido org-completion-use-ido))
16815 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16816 (setq org-completion-use-iswitchb t))
16817 (org-pop-to-buffer-same-window
16818 (org-icompleting-read "Org buffer: "
16819 (mapcar 'list (mapcar 'buffer-name blist))
16820 nil t))))
16822 ;;; Define some older names previously used for this functionality
16823 ;;;###autoload
16824 (defalias 'org-ido-switchb 'org-switchb)
16825 ;;;###autoload
16826 (defalias 'org-iswitchb 'org-switchb)
16828 (defun org-buffer-list (&optional predicate exclude-tmp)
16829 "Return a list of Org buffers.
16830 PREDICATE can be `export', `files' or `agenda'.
16832 export restrict the list to Export buffers.
16833 files restrict the list to buffers visiting Org files.
16834 agenda restrict the list to buffers visiting agenda files.
16836 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16837 (let* ((bfn nil)
16838 (agenda-files (and (eq predicate 'agenda)
16839 (mapcar 'file-truename (org-agenda-files t))))
16840 (filter
16841 (cond
16842 ((eq predicate 'files)
16843 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16844 ((eq predicate 'export)
16845 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16846 ((eq predicate 'agenda)
16847 (lambda (b)
16848 (with-current-buffer b
16849 (and (derived-mode-p 'org-mode)
16850 (setq bfn (buffer-file-name b))
16851 (member (file-truename bfn) agenda-files)))))
16852 (t (lambda (b) (with-current-buffer b
16853 (or (derived-mode-p 'org-mode)
16854 (string-match "\*Org .*Export"
16855 (buffer-name b)))))))))
16856 (delq nil
16857 (mapcar
16858 (lambda(b)
16859 (if (and (funcall filter b)
16860 (or (not exclude-tmp)
16861 (not (string-match "tmp" (buffer-name b)))))
16863 nil))
16864 (buffer-list)))))
16866 (defun org-agenda-files (&optional unrestricted archives)
16867 "Get the list of agenda files.
16868 Optional UNRESTRICTED means return the full list even if a restriction
16869 is currently in place.
16870 When ARCHIVES is t, include all archive files that are really being
16871 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16872 `org-agenda-archives-mode' is t."
16873 (let ((files
16874 (cond
16875 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16876 ((stringp org-agenda-files) (org-read-agenda-file-list))
16877 ((listp org-agenda-files) org-agenda-files)
16878 (t (error "Invalid value of `org-agenda-files'")))))
16879 (setq files (apply 'append
16880 (mapcar (lambda (f)
16881 (if (file-directory-p f)
16882 (directory-files
16883 f t org-agenda-file-regexp)
16884 (list f)))
16885 files)))
16886 (when org-agenda-skip-unavailable-files
16887 (setq files (delq nil
16888 (mapcar (function
16889 (lambda (file)
16890 (and (file-readable-p file) file)))
16891 files))))
16892 (when (or (eq archives t)
16893 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16894 (setq files (org-add-archive-files files)))
16895 files))
16897 (defun org-agenda-file-p (&optional file)
16898 "Return non-nil, if FILE is an agenda file.
16899 If FILE is omitted, use the file associated with the current
16900 buffer."
16901 (member (or file (buffer-file-name))
16902 (org-agenda-files t)))
16904 (defun org-edit-agenda-file-list ()
16905 "Edit the list of agenda files.
16906 Depending on setup, this either uses customize to edit the variable
16907 `org-agenda-files', or it visits the file that is holding the list. In the
16908 latter case, the buffer is set up in a way that saving it automatically kills
16909 the buffer and restores the previous window configuration."
16910 (interactive)
16911 (if (stringp org-agenda-files)
16912 (let ((cw (current-window-configuration)))
16913 (find-file org-agenda-files)
16914 (org-set-local 'org-window-configuration cw)
16915 (org-add-hook 'after-save-hook
16916 (lambda ()
16917 (set-window-configuration
16918 (prog1 org-window-configuration
16919 (kill-buffer (current-buffer))))
16920 (org-install-agenda-files-menu)
16921 (message "New agenda file list installed"))
16922 nil 'local)
16923 (message "%s" (substitute-command-keys
16924 "Edit list and finish with \\[save-buffer]")))
16925 (customize-variable 'org-agenda-files)))
16927 (defun org-store-new-agenda-file-list (list)
16928 "Set new value for the agenda file list and save it correctly."
16929 (if (stringp org-agenda-files)
16930 (let ((fe (org-read-agenda-file-list t)) b u)
16931 (while (setq b (find-buffer-visiting org-agenda-files))
16932 (kill-buffer b))
16933 (with-temp-file org-agenda-files
16934 (insert
16935 (mapconcat
16936 (lambda (f) ;; Keep un-expanded entries.
16937 (if (setq u (assoc f fe))
16938 (cdr u)
16940 list "\n")
16941 "\n")))
16942 (let ((org-mode-hook nil) (org-inhibit-startup t)
16943 (org-insert-mode-line-in-empty-file nil))
16944 (setq org-agenda-files list)
16945 (customize-save-variable 'org-agenda-files org-agenda-files))))
16947 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16948 "Read the list of agenda files from a file.
16949 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16950 filenames, used by `org-store-new-agenda-file-list' to write back
16951 un-expanded file names."
16952 (when (file-directory-p org-agenda-files)
16953 (error "`org-agenda-files' cannot be a single directory"))
16954 (when (stringp org-agenda-files)
16955 (with-temp-buffer
16956 (insert-file-contents org-agenda-files)
16957 (mapcar
16958 (lambda (f)
16959 (let ((e (expand-file-name (substitute-in-file-name f)
16960 org-directory)))
16961 (if pair-with-expansion
16962 (cons e f)
16963 e)))
16964 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16966 ;;;###autoload
16967 (defun org-cycle-agenda-files ()
16968 "Cycle through the files in `org-agenda-files'.
16969 If the current buffer visits an agenda file, find the next one in the list.
16970 If the current buffer does not, find the first agenda file."
16971 (interactive)
16972 (let* ((fs (org-agenda-files t))
16973 (files (append fs (list (car fs))))
16974 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16975 file)
16976 (unless files (error "No agenda files"))
16977 (catch 'exit
16978 (while (setq file (pop files))
16979 (if (equal (file-truename file) tcf)
16980 (when (car files)
16981 (find-file (car files))
16982 (throw 'exit t))))
16983 (find-file (car fs)))
16984 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16986 (defun org-agenda-file-to-front (&optional to-end)
16987 "Move/add the current file to the top of the agenda file list.
16988 If the file is not present in the list, it is added to the front. If it is
16989 present, it is moved there. With optional argument TO-END, add/move to the
16990 end of the list."
16991 (interactive "P")
16992 (let ((org-agenda-skip-unavailable-files nil)
16993 (file-alist (mapcar (lambda (x)
16994 (cons (file-truename x) x))
16995 (org-agenda-files t)))
16996 (ctf (file-truename buffer-file-name))
16997 x had)
16998 (setq x (assoc ctf file-alist) had x)
17000 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17001 (if to-end
17002 (setq file-alist (append (delq x file-alist) (list x)))
17003 (setq file-alist (cons x (delq x file-alist))))
17004 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17005 (org-install-agenda-files-menu)
17006 (message "File %s to %s of agenda file list"
17007 (if had "moved" "added") (if to-end "end" "front"))))
17009 (defun org-remove-file (&optional file)
17010 "Remove current file from the list of files in variable `org-agenda-files'.
17011 These are the files which are being checked for agenda entries.
17012 Optional argument FILE means use this file instead of the current."
17013 (interactive)
17014 (let* ((org-agenda-skip-unavailable-files nil)
17015 (file (or file buffer-file-name))
17016 (true-file (file-truename file))
17017 (afile (abbreviate-file-name file))
17018 (files (delq nil (mapcar
17019 (lambda (x)
17020 (if (equal true-file
17021 (file-truename x))
17022 nil x))
17023 (org-agenda-files t)))))
17024 (if (not (= (length files) (length (org-agenda-files t))))
17025 (progn
17026 (org-store-new-agenda-file-list files)
17027 (org-install-agenda-files-menu)
17028 (message "Removed file: %s" afile))
17029 (message "File was not in list: %s (not removed)" afile))))
17031 (defun org-file-menu-entry (file)
17032 (vector file (list 'find-file file) t))
17034 (defun org-check-agenda-file (file)
17035 "Make sure FILE exists. If not, ask user what to do."
17036 (when (not (file-exists-p file))
17037 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17038 (abbreviate-file-name file))
17039 (let ((r (downcase (read-char-exclusive))))
17040 (cond
17041 ((equal r ?r)
17042 (org-remove-file file)
17043 (throw 'nextfile t))
17044 (t (error "Abort"))))))
17046 (defun org-get-agenda-file-buffer (file)
17047 "Get a buffer visiting FILE. If the buffer needs to be created, add
17048 it to the list of buffers which might be released later."
17049 (let ((buf (org-find-base-buffer-visiting file)))
17050 (if buf
17051 buf ; just return it
17052 ;; Make a new buffer and remember it
17053 (setq buf (find-file-noselect file))
17054 (if buf (push buf org-agenda-new-buffers))
17055 buf)))
17057 (defun org-release-buffers (blist)
17058 "Release all buffers in list, asking the user for confirmation when needed.
17059 When a buffer is unmodified, it is just killed. When modified, it is saved
17060 \(if the user agrees) and then killed."
17061 (let (buf file)
17062 (while (setq buf (pop blist))
17063 (setq file (buffer-file-name buf))
17064 (when (and (buffer-modified-p buf)
17065 file
17066 (y-or-n-p (format "Save file %s? " file)))
17067 (with-current-buffer buf (save-buffer)))
17068 (kill-buffer buf))))
17070 (defun org-agenda-prepare-buffers (files)
17071 "Create buffers for all agenda files, protect archived trees and comments."
17072 (interactive)
17073 (let ((pa '(:org-archived t))
17074 (pc '(:org-comment t))
17075 (pall '(:org-archived t :org-comment t))
17076 (inhibit-read-only t)
17077 (rea (concat ":" org-archive-tag ":"))
17078 bmp file re)
17079 (save-excursion
17080 (save-restriction
17081 (while (setq file (pop files))
17082 (catch 'nextfile
17083 (if (bufferp file)
17084 (set-buffer file)
17085 (org-check-agenda-file file)
17086 (set-buffer (org-get-agenda-file-buffer file)))
17087 (widen)
17088 (setq bmp (buffer-modified-p))
17089 (org-refresh-category-properties)
17090 (setq org-todo-keywords-for-agenda
17091 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17092 (setq org-done-keywords-for-agenda
17093 (append org-done-keywords-for-agenda org-done-keywords))
17094 (setq org-todo-keyword-alist-for-agenda
17095 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17096 (setq org-drawers-for-agenda
17097 (append org-drawers-for-agenda org-drawers))
17098 (setq org-tag-alist-for-agenda
17099 (append org-tag-alist-for-agenda org-tag-alist))
17101 (save-excursion
17102 (remove-text-properties (point-min) (point-max) pall)
17103 (when org-agenda-skip-archived-trees
17104 (goto-char (point-min))
17105 (while (re-search-forward rea nil t)
17106 (if (org-at-heading-p t)
17107 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17108 (goto-char (point-min))
17109 (setq re (format org-heading-keyword-regexp-format
17110 org-comment-string))
17111 (while (re-search-forward re nil t)
17112 (add-text-properties
17113 (match-beginning 0) (org-end-of-subtree t) pc)))
17114 (set-buffer-modified-p bmp)))))
17115 (setq org-todo-keywords-for-agenda
17116 (org-uniquify org-todo-keywords-for-agenda))
17117 (setq org-todo-keyword-alist-for-agenda
17118 (org-uniquify org-todo-keyword-alist-for-agenda)
17119 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17121 ;;;; Embedded LaTeX
17123 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17124 "Keymap for the minor `org-cdlatex-mode'.")
17126 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17127 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17128 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17129 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17130 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17132 (defvar org-cdlatex-texmathp-advice-is-done nil
17133 "Flag remembering if we have applied the advice to texmathp already.")
17135 (define-minor-mode org-cdlatex-mode
17136 "Toggle the minor `org-cdlatex-mode'.
17137 This mode supports entering LaTeX environment and math in LaTeX fragments
17138 in Org-mode.
17139 \\{org-cdlatex-mode-map}"
17140 nil " OCDL" nil
17141 (when org-cdlatex-mode
17142 (require 'cdlatex)
17143 (run-hooks 'cdlatex-mode-hook)
17144 (cdlatex-compute-tables))
17145 (unless org-cdlatex-texmathp-advice-is-done
17146 (setq org-cdlatex-texmathp-advice-is-done t)
17147 (defadvice texmathp (around org-math-always-on activate)
17148 "Always return t in org-mode buffers.
17149 This is because we want to insert math symbols without dollars even outside
17150 the LaTeX math segments. If Orgmode thinks that point is actually inside
17151 an embedded LaTeX fragment, let texmathp do its job.
17152 \\[org-cdlatex-mode-map]"
17153 (interactive)
17154 (let (p)
17155 (cond
17156 ((not (derived-mode-p 'org-mode)) ad-do-it)
17157 ((eq this-command 'cdlatex-math-symbol)
17158 (setq ad-return-value t
17159 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17161 (let ((p (org-inside-LaTeX-fragment-p)))
17162 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17163 (setq ad-return-value t
17164 texmathp-why '("Org-mode embedded math" . 0))
17165 (if p ad-do-it)))))))))
17167 (defun turn-on-org-cdlatex ()
17168 "Unconditionally turn on `org-cdlatex-mode'."
17169 (org-cdlatex-mode 1))
17171 (defun org-inside-LaTeX-fragment-p ()
17172 "Test if point is inside a LaTeX fragment.
17173 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17174 sequence appearing also before point.
17175 Even though the matchers for math are configurable, this function assumes
17176 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17177 delimiters are skipped when they have been removed by customization.
17178 The return value is nil, or a cons cell with the delimiter and the
17179 position of this delimiter.
17181 This function does a reasonably good job, but can locally be fooled by
17182 for example currency specifications. For example it will assume being in
17183 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17184 fragments that are properly closed, but during editing, we have to live
17185 with the uncertainty caused by missing closing delimiters. This function
17186 looks only before point, not after."
17187 (catch 'exit
17188 (let ((pos (point))
17189 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17190 (lim (progn
17191 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17192 (point)))
17193 dd-on str (start 0) m re)
17194 (goto-char pos)
17195 (when dodollar
17196 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17197 re (nth 1 (assoc "$" org-latex-regexps)))
17198 (while (string-match re str start)
17199 (cond
17200 ((= (match-end 0) (length str))
17201 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17202 ((= (match-end 0) (- (length str) 5))
17203 (throw 'exit nil))
17204 (t (setq start (match-end 0))))))
17205 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17206 (goto-char pos)
17207 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17208 (and (match-beginning 2) (throw 'exit nil))
17209 ;; count $$
17210 (while (re-search-backward "\\$\\$" lim t)
17211 (setq dd-on (not dd-on)))
17212 (goto-char pos)
17213 (if dd-on (cons "$$" m))))))
17215 (defun org-inside-latex-macro-p ()
17216 "Is point inside a LaTeX macro or its arguments?"
17217 (save-match-data
17218 (org-in-regexp
17219 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17221 (defun org-try-cdlatex-tab ()
17222 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17223 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17224 - inside a LaTeX fragment, or
17225 - after the first word in a line, where an abbreviation expansion could
17226 insert a LaTeX environment."
17227 (when org-cdlatex-mode
17228 (cond
17229 ;; Before any word on the line: No expansion possible.
17230 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17231 ;; Just after first word on the line: Expand it. Make sure it
17232 ;; cannot happen on headlines, though.
17233 ((save-excursion
17234 (skip-chars-backward "a-zA-Z0-9*")
17235 (skip-chars-backward " \t")
17236 (and (bolp) (not (org-at-heading-p))))
17237 (cdlatex-tab) t)
17238 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17240 (defun org-cdlatex-underscore-caret (&optional arg)
17241 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17242 Revert to the normal definition outside of these fragments."
17243 (interactive "P")
17244 (if (org-inside-LaTeX-fragment-p)
17245 (call-interactively 'cdlatex-sub-superscript)
17246 (let (org-cdlatex-mode)
17247 (call-interactively (key-binding (vector last-input-event))))))
17249 (defun org-cdlatex-math-modify (&optional arg)
17250 "Execute `cdlatex-math-modify' in LaTeX fragments.
17251 Revert to the normal definition outside of these fragments."
17252 (interactive "P")
17253 (if (org-inside-LaTeX-fragment-p)
17254 (call-interactively 'cdlatex-math-modify)
17255 (let (org-cdlatex-mode)
17256 (call-interactively (key-binding (vector last-input-event))))))
17258 (defvar org-latex-fragment-image-overlays nil
17259 "List of overlays carrying the images of latex fragments.")
17260 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17262 (defun org-remove-latex-fragment-image-overlays ()
17263 "Remove all overlays with LaTeX fragment images in current buffer."
17264 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17265 (setq org-latex-fragment-image-overlays nil))
17267 (defun org-preview-latex-fragment (&optional subtree)
17268 "Preview the LaTeX fragment at point, or all locally or globally.
17269 If the cursor is in a LaTeX fragment, create the image and overlay
17270 it over the source code. If there is no fragment at point, display
17271 all fragments in the current text, from one headline to the next. With
17272 prefix SUBTREE, display all fragments in the current subtree. With a
17273 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17274 the cursor is before the first headline,
17275 display all fragments in the buffer.
17276 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17277 (interactive "P")
17278 (unless buffer-file-name
17279 (error "Can't preview LaTeX fragment in a non-file buffer"))
17280 (org-remove-latex-fragment-image-overlays)
17281 (save-excursion
17282 (save-restriction
17283 (let (beg end at msg)
17284 (cond
17285 ((or (equal subtree '(16))
17286 (not (save-excursion
17287 (re-search-backward org-outline-regexp-bol nil t))))
17288 (setq beg (point-min) end (point-max)
17289 msg "Creating images for buffer...%s"))
17290 ((equal subtree '(4))
17291 (org-back-to-heading)
17292 (setq beg (point) end (org-end-of-subtree t)
17293 msg "Creating images for subtree...%s"))
17295 (if (setq at (org-inside-LaTeX-fragment-p))
17296 (goto-char (max (point-min) (- (cdr at) 2)))
17297 (org-back-to-heading))
17298 (setq beg (point) end (progn (outline-next-heading) (point))
17299 msg (if at "Creating image...%s"
17300 "Creating images for entry...%s"))))
17301 (message msg "")
17302 (narrow-to-region beg end)
17303 (goto-char beg)
17304 (org-format-latex
17305 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17306 (file-name-nondirectory
17307 buffer-file-name)))
17308 default-directory 'overlays msg at 'forbuffer
17309 org-latex-create-formula-image-program)
17310 (message msg "done. Use `C-c C-c' to remove images.")))))
17312 (defvar org-latex-regexps
17313 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17314 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17315 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17316 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17317 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17318 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17319 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17320 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17321 "Regular expressions for matching embedded LaTeX.")
17323 (defvar org-export-have-math nil) ;; dynamic scoping
17324 (defun org-format-latex (prefix &optional dir overlays msg at
17325 forbuffer processing-type)
17326 "Replace LaTeX fragments with links to an image, and produce images.
17327 Some of the options can be changed using the variable
17328 `org-format-latex-options'."
17329 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17330 (let* ((prefixnodir (file-name-nondirectory prefix))
17331 (absprefix (expand-file-name prefix dir))
17332 (todir (file-name-directory absprefix))
17333 (opt org-format-latex-options)
17334 (matchers (plist-get opt :matchers))
17335 (re-list org-latex-regexps)
17336 (org-format-latex-header-extra
17337 (plist-get (org-infile-export-plist) :latex-header-extra))
17338 (cnt 0) txt hash link beg end re e checkdir
17339 executables-checked string
17340 m n block-type block linkfile movefile ov)
17341 ;; Check the different regular expressions
17342 (while (setq e (pop re-list))
17343 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17344 block (if block-type "\n\n" ""))
17345 (when (member m matchers)
17346 (goto-char (point-min))
17347 (while (re-search-forward re nil t)
17348 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17349 (not (get-text-property (match-beginning n)
17350 'org-protected))
17351 (or (not overlays)
17352 (not (eq (get-char-property (match-beginning n)
17353 'org-overlay-type)
17354 'org-latex-overlay))))
17355 (setq org-export-have-math t)
17356 (cond
17357 ((eq processing-type 'verbatim)
17358 ;; Leave the text verbatim, just protect it
17359 (add-text-properties (match-beginning n) (match-end n)
17360 '(org-protected t)))
17361 ((eq processing-type 'mathjax)
17362 ;; Prepare for MathJax processing
17363 (setq string (match-string n))
17364 (if (member m '("$" "$1"))
17365 (save-excursion
17366 (delete-region (match-beginning n) (match-end n))
17367 (goto-char (match-beginning n))
17368 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17369 "\\)")
17370 '(org-protected t))))
17371 (add-text-properties (match-beginning n) (match-end n)
17372 '(org-protected t))))
17373 ((or (eq processing-type 'dvipng)
17374 (eq processing-type 'imagemagick))
17375 ;; Process to an image
17376 (setq txt (match-string n)
17377 beg (match-beginning n) end (match-end n)
17378 cnt (1+ cnt))
17379 (let (print-length print-level) ; make sure full list is printed
17380 (setq hash (sha1 (prin1-to-string
17381 (list org-format-latex-header
17382 org-format-latex-header-extra
17383 org-export-latex-default-packages-alist
17384 org-export-latex-packages-alist
17385 org-format-latex-options
17386 forbuffer txt)))
17387 linkfile (format "%s_%s.png" prefix hash)
17388 movefile (format "%s_%s.png" absprefix hash)))
17389 (setq link (concat block "[[file:" linkfile "]]" block))
17390 (if msg (message msg cnt))
17391 (goto-char beg)
17392 (unless checkdir ; make sure the directory exists
17393 (setq checkdir t)
17394 (or (file-directory-p todir) (make-directory todir t)))
17395 (cond
17396 ((eq processing-type 'dvipng)
17397 (unless executables-checked
17398 (org-check-external-command
17399 "latex" "needed to convert LaTeX fragments to images")
17400 (org-check-external-command
17401 "dvipng" "needed to convert LaTeX fragments to images")
17402 (setq executables-checked t))
17403 (unless (file-exists-p movefile)
17404 (org-create-formula-image-with-dvipng
17405 txt movefile opt forbuffer)))
17406 ((eq processing-type 'imagemagick)
17407 (unless executables-checked
17408 (org-check-external-command
17409 "convert" "you need to install imagemagick")
17410 (setq executables-checked t))
17411 (unless (file-exists-p movefile)
17412 (org-create-formula-image-with-imagemagick
17413 txt movefile opt forbuffer))))
17414 (if overlays
17415 (progn
17416 (mapc (lambda (o)
17417 (if (eq (overlay-get o 'org-overlay-type)
17418 'org-latex-overlay)
17419 (delete-overlay o)))
17420 (overlays-in beg end))
17421 (setq ov (make-overlay beg end))
17422 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17423 (if (featurep 'xemacs)
17424 (progn
17425 (overlay-put ov 'invisible t)
17426 (overlay-put
17427 ov 'end-glyph
17428 (make-glyph (vector 'png :file movefile))))
17429 (overlay-put
17430 ov 'display
17431 (list 'image :type 'png :file movefile :ascent 'center)))
17432 (push ov org-latex-fragment-image-overlays)
17433 (goto-char end))
17434 (delete-region beg end)
17435 (insert (org-add-props link
17436 (list 'org-latex-src
17437 (replace-regexp-in-string
17438 "\"" "" txt)
17439 'org-latex-src-embed-type
17440 (if block-type 'paragraph 'character))))))
17441 ((eq processing-type 'mathml)
17442 ;; Process to MathML
17443 (unless executables-checked
17444 (unless (save-match-data (org-format-latex-mathml-available-p))
17445 (error "LaTeX to MathML converter not configured"))
17446 (setq executables-checked t))
17447 (setq txt (match-string n)
17448 beg (match-beginning n) end (match-end n)
17449 cnt (1+ cnt))
17450 (if msg (message msg cnt))
17451 (goto-char beg)
17452 (delete-region beg end)
17453 (insert (org-format-latex-as-mathml
17454 txt block-type prefix dir)))
17456 (error "Unknown conversion type %s for latex fragments"
17457 processing-type)))))))))
17459 (defun org-create-math-formula (latex-frag &optional mathml-file)
17460 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17461 Use `org-latex-to-mathml-convert-command'. If the conversion is
17462 sucessful, return the portion between \"<math...> </math>\"
17463 elements otherwise return nil. When MATHML-FILE is specified,
17464 write the results in to that file. When invoked as an
17465 interactive command, prompt for LATEX-FRAG, with initial value
17466 set to the current active region and echo the results for user
17467 inspection."
17468 (interactive (list (let ((frag (when (org-region-active-p)
17469 (buffer-substring-no-properties
17470 (region-beginning) (region-end)))))
17471 (read-string "LaTeX Fragment: " frag nil frag))))
17472 (unless latex-frag (error "Invalid latex-frag"))
17473 (let* ((tmp-in-file (file-relative-name
17474 (make-temp-name (expand-file-name "ltxmathml-in"))))
17475 (ignore (write-region latex-frag nil tmp-in-file))
17476 (tmp-out-file (file-relative-name
17477 (make-temp-name (expand-file-name "ltxmathml-out"))))
17478 (cmd (format-spec
17479 org-latex-to-mathml-convert-command
17480 `((?j . ,(shell-quote-argument
17481 (expand-file-name org-latex-to-mathml-jar-file)))
17482 (?I . ,(shell-quote-argument tmp-in-file))
17483 (?o . ,(shell-quote-argument tmp-out-file)))))
17484 mathml shell-command-output)
17485 (when (org-called-interactively-p 'any)
17486 (unless (org-format-latex-mathml-available-p)
17487 (error "LaTeX to MathML converter not configured")))
17488 (message "Running %s" cmd)
17489 (setq shell-command-output (shell-command-to-string cmd))
17490 (setq mathml
17491 (when (file-readable-p tmp-out-file)
17492 (with-current-buffer (find-file-noselect tmp-out-file t)
17493 (goto-char (point-min))
17494 (when (re-search-forward
17495 (concat
17496 (regexp-quote
17497 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17498 "\\(.\\|\n\\)*"
17499 (regexp-quote "</math>")) nil t)
17500 (prog1 (match-string 0) (kill-buffer))))))
17501 (cond
17502 (mathml
17503 (setq mathml
17504 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17505 (when mathml-file
17506 (write-region mathml nil mathml-file))
17507 (when (org-called-interactively-p 'any)
17508 (message mathml)))
17509 ((message "LaTeX to MathML conversion failed")
17510 (message shell-command-output)))
17511 (delete-file tmp-in-file)
17512 (when (file-exists-p tmp-out-file)
17513 (delete-file tmp-out-file))
17514 mathml))
17516 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17517 prefix &optional dir)
17518 "Use `org-create-math-formula' but check local cache first."
17519 (let* ((absprefix (expand-file-name prefix dir))
17520 (print-length nil) (print-level nil)
17521 (formula-id (concat
17522 "formula-"
17523 (sha1
17524 (prin1-to-string
17525 (list latex-frag
17526 org-latex-to-mathml-convert-command)))))
17527 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17528 (formula-cache-dir (file-name-directory formula-cache)))
17530 (unless (file-directory-p formula-cache-dir)
17531 (make-directory formula-cache-dir t))
17533 (unless (file-exists-p formula-cache)
17534 (org-create-math-formula latex-frag formula-cache))
17536 (if (file-exists-p formula-cache)
17537 ;; Successful conversion. Return the link to MathML file.
17538 (org-add-props
17539 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17540 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17541 'org-latex-src-embed-type (if latex-frag-type
17542 'paragraph 'character)))
17543 ;; Failed conversion. Return the LaTeX fragment verbatim
17544 (add-text-properties
17545 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17546 latex-frag)))
17548 ;; This function borrows from Ganesh Swami's latex2png.el
17549 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17550 "This calls dvipng."
17551 (require 'org-latex)
17552 (let* ((tmpdir (if (featurep 'xemacs)
17553 (temp-directory)
17554 temporary-file-directory))
17555 (texfilebase (make-temp-name
17556 (expand-file-name "orgtex" tmpdir)))
17557 (texfile (concat texfilebase ".tex"))
17558 (dvifile (concat texfilebase ".dvi"))
17559 (pngfile (concat texfilebase ".png"))
17560 (fnh (if (featurep 'xemacs)
17561 (font-height (face-font 'default))
17562 (face-attribute 'default :height nil)))
17563 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17564 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17565 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17566 "Black"))
17567 (bg (or (plist-get options (if buffer :background :html-background))
17568 "Transparent")))
17569 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17570 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17571 (with-temp-file texfile
17572 (insert (org-splice-latex-header
17573 org-format-latex-header
17574 org-export-latex-default-packages-alist
17575 org-export-latex-packages-alist t
17576 org-format-latex-header-extra))
17577 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17578 (require 'org-latex)
17579 (org-export-latex-fix-inputenc))
17580 (let ((dir default-directory))
17581 (condition-case nil
17582 (progn
17583 (cd tmpdir)
17584 (call-process "latex" nil nil nil texfile))
17585 (error nil))
17586 (cd dir))
17587 (if (not (file-exists-p dvifile))
17588 (progn (message "Failed to create dvi file from %s" texfile) nil)
17589 (condition-case nil
17590 (if (featurep 'xemacs)
17591 (call-process "dvipng" nil nil nil
17592 "-fg" fg "-bg" bg
17593 "-T" "tight"
17594 "-o" pngfile
17595 dvifile)
17596 (call-process "dvipng" nil nil nil
17597 "-fg" fg "-bg" bg
17598 "-D" dpi
17599 ;;"-x" scale "-y" scale
17600 "-T" "tight"
17601 "-o" pngfile
17602 dvifile))
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 '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17612 (if (file-exists-p (concat texfilebase e))
17613 (delete-file (concat texfilebase e))))
17614 pngfile))))
17616 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17617 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17618 "This calls convert, which is included into imagemagick."
17619 (require 'org-latex)
17620 (let* ((tmpdir (if (featurep 'xemacs)
17621 (temp-directory)
17622 temporary-file-directory))
17623 (texfilebase (make-temp-name
17624 (expand-file-name "orgtex" tmpdir)))
17625 (texfile (concat texfilebase ".tex"))
17626 (pdffile (concat texfilebase ".pdf"))
17627 (pngfile (concat texfilebase ".png"))
17628 (fnh (if (featurep 'xemacs)
17629 (font-height (face-font 'default))
17630 (face-attribute 'default :height nil)))
17631 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17632 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17633 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17634 "black"))
17635 (bg (or (plist-get options (if buffer :background :html-background))
17636 "white")))
17637 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17638 (setq fg (org-latex-color-format fg)))
17639 (if (eq bg 'default) (setq bg (org-latex-color :background))
17640 (setq bg (org-latex-color-format
17641 (if (string= bg "Transparent")(setq bg "white")))))
17642 (with-temp-file texfile
17643 (insert (org-splice-latex-header
17644 org-format-latex-header
17645 org-export-latex-default-packages-alist
17646 org-export-latex-packages-alist t
17647 org-format-latex-header-extra))
17648 (insert "\n\\begin{document}\n"
17649 "\\definecolor{fg}{rgb}{" fg "}\n"
17650 "\\definecolor{bg}{rgb}{" bg "}\n"
17651 "\n\\pagecolor{bg}\n"
17652 "\n{\\color{fg}\n"
17653 string
17654 "\n}\n"
17655 "\n\\end{document}\n" )
17656 (require 'org-latex)
17657 (org-export-latex-fix-inputenc))
17658 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17659 (condition-case nil
17660 (progn
17661 (cd tmpdir)
17662 (setq cmds org-latex-to-pdf-process)
17663 (while cmds
17664 (setq latex-frags-cmds (pop cmds))
17665 (if (listp latex-frags-cmds)
17666 (setq cmds nil)
17667 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17668 (while latex-frags-cmds
17669 (setq cmd (pop latex-frags-cmds))
17670 (while (string-match "%b" cmd)
17671 (setq cmd (replace-match
17672 (save-match-data
17673 (shell-quote-argument texfile))
17674 t t cmd)))
17675 (while (string-match "%f" cmd)
17676 (setq cmd (replace-match
17677 (save-match-data
17678 (shell-quote-argument (file-name-nondirectory texfile)))
17679 t t cmd)))
17680 (while (string-match "%o" cmd)
17681 (setq cmd (replace-match
17682 (save-match-data
17683 (shell-quote-argument (file-name-directory texfile)))
17684 t t cmd)))
17685 (setq cmd (split-string cmd))
17686 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17687 (error nil))
17688 (cd dir))
17689 (if (not (file-exists-p pdffile))
17690 (progn (message "Failed to create pdf file from %s" texfile) nil)
17691 (condition-case nil
17692 (if (featurep 'xemacs)
17693 (call-process "convert" nil nil nil
17694 "-density" "96"
17695 "-trim"
17696 "-antialias"
17697 pdffile
17698 "-quality" "100"
17699 ;; "-sharpen" "0x1.0"
17700 pngfile)
17701 (call-process "convert" nil nil nil
17702 "-density" dpi
17703 "-trim"
17704 "-antialias"
17705 pdffile
17706 "-quality" "100"
17707 ; "-sharpen" "0x1.0"
17708 pngfile))
17709 (error nil))
17710 (if (not (file-exists-p pngfile))
17711 (if org-format-latex-signal-error
17712 (error "Failed to create png file from %s" texfile)
17713 (message "Failed to create png file from %s" texfile)
17714 nil)
17715 ;; Use the requested file name and clean up
17716 (copy-file pngfile tofile 'replace)
17717 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17718 (if (file-exists-p (concat texfilebase e))
17719 (delete-file (concat texfilebase e))))
17720 pngfile))))
17722 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17723 "Fill a LaTeX header template TPL.
17724 In the template, the following place holders will be recognized:
17726 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17727 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17728 [PACKAGES] \\usepackage statements for PKG
17729 [NO-PACKAGES] do not include PKG
17730 [EXTRA] the string EXTRA
17731 [NO-EXTRA] do not include EXTRA
17733 For backward compatibility, if both the positive and the negative place
17734 holder is missing, the positive one (without the \"NO-\") will be
17735 assumed to be present at the end of the template.
17736 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17737 EXTRA is a string.
17738 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17739 (let (rpl (end ""))
17740 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17741 (setq rpl (if (or (match-end 1) (not def-pkg))
17742 "" (org-latex-packages-to-string def-pkg snippets-p t))
17743 tpl (replace-match rpl t t tpl))
17744 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17746 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17747 (setq rpl (if (or (match-end 1) (not pkg))
17748 "" (org-latex-packages-to-string pkg snippets-p t))
17749 tpl (replace-match rpl t t tpl))
17750 (if pkg (setq end
17751 (concat end "\n"
17752 (org-latex-packages-to-string pkg snippets-p)))))
17754 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17755 (setq rpl (if (or (match-end 1) (not extra))
17756 "" (concat extra "\n"))
17757 tpl (replace-match rpl t t tpl))
17758 (if (and extra (string-match "\\S-" extra))
17759 (setq end (concat end "\n" extra))))
17761 (if (string-match "\\S-" end)
17762 (concat tpl "\n" end)
17763 tpl)))
17765 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17766 "Turn an alist of packages into a string with the \\usepackage macros."
17767 (setq pkg (mapconcat (lambda(p)
17768 (cond
17769 ((stringp p) p)
17770 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17771 (format "%% Package %s omitted" (cadr p)))
17772 ((equal "" (car p))
17773 (format "\\usepackage{%s}" (cadr p)))
17775 (format "\\usepackage[%s]{%s}"
17776 (car p) (cadr p)))))
17778 "\n"))
17779 (if newline (concat pkg "\n") pkg))
17781 (defun org-dvipng-color (attr)
17782 "Return a RGB color specification for dvipng."
17783 (apply 'format "rgb %s %s %s"
17784 (mapcar 'org-normalize-color
17785 (if (featurep 'xemacs)
17786 (color-rgb-components
17787 (face-property 'default
17788 (cond ((eq attr :foreground) 'foreground)
17789 ((eq attr :background) 'background))))
17790 (color-values (face-attribute 'default attr nil))))))
17792 (defun org-latex-color (attr)
17793 "Return a RGB color for the LaTeX color package."
17794 (apply 'format "%s,%s,%s"
17795 (mapcar 'org-normalize-color
17796 (if (featurep 'xemacs)
17797 (color-rgb-components
17798 (face-property 'default
17799 (cond ((eq attr :foreground) 'foreground)
17800 ((eq attr :background) 'background))))
17801 (color-values (face-attribute 'default attr nil))))))
17803 (defun org-latex-color-format (color-name)
17804 "Convert COLOR-NAME to a RGB color value."
17805 (apply 'format "%s,%s,%s"
17806 (mapcar 'org-normalize-color
17807 (color-values color-name))))
17809 (defun org-normalize-color (value)
17810 "Return string to be used as color value for an RGB component."
17811 (format "%g" (/ value 65535.0)))
17813 ;; Image display
17816 (defvar org-inline-image-overlays nil)
17817 (make-variable-buffer-local 'org-inline-image-overlays)
17819 (defun org-toggle-inline-images (&optional include-linked)
17820 "Toggle the display of inline images.
17821 INCLUDE-LINKED is passed to `org-display-inline-images'."
17822 (interactive "P")
17823 (if org-inline-image-overlays
17824 (progn
17825 (org-remove-inline-images)
17826 (message "Inline image display turned off"))
17827 (org-display-inline-images include-linked)
17828 (if org-inline-image-overlays
17829 (message "%d images displayed inline"
17830 (length org-inline-image-overlays))
17831 (message "No images to display inline"))))
17833 (defun org-redisplay-inline-images ()
17834 "Refresh the display of inline images."
17835 (interactive)
17836 (if (not org-inline-image-overlays)
17837 (org-toggle-inline-images)
17838 (org-toggle-inline-images)
17839 (org-toggle-inline-images)))
17841 (defun org-display-inline-images (&optional include-linked refresh beg end)
17842 "Display inline images.
17843 Normally only links without a description part are inlined, because this
17844 is how it will work for export. When INCLUDE-LINKED is set, also links
17845 with a description part will be inlined. This can be nice for a quick
17846 look at those images, but it does not reflect what exported files will look
17847 like.
17848 When REFRESH is set, refresh existing images between BEG and END.
17849 This will create new image displays only if necessary.
17850 BEG and END default to the buffer boundaries."
17851 (interactive "P")
17852 (unless refresh
17853 (org-remove-inline-images)
17854 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17855 (save-excursion
17856 (save-restriction
17857 (widen)
17858 (setq beg (or beg (point-min)) end (or end (point-max)))
17859 (goto-char beg)
17860 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17861 (substring (org-image-file-name-regexp) 0 -2)
17862 "\\)\\]" (if include-linked "" "\\]")))
17863 old file ov img)
17864 (while (re-search-forward re end t)
17865 (setq old (get-char-property-and-overlay (match-beginning 1)
17866 'org-image-overlay))
17867 (setq file (expand-file-name
17868 (concat (or (match-string 3) "") (match-string 4))))
17869 (when (file-exists-p file)
17870 (if (and (car-safe old) refresh)
17871 (image-refresh (overlay-get (cdr old) 'display))
17872 (setq img (save-match-data (create-image file)))
17873 (when img
17874 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17875 (overlay-put ov 'display img)
17876 (overlay-put ov 'face 'default)
17877 (overlay-put ov 'org-image-overlay t)
17878 (overlay-put ov 'modification-hooks
17879 (list 'org-display-inline-remove-overlay))
17880 (push ov org-inline-image-overlays)))))))))
17882 (define-obsolete-function-alias
17883 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17885 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17886 "Remove inline-display overlay if a corresponding region is modified."
17887 (let ((inhibit-modification-hooks t))
17888 (when (and ov after)
17889 (delete ov org-inline-image-overlays)
17890 (delete-overlay ov))))
17892 (defun org-remove-inline-images ()
17893 "Remove inline display of images."
17894 (interactive)
17895 (mapc 'delete-overlay org-inline-image-overlays)
17896 (setq org-inline-image-overlays nil))
17898 ;;;; Key bindings
17900 ;; Outline functions from `outline-mode-prefix-map'
17901 ;; that can be remapped in Org:
17902 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17903 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17904 (define-key org-mode-map [remap outline-forward-same-level]
17905 'org-forward-heading-same-level)
17906 (define-key org-mode-map [remap outline-backward-same-level]
17907 'org-backward-heading-same-level)
17908 (define-key org-mode-map [remap show-branches]
17909 'org-kill-note-or-show-branches)
17910 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17911 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17912 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17914 ;; Outline functions from `outline-mode-prefix-map' that can not
17915 ;; be remapped in Org:
17917 ;; - the column "key binding" shows whether the Outline function is still
17918 ;; available in Org mode on the same key that it has been bound to in
17919 ;; Outline mode:
17920 ;; - "overridden": key used for a different functionality in Org mode
17921 ;; - else: key still bound to the same Outline function in Org mode
17923 ;; | Outline function | key binding | Org replacement |
17924 ;; |------------------------------------+-------------+-----------------------|
17925 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17926 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17927 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17928 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17929 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17930 ;; | `show-entry' | overridden | no replacement |
17931 ;; | `show-children' | `C-c C-i' | visibility cycling |
17932 ;; | `show-branches' | `C-c C-k' | still same function |
17933 ;; | `show-subtree' | overridden | visibility cycling |
17934 ;; | `show-all' | overridden | no replacement |
17935 ;; | `hide-subtree' | overridden | visibility cycling |
17936 ;; | `hide-body' | overridden | no replacement |
17937 ;; | `hide-entry' | overridden | visibility cycling |
17938 ;; | `hide-leaves' | overridden | no replacement |
17939 ;; | `hide-sublevels' | overridden | no replacement |
17940 ;; | `hide-other' | overridden | no replacement |
17942 ;; Make `C-c C-x' a prefix key
17943 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17945 ;; TAB key with modifiers
17946 (org-defkey org-mode-map "\C-i" 'org-cycle)
17947 (org-defkey org-mode-map [(tab)] 'org-cycle)
17948 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17949 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17950 ;; The following line is necessary under Suse GNU/Linux
17951 (unless (featurep 'xemacs)
17952 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17953 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17954 (define-key org-mode-map [backtab] 'org-shifttab)
17956 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17957 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17958 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17960 ;; Cursor keys with modifiers
17961 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17962 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17963 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17964 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17966 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17967 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17968 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17969 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17971 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17972 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17973 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17974 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17976 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17977 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17978 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17979 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17981 ;; Babel keys
17982 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17983 (mapc (lambda (pair)
17984 (define-key org-babel-map (car pair) (cdr pair)))
17985 org-babel-key-bindings)
17987 ;;; Extra keys for tty access.
17988 ;; We only set them when really needed because otherwise the
17989 ;; menus don't show the simple keys
17991 (when (or org-use-extra-keys
17992 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17993 (not window-system))
17994 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17995 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17996 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17997 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17998 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17999 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18000 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18001 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18002 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18003 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18004 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18005 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18006 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18007 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18008 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18009 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18010 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18011 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18012 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18013 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18014 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18015 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18016 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18017 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18018 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18019 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18020 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18021 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18023 ;; All the other keys
18025 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18026 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18027 (if (boundp 'narrow-map)
18028 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18029 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18030 (if (boundp 'narrow-map)
18031 (org-defkey narrow-map "b" 'org-narrow-to-block)
18032 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18033 (if (boundp 'narrow-map)
18034 (org-defkey narrow-map "e" 'org-narrow-to-element)
18035 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18036 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18037 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18038 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18039 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18040 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18041 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18042 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18043 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18044 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18045 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18046 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18047 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18048 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18049 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18050 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18051 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18052 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18053 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18054 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18055 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18056 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18057 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18058 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18059 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18060 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18061 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18062 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18063 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18064 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18065 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18066 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18067 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18068 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18069 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18070 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18071 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18072 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18073 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18074 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18075 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18076 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18077 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18078 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18079 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18080 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18081 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18082 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18083 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18084 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18085 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18086 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18087 (org-defkey org-mode-map "\C-c^" 'org-sort)
18088 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18089 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18090 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18091 (org-defkey org-mode-map "\C-m" 'org-return)
18092 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18093 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18094 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18095 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18096 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18097 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18098 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18099 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18100 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18101 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18102 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18103 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18104 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18105 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18106 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18107 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18108 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18109 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18110 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18111 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18112 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18113 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18114 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18116 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18117 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18118 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18119 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18121 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18122 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18123 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18124 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18125 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18126 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18127 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18128 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18129 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18130 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18131 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18132 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18133 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18134 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18135 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18136 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18137 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18138 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18139 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18140 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18141 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18142 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18144 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18145 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18146 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18147 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18148 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18150 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18152 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18154 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18155 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18157 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18160 (when (featurep 'xemacs)
18161 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18164 (defconst org-speed-commands-default
18166 ("Outline Navigation")
18167 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18168 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18169 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18170 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18171 ("u" . (org-speed-move-safe 'outline-up-heading))
18172 ("j" . org-goto)
18173 ("g" . (org-refile t))
18174 ("Outline Visibility")
18175 ("c" . org-cycle)
18176 ("C" . org-shifttab)
18177 (" " . org-display-outline-path)
18178 (":" . org-columns)
18179 ("Outline Structure Editing")
18180 ("U" . org-shiftmetaup)
18181 ("D" . org-shiftmetadown)
18182 ("r" . org-metaright)
18183 ("l" . org-metaleft)
18184 ("R" . org-shiftmetaright)
18185 ("L" . org-shiftmetaleft)
18186 ("i" . (progn (forward-char 1) (call-interactively
18187 'org-insert-heading-respect-content)))
18188 ("^" . org-sort)
18189 ("w" . org-refile)
18190 ("a" . org-archive-subtree-default-with-confirmation)
18191 ("." . org-mark-subtree)
18192 ("#" . org-toggle-comment)
18193 ("Clock Commands")
18194 ("I" . org-clock-in)
18195 ("O" . org-clock-out)
18196 ("Meta Data Editing")
18197 ("t" . org-todo)
18198 ("," . (org-priority))
18199 ("0" . (org-priority ?\ ))
18200 ("1" . (org-priority ?A))
18201 ("2" . (org-priority ?B))
18202 ("3" . (org-priority ?C))
18203 (";" . org-set-tags-command)
18204 ("e" . org-set-effort)
18205 ("E" . org-inc-effort)
18206 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18207 (org-entry-put (point) "APPT_WARNTIME" m)))
18208 ("Agenda Views etc")
18209 ("v" . org-agenda)
18210 ("/" . org-sparse-tree)
18211 ("Misc")
18212 ("o" . org-open-at-point)
18213 ("?" . org-speed-command-help)
18214 ("<" . (org-agenda-set-restriction-lock 'subtree))
18215 (">" . (org-agenda-remove-restriction-lock))
18217 "The default speed commands.")
18219 (defun org-print-speed-command (e)
18220 (if (> (length (car e)) 1)
18221 (progn
18222 (princ "\n")
18223 (princ (car e))
18224 (princ "\n")
18225 (princ (make-string (length (car e)) ?-))
18226 (princ "\n"))
18227 (princ (car e))
18228 (princ " ")
18229 (if (symbolp (cdr e))
18230 (princ (symbol-name (cdr e)))
18231 (prin1 (cdr e)))
18232 (princ "\n")))
18234 (defun org-speed-command-help ()
18235 "Show the available speed commands."
18236 (interactive)
18237 (if (not org-use-speed-commands)
18238 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18239 (with-output-to-temp-buffer "*Help*"
18240 (princ "User-defined Speed commands\n===========================\n")
18241 (mapc 'org-print-speed-command org-speed-commands-user)
18242 (princ "\n")
18243 (princ "Built-in Speed commands\n=======================\n")
18244 (mapc 'org-print-speed-command org-speed-commands-default))
18245 (with-current-buffer "*Help*"
18246 (setq truncate-lines t))))
18248 (defun org-speed-move-safe (cmd)
18249 "Execute CMD, but make sure that the cursor always ends up in a headline.
18250 If not, return to the original position and throw an error."
18251 (interactive)
18252 (let ((pos (point)))
18253 (call-interactively cmd)
18254 (unless (and (bolp) (org-at-heading-p))
18255 (goto-char pos)
18256 (error "Boundary reached while executing %s" cmd))))
18258 (defvar org-self-insert-command-undo-counter 0)
18260 (defvar org-table-auto-blank-field) ; defined in org-table.el
18261 (defvar org-speed-command nil)
18263 (define-obsolete-function-alias
18264 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18266 (defun org-speed-command-activate (keys)
18267 "Hook for activating single-letter speed commands.
18268 `org-speed-commands-default' specifies a minimal command set.
18269 Use `org-speed-commands-user' for further customization."
18270 (when (or (and (bolp) (looking-at org-outline-regexp))
18271 (and (functionp org-use-speed-commands)
18272 (funcall org-use-speed-commands)))
18273 (cdr (assoc keys (append org-speed-commands-user
18274 org-speed-commands-default)))))
18276 (define-obsolete-function-alias
18277 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18279 (defun org-babel-speed-command-activate (keys)
18280 "Hook for activating single-letter code block commands."
18281 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18282 (cdr (assoc keys org-babel-key-bindings))))
18284 (defcustom org-speed-command-hook
18285 '(org-speed-command-default-hook org-babel-speed-command-hook)
18286 "Hook for activating speed commands at strategic locations.
18287 Hook functions are called in sequence until a valid handler is
18288 found.
18290 Each hook takes a single argument, a user-pressed command key
18291 which is also a `self-insert-command' from the global map.
18293 Within the hook, examine the cursor position and the command key
18294 and return nil or a valid handler as appropriate. Handler could
18295 be one of an interactive command, a function, or a form.
18297 Set `org-use-speed-commands' to non-nil value to enable this
18298 hook. The default setting is `org-speed-command-activate'."
18299 :group 'org-structure
18300 :version "24.1"
18301 :type 'hook)
18303 (defun org-self-insert-command (N)
18304 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18305 If the cursor is in a table looking at whitespace, the whitespace is
18306 overwritten, and the table is not marked as requiring realignment."
18307 (interactive "p")
18308 (org-check-before-invisible-edit 'insert)
18309 (cond
18310 ((and org-use-speed-commands
18311 (setq org-speed-command
18312 (run-hook-with-args-until-success
18313 'org-speed-command-hook (this-command-keys))))
18314 (cond
18315 ((commandp org-speed-command)
18316 (setq this-command org-speed-command)
18317 (call-interactively org-speed-command))
18318 ((functionp org-speed-command)
18319 (funcall org-speed-command))
18320 ((and org-speed-command (listp org-speed-command))
18321 (eval org-speed-command))
18322 (t (let (org-use-speed-commands)
18323 (call-interactively 'org-self-insert-command)))))
18324 ((and
18325 (org-table-p)
18326 (progn
18327 ;; check if we blank the field, and if that triggers align
18328 (and (featurep 'org-table) org-table-auto-blank-field
18329 (member last-command
18330 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18331 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18332 ;; got extra space, this field does not determine column width
18333 (let (org-table-may-need-update) (org-table-blank-field))
18334 ;; no extra space, this field may determine column width
18335 (org-table-blank-field)))
18337 (eq N 1)
18338 (looking-at "[^|\n]* |"))
18339 (let (org-table-may-need-update)
18340 (goto-char (1- (match-end 0)))
18341 (backward-delete-char 1)
18342 (goto-char (match-beginning 0))
18343 (self-insert-command N)))
18345 (setq org-table-may-need-update t)
18346 (self-insert-command N)
18347 (org-fix-tags-on-the-fly)
18348 (if org-self-insert-cluster-for-undo
18349 (if (not (eq last-command 'org-self-insert-command))
18350 (setq org-self-insert-command-undo-counter 1)
18351 (if (>= org-self-insert-command-undo-counter 20)
18352 (setq org-self-insert-command-undo-counter 1)
18353 (and (> org-self-insert-command-undo-counter 0)
18354 buffer-undo-list (listp buffer-undo-list)
18355 (not (cadr buffer-undo-list)) ; remove nil entry
18356 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18357 (setq org-self-insert-command-undo-counter
18358 (1+ org-self-insert-command-undo-counter))))))))
18360 (defun org-check-before-invisible-edit (kind)
18361 "Check is editing if kind KIND would be dangerous with invisible text around.
18362 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18363 ;; First, try to get out of here as quickly as possible, to reduce overhead
18364 (if (and org-catch-invisible-edits
18365 (or (not (boundp 'visible-mode)) (not visible-mode))
18366 (or (get-char-property (point) 'invisible)
18367 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18368 ;; OK, we need to take a closer look
18369 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18370 (invisible-before-point (if (bobp) nil (get-char-property
18371 (1- (point)) 'invisible)))
18372 (border-and-ok-direction
18374 ;; Check if we are acting predictably before invisible text
18375 (and invisible-at-point (not invisible-before-point)
18376 (memq kind '(insert delete-backward)))
18377 ;; Check if we are acting predictably after invisible text
18378 ;; This works not well, and I have turned it off. It seems
18379 ;; better to always show and stop after invisible text.
18380 ;; (and (not invisible-at-point) invisible-before-point
18381 ;; (memq kind '(insert delete)))
18383 (when (or (memq invisible-at-point '(outline org-hide-block t))
18384 (memq invisible-before-point '(outline org-hide-block t)))
18385 (if (eq org-catch-invisible-edits 'error)
18386 (error "Editing in invisible areas is prohibited - make visible first"))
18387 (if (and org-custom-properties-overlays
18388 (y-or-n-p "Display invisible properties in this buffer? "))
18389 (org-toggle-custom-properties-visibility)
18390 ;; Make the area visible
18391 (save-excursion
18392 (if invisible-before-point
18393 (goto-char (previous-single-char-property-change
18394 (point) 'invisible)))
18395 (org-cycle))
18396 (cond
18397 ((eq org-catch-invisible-edits 'show)
18398 ;; That's it, we do the edit after showing
18399 (message
18400 "Unfolding invisible region around point before editing")
18401 (sit-for 1))
18402 ((and (eq org-catch-invisible-edits 'smart)
18403 border-and-ok-direction)
18404 (message "Unfolding invisible region around point before editing"))
18406 ;; Don't do the edit, make the user repeat it in full visibility
18407 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18409 (defun org-fix-tags-on-the-fly ()
18410 (when (and (equal (char-after (point-at-bol)) ?*)
18411 (org-at-heading-p))
18412 (org-align-tags-here org-tags-column)))
18414 (defun org-delete-backward-char (N)
18415 "Like `delete-backward-char', insert whitespace at field end in tables.
18416 When deleting backwards, in tables this function will insert whitespace in
18417 front of the next \"|\" separator, to keep the table aligned. The table will
18418 still be marked for re-alignment if the field did fill the entire column,
18419 because, in this case the deletion might narrow the column."
18420 (interactive "p")
18421 (org-check-before-invisible-edit 'delete-backward)
18422 (if (and (org-table-p)
18423 (eq N 1)
18424 (string-match "|" (buffer-substring (point-at-bol) (point)))
18425 (looking-at ".*?|"))
18426 (let ((pos (point))
18427 (noalign (looking-at "[^|\n\r]* |"))
18428 (c org-table-may-need-update))
18429 (backward-delete-char N)
18430 (if (not overwrite-mode)
18431 (progn
18432 (skip-chars-forward "^|")
18433 (insert " ")
18434 (goto-char (1- pos))))
18435 ;; noalign: if there were two spaces at the end, this field
18436 ;; does not determine the width of the column.
18437 (if noalign (setq org-table-may-need-update c)))
18438 (backward-delete-char N)
18439 (org-fix-tags-on-the-fly)))
18441 (defun org-delete-char (N)
18442 "Like `delete-char', but insert whitespace at field end in tables.
18443 When deleting characters, in tables this function will insert whitespace in
18444 front of the next \"|\" separator, to keep the table aligned. The table will
18445 still be marked for re-alignment if the field did fill the entire column,
18446 because, in this case the deletion might narrow the column."
18447 (interactive "p")
18448 (org-check-before-invisible-edit 'delete)
18449 (if (and (org-table-p)
18450 (not (bolp))
18451 (not (= (char-after) ?|))
18452 (eq N 1))
18453 (if (looking-at ".*?|")
18454 (let ((pos (point))
18455 (noalign (looking-at "[^|\n\r]* |"))
18456 (c org-table-may-need-update))
18457 (replace-match (concat
18458 (substring (match-string 0) 1 -1)
18459 " |"))
18460 (goto-char pos)
18461 ;; noalign: if there were two spaces at the end, this field
18462 ;; does not determine the width of the column.
18463 (if noalign (setq org-table-may-need-update c)))
18464 (delete-char N))
18465 (delete-char N)
18466 (org-fix-tags-on-the-fly)))
18468 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18469 (put 'org-self-insert-command 'delete-selection t)
18470 (put 'orgtbl-self-insert-command 'delete-selection t)
18471 (put 'org-delete-char 'delete-selection 'supersede)
18472 (put 'org-delete-backward-char 'delete-selection 'supersede)
18473 (put 'org-yank 'delete-selection 'yank)
18475 ;; Make `flyspell-mode' delay after some commands
18476 (put 'org-self-insert-command 'flyspell-delayed t)
18477 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18478 (put 'org-delete-char 'flyspell-delayed t)
18479 (put 'org-delete-backward-char 'flyspell-delayed t)
18481 ;; Make pabbrev-mode expand after org-mode commands
18482 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18483 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18485 ;; How to do this: Measure non-white length of current string
18486 ;; If equal to column width, we should realign.
18488 (defun org-remap (map &rest commands)
18489 "In MAP, remap the functions given in COMMANDS.
18490 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18491 (let (new old)
18492 (while commands
18493 (setq old (pop commands) new (pop commands))
18494 (if (fboundp 'command-remapping)
18495 (org-defkey map (vector 'remap old) new)
18496 (substitute-key-definition old new map global-map)))))
18498 (when (eq org-enable-table-editor 'optimized)
18499 ;; If the user wants maximum table support, we need to hijack
18500 ;; some standard editing functions
18501 (org-remap org-mode-map
18502 'self-insert-command 'org-self-insert-command
18503 'delete-char 'org-delete-char
18504 'delete-backward-char 'org-delete-backward-char)
18505 (org-defkey org-mode-map "|" 'org-force-self-insert))
18507 (defvar org-ctrl-c-ctrl-c-hook nil
18508 "Hook for functions attaching themselves to `C-c C-c'.
18510 This can be used to add additional functionality to the C-c C-c
18511 key which executes context-dependent commands. This hook is run
18512 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18513 run after the last test.
18515 Each function will be called with no arguments. The function
18516 must check if the context is appropriate for it to act. If yes,
18517 it should do its thing and then return a non-nil value. If the
18518 context is wrong, just do nothing and return nil.")
18520 (defvar org-ctrl-c-ctrl-c-final-hook nil
18521 "Hook for functions attaching themselves to `C-c C-c'.
18523 This can be used to add additional functionality to the C-c C-c
18524 key which executes context-dependent commands. This hook is run
18525 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18526 before the first test.
18528 Each function will be called with no arguments. The function
18529 must check if the context is appropriate for it to act. If yes,
18530 it should do its thing and then return a non-nil value. If the
18531 context is wrong, just do nothing and return nil.")
18533 (defvar org-tab-first-hook nil
18534 "Hook for functions to attach themselves to TAB.
18535 See `org-ctrl-c-ctrl-c-hook' for more information.
18536 This hook runs as the first action when TAB is pressed, even before
18537 `org-cycle' messes around with the `outline-regexp' to cater for
18538 inline tasks and plain list item folding.
18539 If any function in this hook returns t, any other actions that
18540 would have been caused by TAB (such as table field motion or visibility
18541 cycling) will not occur.")
18543 (defvar org-tab-after-check-for-table-hook nil
18544 "Hook for functions to attach themselves to TAB.
18545 See `org-ctrl-c-ctrl-c-hook' for more information.
18546 This hook runs after it has been established that the cursor is not in a
18547 table, but before checking if the cursor is in a headline or if global cycling
18548 should be done.
18549 If any function in this hook returns t, not other actions like visibility
18550 cycling will be done.")
18552 (defvar org-tab-after-check-for-cycling-hook nil
18553 "Hook for functions to attach themselves to TAB.
18554 See `org-ctrl-c-ctrl-c-hook' for more information.
18555 This hook runs after it has been established that not table field motion and
18556 not visibility should be done because of current context. This is probably
18557 the place where a package like yasnippets can hook in.")
18559 (defvar org-tab-before-tab-emulation-hook nil
18560 "Hook for functions to attach themselves to TAB.
18561 See `org-ctrl-c-ctrl-c-hook' for more information.
18562 This hook runs after every other options for TAB have been exhausted, but
18563 before indentation and \t insertion takes place.")
18565 (defvar org-metaleft-hook nil
18566 "Hook for functions attaching themselves to `M-left'.
18567 See `org-ctrl-c-ctrl-c-hook' for more information.")
18568 (defvar org-metaright-hook nil
18569 "Hook for functions attaching themselves to `M-right'.
18570 See `org-ctrl-c-ctrl-c-hook' for more information.")
18571 (defvar org-metaup-hook nil
18572 "Hook for functions attaching themselves to `M-up'.
18573 See `org-ctrl-c-ctrl-c-hook' for more information.")
18574 (defvar org-metadown-hook nil
18575 "Hook for functions attaching themselves to `M-down'.
18576 See `org-ctrl-c-ctrl-c-hook' for more information.")
18577 (defvar org-shiftmetaleft-hook nil
18578 "Hook for functions attaching themselves to `M-S-left'.
18579 See `org-ctrl-c-ctrl-c-hook' for more information.")
18580 (defvar org-shiftmetaright-hook nil
18581 "Hook for functions attaching themselves to `M-S-right'.
18582 See `org-ctrl-c-ctrl-c-hook' for more information.")
18583 (defvar org-shiftmetaup-hook nil
18584 "Hook for functions attaching themselves to `M-S-up'.
18585 See `org-ctrl-c-ctrl-c-hook' for more information.")
18586 (defvar org-shiftmetadown-hook nil
18587 "Hook for functions attaching themselves to `M-S-down'.
18588 See `org-ctrl-c-ctrl-c-hook' for more information.")
18589 (defvar org-metareturn-hook nil
18590 "Hook for functions attaching themselves to `M-RET'.
18591 See `org-ctrl-c-ctrl-c-hook' for more information.")
18592 (defvar org-shiftup-hook nil
18593 "Hook for functions attaching themselves to `S-up'.
18594 See `org-ctrl-c-ctrl-c-hook' for more information.")
18595 (defvar org-shiftup-final-hook nil
18596 "Hook for functions attaching themselves to `S-up'.
18597 This one runs after all other options except shift-select have been excluded.
18598 See `org-ctrl-c-ctrl-c-hook' for more information.")
18599 (defvar org-shiftdown-hook nil
18600 "Hook for functions attaching themselves to `S-down'.
18601 See `org-ctrl-c-ctrl-c-hook' for more information.")
18602 (defvar org-shiftdown-final-hook nil
18603 "Hook for functions attaching themselves to `S-down'.
18604 This one runs after all other options except shift-select have been excluded.
18605 See `org-ctrl-c-ctrl-c-hook' for more information.")
18606 (defvar org-shiftleft-hook nil
18607 "Hook for functions attaching themselves to `S-left'.
18608 See `org-ctrl-c-ctrl-c-hook' for more information.")
18609 (defvar org-shiftleft-final-hook nil
18610 "Hook for functions attaching themselves to `S-left'.
18611 This one runs after all other options except shift-select have been excluded.
18612 See `org-ctrl-c-ctrl-c-hook' for more information.")
18613 (defvar org-shiftright-hook nil
18614 "Hook for functions attaching themselves to `S-right'.
18615 See `org-ctrl-c-ctrl-c-hook' for more information.")
18616 (defvar org-shiftright-final-hook nil
18617 "Hook for functions attaching themselves to `S-right'.
18618 This one runs after all other options except shift-select have been excluded.
18619 See `org-ctrl-c-ctrl-c-hook' for more information.")
18621 (defun org-modifier-cursor-error ()
18622 "Throw an error, a modified cursor command was applied in wrong context."
18623 (error "This command is active in special context like tables, headlines or items"))
18625 (defun org-shiftselect-error ()
18626 "Throw an error because Shift-Cursor command was applied in wrong context."
18627 (if (and (boundp 'shift-select-mode) shift-select-mode)
18628 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18629 (error "This command works only in special context like headlines or timestamps")))
18631 (defun org-call-for-shift-select (cmd)
18632 (let ((this-command-keys-shift-translated t))
18633 (call-interactively cmd)))
18635 (defun org-shifttab (&optional arg)
18636 "Global visibility cycling or move to previous table field.
18637 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18638 on context.
18639 See the individual commands for more information."
18640 (interactive "P")
18641 (cond
18642 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18643 ((integerp arg)
18644 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18645 (message "Content view to level: %d" arg)
18646 (org-content (prefix-numeric-value arg2))
18647 (setq org-cycle-global-status 'overview)))
18648 (t (call-interactively 'org-global-cycle))))
18650 (defun org-shiftmetaleft ()
18651 "Promote subtree or delete table column.
18652 Calls `org-promote-subtree', `org-outdent-item-tree', or
18653 `org-table-delete-column', depending on context. See the
18654 individual commands for more information."
18655 (interactive)
18656 (cond
18657 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18658 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18659 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18660 ((if (not (org-region-active-p)) (org-at-item-p)
18661 (save-excursion (goto-char (region-beginning))
18662 (org-at-item-p)))
18663 (call-interactively 'org-outdent-item-tree))
18664 (t (org-modifier-cursor-error))))
18666 (defun org-shiftmetaright ()
18667 "Demote subtree or insert table column.
18668 Calls `org-demote-subtree', `org-indent-item-tree', or
18669 `org-table-insert-column', depending on context. See the
18670 individual commands for more information."
18671 (interactive)
18672 (cond
18673 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18674 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18675 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18676 ((if (not (org-region-active-p)) (org-at-item-p)
18677 (save-excursion (goto-char (region-beginning))
18678 (org-at-item-p)))
18679 (call-interactively 'org-indent-item-tree))
18680 (t (org-modifier-cursor-error))))
18682 (defun org-shiftmetaup (&optional arg)
18683 "Move subtree up or kill table row.
18684 Calls `org-move-subtree-up' or `org-table-kill-row' or
18685 `org-move-item-up' or `org-timestamp-up', depending on context.
18686 See the individual commands for more information."
18687 (interactive "P")
18688 (cond
18689 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18690 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18691 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18692 ((org-at-item-p) (call-interactively 'org-move-item-up))
18693 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18694 (call-interactively 'org-timestamp-up)))
18695 (t (org-modifier-cursor-error))))
18697 (defun org-shiftmetadown (&optional arg)
18698 "Move subtree down or insert table row.
18699 Calls `org-move-subtree-down' or `org-table-insert-row' or
18700 `org-move-item-down' or `org-timestamp-up', depending on context.
18701 See the individual commands for more information."
18702 (interactive "P")
18703 (cond
18704 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18705 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18706 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18707 ((org-at-item-p) (call-interactively 'org-move-item-down))
18708 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18709 (call-interactively 'org-timestamp-down)))
18710 (t (org-modifier-cursor-error))))
18712 (defsubst org-hidden-tree-error ()
18713 (error
18714 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18716 (defun org-metaleft (&optional arg)
18717 "Promote heading or move table column to left.
18718 Calls `org-do-promote' or `org-table-move-column', depending on context.
18719 With no specific context, calls the Emacs default `backward-word'.
18720 See the individual commands for more information."
18721 (interactive "P")
18722 (cond
18723 ((run-hook-with-args-until-success 'org-metaleft-hook))
18724 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18725 ((org-with-limited-levels
18726 (or (org-at-heading-p)
18727 (and (org-region-active-p)
18728 (save-excursion
18729 (goto-char (region-beginning))
18730 (org-at-heading-p)))))
18731 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18732 (call-interactively 'org-do-promote))
18733 ;; At an inline task.
18734 ((org-at-heading-p)
18735 (call-interactively 'org-inlinetask-promote))
18736 ((or (org-at-item-p)
18737 (and (org-region-active-p)
18738 (save-excursion
18739 (goto-char (region-beginning))
18740 (org-at-item-p))))
18741 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18742 (call-interactively 'org-outdent-item))
18743 (t (call-interactively 'backward-word))))
18745 (defun org-metaright (&optional arg)
18746 "Demote a subtree, a list item or move table column to right.
18747 In front of a drawer or a block keyword, indent it correctly.
18748 With no specific context, calls the Emacs default `forward-word'.
18749 See the individual commands for more information."
18750 (interactive "P")
18751 (cond
18752 ((run-hook-with-args-until-success 'org-metaright-hook))
18753 ((org-at-table-p) (call-interactively 'org-table-move-column))
18754 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18755 ((org-at-block-p) (call-interactively 'org-indent-block))
18756 ((org-with-limited-levels
18757 (or (org-at-heading-p)
18758 (and (org-region-active-p)
18759 (save-excursion
18760 (goto-char (region-beginning))
18761 (org-at-heading-p)))))
18762 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18763 (call-interactively 'org-do-demote))
18764 ;; At an inline task.
18765 ((org-at-heading-p)
18766 (call-interactively 'org-inlinetask-demote))
18767 ((or (org-at-item-p)
18768 (and (org-region-active-p)
18769 (save-excursion
18770 (goto-char (region-beginning))
18771 (org-at-item-p))))
18772 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18773 (call-interactively 'org-indent-item))
18774 (t (call-interactively 'forward-word))))
18776 (defun org-check-for-hidden (what)
18777 "Check if there are hidden headlines/items in the current visual line.
18778 WHAT can be either `headlines' or `items'. If the current line is
18779 an outline or item heading and it has a folded subtree below it,
18780 this function returns t, nil otherwise."
18781 (let ((re (cond
18782 ((eq what 'headlines) org-outline-regexp-bol)
18783 ((eq what 'items) (org-item-beginning-re))
18784 (t (error "This should not happen"))))
18785 beg end)
18786 (save-excursion
18787 (catch 'exit
18788 (unless (org-region-active-p)
18789 (setq beg (point-at-bol))
18790 (beginning-of-line 2)
18791 (while (and (not (eobp)) ;; this is like `next-line'
18792 (get-char-property (1- (point)) 'invisible))
18793 (beginning-of-line 2))
18794 (setq end (point))
18795 (goto-char beg)
18796 (goto-char (point-at-eol))
18797 (setq end (max end (point)))
18798 (while (re-search-forward re end t)
18799 (if (get-char-property (match-beginning 0) 'invisible)
18800 (throw 'exit t))))
18801 nil))))
18803 (autoload 'org-element-at-point "org-element")
18805 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18806 (declare-function org-element-type "org-element" (element))
18807 (declare-function org-element-context "org-element" ())
18808 (declare-function org-element-contents "org-element" (element))
18809 (declare-function org-element-property "org-element" (property element))
18810 (declare-function org-element-paragraph-parser "org-element" (limit))
18811 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18812 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18813 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18814 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18815 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18817 (defun org-metaup (&optional arg)
18818 "Move subtree up or move table row up.
18819 Calls `org-move-subtree-up' or `org-table-move-row' or
18820 `org-move-item-up', depending on context. See the individual commands
18821 for more information."
18822 (interactive "P")
18823 (cond
18824 ((run-hook-with-args-until-success 'org-metaup-hook))
18825 ((org-region-active-p)
18826 (let* ((a (min (region-beginning) (region-end)))
18827 (b (1- (max (region-beginning) (region-end))))
18828 (c (save-excursion (goto-char a)
18829 (move-beginning-of-line 0)))
18830 (d (save-excursion (goto-char a)
18831 (move-end-of-line 0) (point))))
18832 (transpose-regions a b c d)
18833 (goto-char c)))
18834 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18835 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18836 ((org-at-item-p) (call-interactively 'org-move-item-up))
18837 (t (org-drag-element-backward))))
18839 (defun org-metadown (&optional arg)
18840 "Move subtree down or move table row down.
18841 Calls `org-move-subtree-down' or `org-table-move-row' or
18842 `org-move-item-down', depending on context. See the individual
18843 commands for more information."
18844 (interactive "P")
18845 (cond
18846 ((run-hook-with-args-until-success 'org-metadown-hook))
18847 ((org-region-active-p)
18848 (let* ((a (min (region-beginning) (region-end)))
18849 (b (max (region-beginning) (region-end)))
18850 (c (save-excursion (goto-char b)
18851 (move-beginning-of-line 1)))
18852 (d (save-excursion (goto-char b)
18853 (move-end-of-line 1) (1+ (point)))))
18854 (transpose-regions a b c d)
18855 (goto-char d)))
18856 ((org-at-table-p) (call-interactively 'org-table-move-row))
18857 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18858 ((org-at-item-p) (call-interactively 'org-move-item-down))
18859 (t (org-drag-element-forward))))
18861 (defun org-shiftup (&optional arg)
18862 "Increase item in timestamp or increase priority of current headline.
18863 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18864 depending on context. See the individual commands for more information."
18865 (interactive "P")
18866 (cond
18867 ((run-hook-with-args-until-success 'org-shiftup-hook))
18868 ((and org-support-shift-select (org-region-active-p))
18869 (org-call-for-shift-select 'previous-line))
18870 ((org-at-timestamp-p t)
18871 (call-interactively (if org-edit-timestamp-down-means-later
18872 'org-timestamp-down 'org-timestamp-up)))
18873 ((and (not (eq org-support-shift-select 'always))
18874 org-enable-priority-commands
18875 (org-at-heading-p))
18876 (call-interactively 'org-priority-up))
18877 ((and (not org-support-shift-select) (org-at-item-p))
18878 (call-interactively 'org-previous-item))
18879 ((org-clocktable-try-shift 'up arg))
18880 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18881 (org-support-shift-select
18882 (org-call-for-shift-select 'previous-line))
18883 (t (org-shiftselect-error))))
18885 (defun org-shiftdown (&optional arg)
18886 "Decrease item in timestamp or decrease priority of current headline.
18887 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18888 depending on context. See the individual commands for more information."
18889 (interactive "P")
18890 (cond
18891 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18892 ((and org-support-shift-select (org-region-active-p))
18893 (org-call-for-shift-select 'next-line))
18894 ((org-at-timestamp-p t)
18895 (call-interactively (if org-edit-timestamp-down-means-later
18896 'org-timestamp-up 'org-timestamp-down)))
18897 ((and (not (eq org-support-shift-select 'always))
18898 org-enable-priority-commands
18899 (org-at-heading-p))
18900 (call-interactively 'org-priority-down))
18901 ((and (not org-support-shift-select) (org-at-item-p))
18902 (call-interactively 'org-next-item))
18903 ((org-clocktable-try-shift 'down arg))
18904 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18905 (org-support-shift-select
18906 (org-call-for-shift-select 'next-line))
18907 (t (org-shiftselect-error))))
18909 (defun org-shiftright (&optional arg)
18910 "Cycle the thing at point or in the current line, depending on context.
18911 Depending on context, this does one of the following:
18913 - switch a timestamp at point one day into the future
18914 - on a headline, switch to the next TODO keyword.
18915 - on an item, switch entire list to the next bullet type
18916 - on a property line, switch to the next allowed value
18917 - on a clocktable definition line, move time block into the future"
18918 (interactive "P")
18919 (cond
18920 ((run-hook-with-args-until-success 'org-shiftright-hook))
18921 ((and org-support-shift-select (org-region-active-p))
18922 (org-call-for-shift-select 'forward-char))
18923 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18924 ((and (not (eq org-support-shift-select 'always))
18925 (org-at-heading-p))
18926 (let ((org-inhibit-logging
18927 (not org-treat-S-cursor-todo-selection-as-state-change))
18928 (org-inhibit-blocking
18929 (not org-treat-S-cursor-todo-selection-as-state-change)))
18930 (org-call-with-arg 'org-todo 'right)))
18931 ((or (and org-support-shift-select
18932 (not (eq org-support-shift-select 'always))
18933 (org-at-item-bullet-p))
18934 (and (not org-support-shift-select) (org-at-item-p)))
18935 (org-call-with-arg 'org-cycle-list-bullet nil))
18936 ((and (not (eq org-support-shift-select 'always))
18937 (org-at-property-p))
18938 (call-interactively 'org-property-next-allowed-value))
18939 ((org-clocktable-try-shift 'right arg))
18940 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18941 (org-support-shift-select
18942 (org-call-for-shift-select 'forward-char))
18943 (t (org-shiftselect-error))))
18945 (defun org-shiftleft (&optional arg)
18946 "Cycle the thing at point or in the current line, depending on context.
18947 Depending on context, this does one of the following:
18949 - switch a timestamp at point one day into the past
18950 - on a headline, switch to the previous TODO keyword.
18951 - on an item, switch entire list to the previous bullet type
18952 - on a property line, switch to the previous allowed value
18953 - on a clocktable definition line, move time block into the past"
18954 (interactive "P")
18955 (cond
18956 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18957 ((and org-support-shift-select (org-region-active-p))
18958 (org-call-for-shift-select 'backward-char))
18959 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18960 ((and (not (eq org-support-shift-select 'always))
18961 (org-at-heading-p))
18962 (let ((org-inhibit-logging
18963 (not org-treat-S-cursor-todo-selection-as-state-change))
18964 (org-inhibit-blocking
18965 (not org-treat-S-cursor-todo-selection-as-state-change)))
18966 (org-call-with-arg 'org-todo 'left)))
18967 ((or (and org-support-shift-select
18968 (not (eq org-support-shift-select 'always))
18969 (org-at-item-bullet-p))
18970 (and (not org-support-shift-select) (org-at-item-p)))
18971 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18972 ((and (not (eq org-support-shift-select 'always))
18973 (org-at-property-p))
18974 (call-interactively 'org-property-previous-allowed-value))
18975 ((org-clocktable-try-shift 'left arg))
18976 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18977 (org-support-shift-select
18978 (org-call-for-shift-select 'backward-char))
18979 (t (org-shiftselect-error))))
18981 (defun org-shiftcontrolright ()
18982 "Switch to next TODO set."
18983 (interactive)
18984 (cond
18985 ((and org-support-shift-select (org-region-active-p))
18986 (org-call-for-shift-select 'forward-word))
18987 ((and (not (eq org-support-shift-select 'always))
18988 (org-at-heading-p))
18989 (org-call-with-arg 'org-todo 'nextset))
18990 (org-support-shift-select
18991 (org-call-for-shift-select 'forward-word))
18992 (t (org-shiftselect-error))))
18994 (defun org-shiftcontrolleft ()
18995 "Switch to previous TODO set."
18996 (interactive)
18997 (cond
18998 ((and org-support-shift-select (org-region-active-p))
18999 (org-call-for-shift-select 'backward-word))
19000 ((and (not (eq org-support-shift-select 'always))
19001 (org-at-heading-p))
19002 (org-call-with-arg 'org-todo 'previousset))
19003 (org-support-shift-select
19004 (org-call-for-shift-select 'backward-word))
19005 (t (org-shiftselect-error))))
19007 (defun org-shiftcontrolup ()
19008 "Change timestamps synchronously up in CLOCK log lines."
19009 (interactive)
19010 (cond ((and (not org-support-shift-select)
19011 (org-at-clock-log-p)
19012 (org-at-timestamp-p t))
19013 (org-clock-timestamps-up))
19014 (t (org-shiftselect-error))))
19016 (defun org-shiftcontroldown ()
19017 "Change timestamps synchronously down in CLOCK log lines."
19018 (interactive)
19019 (cond ((and (not org-support-shift-select)
19020 (org-at-clock-log-p)
19021 (org-at-timestamp-p t))
19022 (org-clock-timestamps-down))
19023 (t (org-shiftselect-error))))
19025 (defun org-ctrl-c-ret ()
19026 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19027 (interactive)
19028 (cond
19029 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19030 (t (call-interactively 'org-insert-heading))))
19032 (defun org-find-visible ()
19033 (let ((s (point)))
19034 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19035 (get-char-property s 'invisible)))
19037 (defun org-find-invisible ()
19038 (let ((s (point)))
19039 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19040 (not (get-char-property s 'invisible))))
19043 (defun org-copy-visible (beg end)
19044 "Copy the visible parts of the region."
19045 (interactive "r")
19046 (let (snippets s)
19047 (save-excursion
19048 (save-restriction
19049 (narrow-to-region beg end)
19050 (setq s (goto-char (point-min)))
19051 (while (not (= (point) (point-max)))
19052 (goto-char (org-find-invisible))
19053 (push (buffer-substring s (point)) snippets)
19054 (setq s (goto-char (org-find-visible))))))
19055 (kill-new (apply 'concat (nreverse snippets)))))
19057 (defun org-copy-special ()
19058 "Copy region in table or copy current subtree.
19059 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19060 See the individual commands for more information."
19061 (interactive)
19062 (call-interactively
19063 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19065 (defun org-cut-special ()
19066 "Cut region in table or cut current subtree.
19067 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19068 See the individual commands for more information."
19069 (interactive)
19070 (call-interactively
19071 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19073 (defun org-paste-special (arg)
19074 "Paste rectangular region into table, or past subtree relative to level.
19075 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19076 See the individual commands for more information."
19077 (interactive "P")
19078 (if (org-at-table-p)
19079 (org-table-paste-rectangle)
19080 (org-paste-subtree arg)))
19082 (defun org-edit-special (&optional arg)
19083 "Call a special editor for the stuff at point.
19084 When at a table, call the formula editor with `org-table-edit-formulas'.
19085 When at the first line of an src example, call `org-edit-src-code'.
19086 When in an #+include line, visit the include file. Otherwise call
19087 `ffap' to visit the file at point."
19088 (interactive)
19089 ;; possibly prep session before editing source
19090 (when arg
19091 (let* ((info (org-babel-get-src-block-info))
19092 (lang (nth 0 info))
19093 (params (nth 2 info))
19094 (session (cdr (assoc :session params))))
19095 (when (and info session) ;; we are in a source-code block with a session
19096 (funcall
19097 (intern (concat "org-babel-prep-session:" lang)) session params))))
19098 (cond ;; proceed with `org-edit-special'
19099 ((save-excursion
19100 (beginning-of-line 1)
19101 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19102 (find-file (org-trim (match-string 1))))
19103 ((org-edit-src-code))
19104 ((org-edit-fixed-width-region))
19105 ((org-at-table.el-p)
19106 (org-edit-src-code))
19107 ((or (org-at-table-p)
19108 (save-excursion
19109 (beginning-of-line 1)
19110 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19111 (call-interactively 'org-table-edit-formulas))
19112 (t (call-interactively 'ffap))))
19114 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19115 (defun org-ctrl-c-ctrl-c (&optional arg)
19116 "Set tags in headline, or update according to changed information at point.
19118 This command does many different things, depending on context:
19120 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19121 this is what we do.
19123 - If the cursor is on a statistics cookie, update it.
19125 - If the cursor is in a headline, prompt for tags and insert them
19126 into the current line, aligned to `org-tags-column'. When called
19127 with prefix arg, realign all tags in the current buffer.
19129 - If the cursor is in one of the special #+KEYWORD lines, this
19130 triggers scanning the buffer for these lines and updating the
19131 information.
19133 - If the cursor is inside a table, realign the table. This command
19134 works even if the automatic table editor has been turned off.
19136 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19137 the entire table.
19139 - If the cursor is at a footnote reference or definition, jump to
19140 the corresponding definition or references, respectively.
19142 - If the cursor is a the beginning of a dynamic block, update it.
19144 - If the current buffer is a capture buffer, close note and file it.
19146 - If the cursor is on a <<<target>>>, update radio targets and
19147 corresponding links in this buffer.
19149 - If the cursor is on a numbered item in a plain list, renumber the
19150 ordered list.
19152 - If the cursor is on a checkbox, toggle it.
19154 - If the cursor is on a code block, evaluate it. The variable
19155 `org-confirm-babel-evaluate' can be used to control prompting
19156 before code block evaluation, by default every code block
19157 evaluation requires confirmation. Code block evaluation can be
19158 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19159 (interactive "P")
19160 (let ((org-enable-table-editor t))
19161 (cond
19162 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19163 org-occur-highlights
19164 org-latex-fragment-image-overlays)
19165 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19166 (org-remove-occur-highlights)
19167 (org-remove-latex-fragment-image-overlays)
19168 (message "Temporary highlights/overlays removed from current buffer"))
19169 ((and (local-variable-p 'org-finish-function (current-buffer))
19170 (fboundp org-finish-function))
19171 (funcall org-finish-function))
19172 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19173 ((org-in-regexp org-ts-regexp-both)
19174 (org-timestamp-change 0 'day))
19175 ((or (looking-at org-property-start-re)
19176 (org-at-property-p))
19177 (call-interactively 'org-property-action))
19178 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19179 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19180 (or (org-at-heading-p) (org-at-item-p)))
19181 (call-interactively 'org-update-statistics-cookies))
19182 ((org-at-heading-p) (call-interactively 'org-set-tags))
19183 ((org-at-table.el-p)
19184 (message "Use C-c ' to edit table.el tables"))
19185 ((org-at-table-p)
19186 (org-table-maybe-eval-formula)
19187 (if arg
19188 (call-interactively 'org-table-recalculate)
19189 (org-table-maybe-recalculate-line))
19190 (call-interactively 'org-table-align)
19191 (orgtbl-send-table 'maybe))
19192 ((or (org-footnote-at-reference-p)
19193 (org-footnote-at-definition-p))
19194 (call-interactively 'org-footnote-action))
19195 ((org-at-item-checkbox-p)
19196 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19197 ;; list only if at top item.
19198 (let* ((cbox (match-string 1))
19199 (struct (org-list-struct))
19200 (old-struct (copy-tree struct))
19201 (parents (org-list-parents-alist struct))
19202 (orderedp (org-entry-get nil "ORDERED"))
19203 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19204 block-item)
19205 ;; Use a light version of `org-toggle-checkbox' to avoid
19206 ;; computing list structure twice.
19207 (let ((new-box (cond
19208 ((equal arg '(16)) "[-]")
19209 ((equal arg '(4)) nil)
19210 ((equal "[X]" cbox) "[ ]")
19211 (t "[X]"))))
19212 (if (and firstp arg)
19213 ;; If at first item of sub-list, remove check-box from
19214 ;; every item at the same level.
19215 (mapc
19216 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19217 (org-list-get-all-items
19218 (point-at-bol) struct (org-list-prevs-alist struct)))
19219 (org-list-set-checkbox (point-at-bol) struct new-box)))
19220 ;; Replicate `org-list-write-struct', while grabbing a return
19221 ;; value from `org-list-struct-fix-box'.
19222 (org-list-struct-fix-ind struct parents 2)
19223 (org-list-struct-fix-item-end struct)
19224 (let ((prevs (org-list-prevs-alist struct)))
19225 (org-list-struct-fix-bul struct prevs)
19226 (org-list-struct-fix-ind struct parents)
19227 (setq block-item
19228 (org-list-struct-fix-box struct parents prevs orderedp)))
19229 (org-list-struct-apply-struct struct old-struct)
19230 (org-update-checkbox-count-maybe)
19231 (when block-item
19232 (message
19233 "Checkboxes were removed due to unchecked box at line %d"
19234 (org-current-line block-item)))
19235 (when firstp (org-list-send-list 'maybe))))
19236 ((org-at-item-p)
19237 ;; Cursor at an item: repair list. Do checkbox related actions
19238 ;; only if function was called with an argument. Send list only
19239 ;; if at top item.
19240 (let* ((struct (org-list-struct))
19241 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19242 old-struct)
19243 (when arg
19244 (setq old-struct (copy-tree struct))
19245 (if firstp
19246 ;; If at first item of sub-list, add check-box to every
19247 ;; item at the same level.
19248 (mapc
19249 (lambda (pos)
19250 (unless (org-list-get-checkbox pos struct)
19251 (org-list-set-checkbox pos struct "[ ]")))
19252 (org-list-get-all-items
19253 (point-at-bol) struct (org-list-prevs-alist struct)))
19254 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19255 (org-list-write-struct
19256 struct (org-list-parents-alist struct) old-struct)
19257 (when arg (org-update-checkbox-count-maybe))
19258 (when firstp (org-list-send-list 'maybe))))
19259 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19260 ;; Dynamic block
19261 (beginning-of-line 1)
19262 (save-excursion (org-update-dblock)))
19263 ((save-excursion
19264 (let ((case-fold-search t))
19265 (beginning-of-line 1)
19266 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19267 (cond
19268 ((or (equal (match-string 1) "TBLFM")
19269 (equal (match-string 1) "tblfm"))
19270 ;; Recalculate the table before this line
19271 (save-excursion
19272 (beginning-of-line 1)
19273 (skip-chars-backward " \r\n\t")
19274 (if (org-at-table-p)
19275 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19277 (let ((org-inhibit-startup-visibility-stuff t)
19278 (org-startup-align-all-tables nil))
19279 (when (boundp 'org-table-coordinate-overlays)
19280 (mapc 'delete-overlay org-table-coordinate-overlays)
19281 (setq org-table-coordinate-overlays nil))
19282 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19283 (message "Local setup has been refreshed"))))
19284 ((org-clock-update-time-maybe))
19286 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19287 (error "C-c C-c can do nothing useful at this location"))))))
19289 (defun org-mode-restart ()
19290 "Restart Org-mode, to scan again for special lines.
19291 Also updates the keyword regular expressions."
19292 (interactive)
19293 (org-mode)
19294 (message "Org-mode restarted"))
19296 (defun org-kill-note-or-show-branches ()
19297 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19298 (interactive)
19299 (if (not org-finish-function)
19300 (progn
19301 (hide-subtree)
19302 (call-interactively 'show-branches))
19303 (let ((org-note-abort t))
19304 (funcall org-finish-function))))
19306 (defun org-return (&optional indent)
19307 "Goto next table row or insert a newline.
19308 Calls `org-table-next-row' or `newline', depending on context.
19309 See the individual commands for more information."
19310 (interactive)
19311 (let (org-ts-what)
19312 (cond
19313 ((or (bobp) (org-in-src-block-p))
19314 (if indent (newline-and-indent) (newline)))
19315 ((org-at-table-p)
19316 (org-table-justify-field-maybe)
19317 (call-interactively 'org-table-next-row))
19318 ;; when `newline-and-indent' is called within a list, make sure
19319 ;; text moved stays inside the item.
19320 ((and (org-in-item-p) indent)
19321 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19322 (progn
19323 (save-match-data (newline))
19324 (org-indent-line-to (length (match-string 0))))
19325 (let ((ind (org-get-indentation)))
19326 (newline)
19327 (if (org-looking-back org-list-end-re)
19328 (org-indent-line)
19329 (org-indent-line-to ind)))))
19330 ((and org-return-follows-link
19331 (org-at-timestamp-p t)
19332 (not (eq org-ts-what 'after)))
19333 (org-follow-timestamp-link))
19334 ((and org-return-follows-link
19335 (let ((tprop (get-text-property (point) 'face)))
19336 (or (eq tprop 'org-link)
19337 (and (listp tprop) (memq 'org-link tprop)))))
19338 (call-interactively 'org-open-at-point))
19339 ((and (org-at-heading-p)
19340 (looking-at
19341 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19342 (org-show-entry)
19343 (end-of-line 1)
19344 (newline))
19345 (t (if indent (newline-and-indent) (newline))))))
19347 (defun org-return-indent ()
19348 "Goto next table row or insert a newline and indent.
19349 Calls `org-table-next-row' or `newline-and-indent', depending on
19350 context. See the individual commands for more information."
19351 (interactive)
19352 (org-return t))
19354 (defun org-ctrl-c-star ()
19355 "Compute table, or change heading status of lines.
19356 Calls `org-table-recalculate' or `org-toggle-heading',
19357 depending on context."
19358 (interactive)
19359 (cond
19360 ((org-at-table-p)
19361 (call-interactively 'org-table-recalculate))
19363 ;; Convert all lines in region to list items
19364 (call-interactively 'org-toggle-heading))))
19366 (defun org-ctrl-c-minus ()
19367 "Insert separator line in table or modify bullet status of line.
19368 Also turns a plain line or a region of lines into list items.
19369 Calls `org-table-insert-hline', `org-toggle-item', or
19370 `org-cycle-list-bullet', depending on context."
19371 (interactive)
19372 (cond
19373 ((org-at-table-p)
19374 (call-interactively 'org-table-insert-hline))
19375 ((org-region-active-p)
19376 (call-interactively 'org-toggle-item))
19377 ((org-in-item-p)
19378 (call-interactively 'org-cycle-list-bullet))
19380 (call-interactively 'org-toggle-item))))
19382 (defun org-toggle-item (arg)
19383 "Convert headings or normal lines to items, items to normal lines.
19384 If there is no active region, only the current line is considered.
19386 If the first non blank line in the region is an headline, convert
19387 all headlines to items, shifting text accordingly.
19389 If it is an item, convert all items to normal lines.
19391 If it is normal text, change region into an item. With a prefix
19392 argument ARG, change each line in region into an item."
19393 (interactive "P")
19394 (let ((shift-text
19395 (function
19396 ;; Shift text in current section to IND, from point to END.
19397 ;; The function leaves point to END line.
19398 (lambda (ind end)
19399 (let ((min-i 1000) (end (copy-marker end)))
19400 ;; First determine the minimum indentation (MIN-I) of
19401 ;; the text.
19402 (save-excursion
19403 (catch 'exit
19404 (while (< (point) end)
19405 (let ((i (org-get-indentation)))
19406 (cond
19407 ;; Skip blank lines and inline tasks.
19408 ((looking-at "^[ \t]*$"))
19409 ((looking-at org-outline-regexp-bol))
19410 ;; We can't find less than 0 indentation.
19411 ((zerop i) (throw 'exit (setq min-i 0)))
19412 ((< i min-i) (setq min-i i))))
19413 (forward-line))))
19414 ;; Then indent each line so that a line indented to
19415 ;; MIN-I becomes indented to IND. Ignore blank lines
19416 ;; and inline tasks in the process.
19417 (let ((delta (- ind min-i)))
19418 (while (< (point) end)
19419 (unless (or (looking-at "^[ \t]*$")
19420 (looking-at org-outline-regexp-bol))
19421 (org-indent-line-to (+ (org-get-indentation) delta)))
19422 (forward-line)))))))
19423 (skip-blanks
19424 (function
19425 ;; Return beginning of first non-blank line, starting from
19426 ;; line at POS.
19427 (lambda (pos)
19428 (save-excursion
19429 (goto-char pos)
19430 (skip-chars-forward " \r\t\n")
19431 (point-at-bol)))))
19432 beg end)
19433 ;; Determine boundaries of changes.
19434 (if (org-region-active-p)
19435 (setq beg (funcall skip-blanks (region-beginning))
19436 end (copy-marker (region-end)))
19437 (setq beg (funcall skip-blanks (point-at-bol))
19438 end (copy-marker (point-at-eol))))
19439 ;; Depending on the starting line, choose an action on the text
19440 ;; between BEG and END.
19441 (org-with-limited-levels
19442 (save-excursion
19443 (goto-char beg)
19444 (cond
19445 ;; Case 1. Start at an item: de-itemize. Note that it only
19446 ;; happens when a region is active: `org-ctrl-c-minus'
19447 ;; would call `org-cycle-list-bullet' otherwise.
19448 ((org-at-item-p)
19449 (while (< (point) end)
19450 (when (org-at-item-p)
19451 (skip-chars-forward " \t")
19452 (delete-region (point) (match-end 0)))
19453 (forward-line)))
19454 ;; Case 2. Start at an heading: convert to items.
19455 ((org-at-heading-p)
19456 (let* ((bul (org-list-bullet-string "-"))
19457 (bul-len (length bul))
19458 ;; Indentation of the first heading. It should be
19459 ;; relative to the indentation of its parent, if any.
19460 (start-ind (save-excursion
19461 (cond
19462 ((not org-adapt-indentation) 0)
19463 ((not (outline-previous-heading)) 0)
19464 (t (length (match-string 0))))))
19465 ;; Level of first heading. Further headings will be
19466 ;; compared to it to determine hierarchy in the list.
19467 (ref-level (org-reduced-level (org-outline-level))))
19468 (while (< (point) end)
19469 (let* ((level (org-reduced-level (org-outline-level)))
19470 (delta (max 0 (- level ref-level))))
19471 ;; If current headline is less indented than the first
19472 ;; one, set it as reference, in order to preserve
19473 ;; subtrees.
19474 (when (< level ref-level) (setq ref-level level))
19475 (replace-match bul t t)
19476 (org-indent-line-to (+ start-ind (* delta bul-len)))
19477 ;; Ensure all text down to END (or SECTION-END) belongs
19478 ;; to the newly created item.
19479 (let ((section-end (save-excursion
19480 (or (outline-next-heading) (point)))))
19481 (forward-line)
19482 (funcall shift-text
19483 (+ start-ind (* (1+ delta) bul-len))
19484 (min end section-end)))))))
19485 ;; Case 3. Normal line with ARG: turn each non-item line into
19486 ;; an item.
19487 (arg
19488 (while (< (point) end)
19489 (unless (or (org-at-heading-p) (org-at-item-p))
19490 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19491 (replace-match
19492 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19493 (forward-line)))
19494 ;; Case 4. Normal line without ARG: make the first line of
19495 ;; region an item, and shift indentation of others
19496 ;; lines to set them as item's body.
19497 (t (let* ((bul (org-list-bullet-string "-"))
19498 (bul-len (length bul))
19499 (ref-ind (org-get-indentation)))
19500 (skip-chars-forward " \t")
19501 (insert bul)
19502 (forward-line)
19503 (while (< (point) end)
19504 ;; Ensure that lines less indented than first one
19505 ;; still get included in item body.
19506 (funcall shift-text
19507 (+ ref-ind bul-len)
19508 (min end (save-excursion (or (outline-next-heading)
19509 (point)))))
19510 (forward-line)))))))))
19512 (defun org-toggle-heading (&optional nstars)
19513 "Convert headings to normal text, or items or text to headings.
19514 If there is no active region, only the current line is considered.
19516 With a \\[universal-argument] prefix, convert the whole list at
19517 point into heading.
19519 In a region:
19521 - If the first non blank line is an headline, remove the stars
19522 from all headlines in the region.
19524 - If it is a normal line turn each and every normal line (i.e. not an
19525 heading or an item) in the region into a heading.
19527 - If it is a plain list item, turn all plain list items into headings.
19529 When converting a line into a heading, the number of stars is chosen
19530 such that the lines become children of the current entry. However,
19531 when a prefix argument is given, its value determines the number of
19532 stars to add."
19533 (interactive "P")
19534 (let ((skip-blanks
19535 (function
19536 ;; Return beginning of first non-blank line, starting from
19537 ;; line at POS.
19538 (lambda (pos)
19539 (save-excursion
19540 (goto-char pos)
19541 (while (org-at-comment-p) (forward-line))
19542 (skip-chars-forward " \r\t\n")
19543 (point-at-bol)))))
19544 beg end toggled)
19545 ;; Determine boundaries of changes. If a universal prefix has
19546 ;; been given, put the list in a region. If region ends at a bol,
19547 ;; do not consider the last line to be in the region.
19549 (when (and current-prefix-arg (org-at-item-p))
19550 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19551 (org-mark-element))
19553 (if (org-region-active-p)
19554 (setq beg (funcall skip-blanks (region-beginning))
19555 end (copy-marker (save-excursion
19556 (goto-char (region-end))
19557 (if (bolp) (point) (point-at-eol)))))
19558 (setq beg (funcall skip-blanks (point-at-bol))
19559 end (copy-marker (point-at-eol))))
19560 ;; Ensure inline tasks don't count as headings.
19561 (org-with-limited-levels
19562 (save-excursion
19563 (goto-char beg)
19564 (cond
19565 ;; Case 1. Started at an heading: de-star headings.
19566 ((org-at-heading-p)
19567 (while (< (point) end)
19568 (when (org-at-heading-p t)
19569 (looking-at org-outline-regexp) (replace-match "")
19570 (setq toggled t))
19571 (forward-line)))
19572 ;; Case 2. Started at an item: change items into headlines.
19573 ;; One star will be added by `org-list-to-subtree'.
19574 ((org-at-item-p)
19575 (let* ((stars (make-string
19576 (if nstars
19577 ;; subtract the star that will be added again by
19578 ;; `org-list-to-subtree'
19579 (1- (prefix-numeric-value current-prefix-arg))
19580 (or (org-current-level) 0))
19581 ?*))
19582 (add-stars
19583 (cond (nstars "") ; stars from prefix only
19584 ((equal stars "") "") ; before first heading
19585 (org-odd-levels-only "*") ; inside heading, odd
19586 (t "")))) ; inside heading, oddeven
19587 (while (< (point) end)
19588 (when (org-at-item-p)
19589 ;; Pay attention to cases when region ends before list.
19590 (let* ((struct (org-list-struct))
19591 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19592 (save-restriction
19593 (narrow-to-region (point) list-end)
19594 (insert
19595 (org-list-to-subtree
19596 (org-list-parse-list t)
19597 '(:istart (concat stars add-stars (funcall get-stars depth))
19598 :icount (concat stars add-stars (funcall get-stars depth)))))))
19599 (setq toggled t))
19600 (forward-line))))
19601 ;; Case 3. Started at normal text: make every line an heading,
19602 ;; skipping headlines and items.
19603 (t (let* ((stars (make-string
19604 (if nstars
19605 (prefix-numeric-value current-prefix-arg)
19606 (or (org-current-level) 0))
19607 ?*))
19608 (add-stars
19609 (cond (nstars "") ; stars from prefix only
19610 ((equal stars "") "*") ; before first heading
19611 (org-odd-levels-only "**") ; inside heading, odd
19612 (t "*"))) ; inside heading, oddeven
19613 (rpl (concat stars add-stars " ")))
19614 (while (< (point) end)
19615 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19616 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19617 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19618 (forward-line)))))))
19619 (unless toggled (message "Cannot toggle heading from here"))))
19621 (defun org-meta-return (&optional arg)
19622 "Insert a new heading or wrap a region in a table.
19623 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19624 See the individual commands for more information."
19625 (interactive "P")
19626 (cond
19627 ((run-hook-with-args-until-success 'org-metareturn-hook))
19628 ((or (org-at-drawer-p) (org-at-property-p))
19629 (newline-and-indent))
19630 ((org-at-table-p)
19631 (call-interactively 'org-table-wrap-region))
19632 (t (call-interactively 'org-insert-heading))))
19634 ;;; Menu entries
19636 (defsubst org-in-subtree-not-table-p ()
19637 "Are we in a subtree and not in a table?"
19638 (and (not (org-before-first-heading-p))
19639 (not (org-at-table-p))))
19641 ;; Define the Org-mode menus
19642 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19643 '("Tbl"
19644 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19645 ["Next Field" org-cycle (org-at-table-p)]
19646 ["Previous Field" org-shifttab (org-at-table-p)]
19647 ["Next Row" org-return (org-at-table-p)]
19648 "--"
19649 ["Blank Field" org-table-blank-field (org-at-table-p)]
19650 ["Edit Field" org-table-edit-field (org-at-table-p)]
19651 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19652 "--"
19653 ("Column"
19654 ["Move Column Left" org-metaleft (org-at-table-p)]
19655 ["Move Column Right" org-metaright (org-at-table-p)]
19656 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19657 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19658 ("Row"
19659 ["Move Row Up" org-metaup (org-at-table-p)]
19660 ["Move Row Down" org-metadown (org-at-table-p)]
19661 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19662 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19663 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19664 "--"
19665 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19666 ("Rectangle"
19667 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19668 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19669 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19670 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19671 "--"
19672 ("Calculate"
19673 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19674 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19675 ["Edit Formulas" org-edit-special (org-at-table-p)]
19676 "--"
19677 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19678 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19679 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19680 "--"
19681 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19682 "--"
19683 ["Sum Column/Rectangle" org-table-sum
19684 (or (org-at-table-p) (org-region-active-p))]
19685 ["Which Column?" org-table-current-column (org-at-table-p)])
19686 ["Debug Formulas"
19687 org-table-toggle-formula-debugger
19688 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19689 ["Show Col/Row Numbers"
19690 org-table-toggle-coordinate-overlays
19691 :style toggle
19692 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19693 "--"
19694 ["Create" org-table-create (and (not (org-at-table-p))
19695 org-enable-table-editor)]
19696 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19697 ["Import from File" org-table-import (not (org-at-table-p))]
19698 ["Export to File" org-table-export (org-at-table-p)]
19699 "--"
19700 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19702 (easy-menu-define org-org-menu org-mode-map "Org menu"
19703 '("Org"
19704 ("Show/Hide"
19705 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19706 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19707 ["Sparse Tree..." org-sparse-tree t]
19708 ["Reveal Context" org-reveal t]
19709 ["Show All" show-all t]
19710 "--"
19711 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19712 "--"
19713 ["New Heading" org-insert-heading t]
19714 ("Navigate Headings"
19715 ["Up" outline-up-heading t]
19716 ["Next" outline-next-visible-heading t]
19717 ["Previous" outline-previous-visible-heading t]
19718 ["Next Same Level" outline-forward-same-level t]
19719 ["Previous Same Level" outline-backward-same-level t]
19720 "--"
19721 ["Jump" org-goto t])
19722 ("Edit Structure"
19723 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19724 "--"
19725 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19726 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19727 "--"
19728 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19729 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19730 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19731 "--"
19732 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19733 "--"
19734 ["Copy visible text" org-copy-visible t]
19735 "--"
19736 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19737 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19738 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19739 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19740 "--"
19741 ["Sort Region/Children" org-sort t]
19742 "--"
19743 ["Convert to odd levels" org-convert-to-odd-levels t]
19744 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19745 ("Editing"
19746 ["Emphasis..." org-emphasize t]
19747 ["Edit Source Example" org-edit-special t]
19748 "--"
19749 ["Footnote new/jump" org-footnote-action t]
19750 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19751 ("Archive"
19752 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19753 "--"
19754 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19755 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19756 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19758 "--"
19759 ("Hyperlinks"
19760 ["Store Link (Global)" org-store-link t]
19761 ["Find existing link to here" org-occur-link-in-agenda-files t]
19762 ["Insert Link" org-insert-link t]
19763 ["Follow Link" org-open-at-point t]
19764 "--"
19765 ["Next link" org-next-link t]
19766 ["Previous link" org-previous-link t]
19767 "--"
19768 ["Descriptive Links"
19769 org-toggle-link-display
19770 :style radio
19771 :selected org-descriptive-links
19773 ["Literal Links"
19774 org-toggle-link-display
19775 :style radio
19776 :selected (not org-descriptive-links)])
19777 "--"
19778 ("TODO Lists"
19779 ["TODO/DONE/-" org-todo t]
19780 ("Select keyword"
19781 ["Next keyword" org-shiftright (org-at-heading-p)]
19782 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19783 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19784 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19785 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19786 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19787 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19788 "--"
19789 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19790 :selected org-enforce-todo-dependencies :style toggle :active t]
19791 "Settings for tree at point"
19792 ["Do Children sequentially" org-toggle-ordered-property :style radio
19793 :selected (org-entry-get nil "ORDERED")
19794 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19795 ["Do Children parallel" org-toggle-ordered-property :style radio
19796 :selected (not (org-entry-get nil "ORDERED"))
19797 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19798 "--"
19799 ["Set Priority" org-priority t]
19800 ["Priority Up" org-shiftup t]
19801 ["Priority Down" org-shiftdown t]
19802 "--"
19803 ["Get news from all feeds" org-feed-update-all t]
19804 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19805 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19806 ("TAGS and Properties"
19807 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19808 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19809 "--"
19810 ["Set property" org-set-property (not (org-before-first-heading-p))]
19811 ["Column view of properties" org-columns t]
19812 ["Insert Column View DBlock" org-insert-columns-dblock t])
19813 ("Dates and Scheduling"
19814 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19815 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19816 ("Change Date"
19817 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19818 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19819 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19820 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19821 ["Compute Time Range" org-evaluate-time-range t]
19822 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19823 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19824 "--"
19825 ["Custom time format" org-toggle-time-stamp-overlays
19826 :style radio :selected org-display-custom-times]
19827 "--"
19828 ["Goto Calendar" org-goto-calendar t]
19829 ["Date from Calendar" org-date-from-calendar t]
19830 "--"
19831 ["Start/Restart Timer" org-timer-start t]
19832 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19833 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19834 ["Insert Timer String" org-timer t]
19835 ["Insert Timer Item" org-timer-item t])
19836 ("Logging work"
19837 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19838 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19839 ["Clock out" org-clock-out t]
19840 ["Clock cancel" org-clock-cancel t]
19841 "--"
19842 ["Mark as default task" org-clock-mark-default-task t]
19843 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19844 ["Goto running clock" org-clock-goto t]
19845 "--"
19846 ["Display times" org-clock-display t]
19847 ["Create clock table" org-clock-report t]
19848 "--"
19849 ["Record DONE time"
19850 (progn (setq org-log-done (not org-log-done))
19851 (message "Switching to %s will %s record a timestamp"
19852 (car org-done-keywords)
19853 (if org-log-done "automatically" "not")))
19854 :style toggle :selected org-log-done])
19855 "--"
19856 ["Agenda Command..." org-agenda t]
19857 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19858 ("File List for Agenda")
19859 ("Special views current file"
19860 ["TODO Tree" org-show-todo-tree t]
19861 ["Check Deadlines" org-check-deadlines t]
19862 ["Timeline" org-timeline t]
19863 ["Tags/Property tree" org-match-sparse-tree t])
19864 "--"
19865 ["Export/Publish..." org-export t]
19866 ("LaTeX"
19867 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19868 :selected org-cdlatex-mode]
19869 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19870 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19871 ["Modify math symbol" org-cdlatex-math-modify
19872 (org-inside-LaTeX-fragment-p)]
19873 ["Insert citation" org-reftex-citation t]
19874 "--"
19875 ["Template for BEAMER" (progn (require 'org-beamer)
19876 (org-insert-beamer-options-template)) t])
19877 "--"
19878 ("MobileOrg"
19879 ["Push Files and Views" org-mobile-push t]
19880 ["Get Captured and Flagged" org-mobile-pull t]
19881 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19882 "--"
19883 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19884 "--"
19885 ("Documentation"
19886 ["Show Version" org-version t]
19887 ["Info Documentation" org-info t])
19888 ("Customize"
19889 ["Browse Org Group" org-customize t]
19890 "--"
19891 ["Expand This Menu" org-create-customize-menu
19892 (fboundp 'customize-menu-create)])
19893 ["Send bug report" org-submit-bug-report t]
19894 "--"
19895 ("Refresh/Reload"
19896 ["Refresh setup current buffer" org-mode-restart t]
19897 ["Reload Org (after update)" org-reload t]
19898 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19901 (defun org-info (&optional node)
19902 "Read documentation for Org-mode in the info system.
19903 With optional NODE, go directly to that node."
19904 (interactive)
19905 (info (format "(org)%s" (or node ""))))
19907 ;;;###autoload
19908 (defun org-submit-bug-report ()
19909 "Submit a bug report on Org-mode via mail.
19911 Don't hesitate to report any problems or inaccurate documentation.
19913 If you don't have setup sending mail from (X)Emacs, please copy the
19914 output buffer into your mail program, as it gives us important
19915 information about your Org-mode version and configuration."
19916 (interactive)
19917 (require 'reporter)
19918 (org-load-modules-maybe)
19919 (org-require-autoloaded-modules)
19920 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19921 (reporter-submit-bug-report
19922 "emacs-orgmode@gnu.org"
19923 (org-version nil 'full)
19924 (let (list)
19925 (save-window-excursion
19926 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19927 (delete-other-windows)
19928 (erase-buffer)
19929 (insert "You are about to submit a bug report to the Org-mode mailing list.
19931 We would like to add your full Org-mode and Outline configuration to the
19932 bug report. This greatly simplifies the work of the maintainer and
19933 other experts on the mailing list.
19935 HOWEVER, some variables you have customized may contain private
19936 information. The names of customers, colleagues, or friends, might
19937 appear in the form of file names, tags, todo states, or search strings.
19938 If you answer yes to the prompt, you might want to check and remove
19939 such private information before sending the email.")
19940 (add-text-properties (point-min) (point-max) '(face org-warning))
19941 (when (yes-or-no-p "Include your Org-mode configuration ")
19942 (mapatoms
19943 (lambda (v)
19944 (and (boundp v)
19945 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19946 (or (and (symbol-value v)
19947 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19948 (and
19949 (get v 'custom-type) (get v 'standard-value)
19950 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19951 (push v list)))))
19952 (kill-buffer (get-buffer "*Warn about privacy*"))
19953 list))
19954 nil nil
19955 "Remember to cover the basics, that is, what you expected to happen and
19956 what in fact did happen. You don't know how to make a good report? See
19958 http://orgmode.org/manual/Feedback.html#Feedback
19960 Your bug report will be posted to the Org-mode mailing list.
19961 ------------------------------------------------------------------------")
19962 (save-excursion
19963 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19964 (replace-match "\\1Bug: \\3 [\\2]")))))
19967 (defun org-install-agenda-files-menu ()
19968 (let ((bl (buffer-list)))
19969 (save-excursion
19970 (while bl
19971 (set-buffer (pop bl))
19972 (if (derived-mode-p 'org-mode) (setq bl nil)))
19973 (when (derived-mode-p 'org-mode)
19974 (easy-menu-change
19975 '("Org") "File List for Agenda"
19976 (append
19977 (list
19978 ["Edit File List" (org-edit-agenda-file-list) t]
19979 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19980 ["Remove Current File from List" org-remove-file t]
19981 ["Cycle through agenda files" org-cycle-agenda-files t]
19982 ["Occur in all agenda files" org-occur-in-agenda-files t]
19983 "--")
19984 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19986 ;;;; Documentation
19988 ;;;###autoload
19989 (defun org-require-autoloaded-modules ()
19990 (interactive)
19991 (mapc 'require
19992 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19993 org-docbook org-exp org-html org-icalendar
19994 org-id org-latex
19995 org-publish org-remember org-table
19996 org-timer org-xoxo)))
19998 ;;;###autoload
19999 (defun org-reload (&optional uncompiled)
20000 "Reload all org lisp files.
20001 With prefix arg UNCOMPILED, load the uncompiled versions."
20002 (interactive "P")
20003 (require 'find-func)
20004 (let* ((file-re "^org\\(-.*\\)?\\.el")
20005 (dir-org (file-name-directory (org-find-library-dir "org")))
20006 (dir-org-contrib (ignore-errors
20007 (file-name-directory
20008 (org-find-library-dir "org-contribdir"))))
20009 (babel-files
20010 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20011 (append (list nil "comint" "eval" "exp" "keys"
20012 "lob" "ref" "table" "tangle")
20013 (delq nil
20014 (mapcar
20015 (lambda (lang)
20016 (when (cdr lang) (symbol-name (car lang))))
20017 org-babel-load-languages)))))
20018 (files
20019 (append babel-files
20020 (and dir-org-contrib
20021 (directory-files dir-org-contrib t file-re))
20022 (directory-files dir-org t file-re)))
20023 (remove-re (concat (if (featurep 'xemacs)
20024 "org-colview" "org-colview-xemacs")
20025 "\\'")))
20026 (setq files (mapcar 'file-name-sans-extension files))
20027 (setq files (mapcar
20028 (lambda (x) (if (string-match remove-re x) nil x))
20029 files))
20030 (setq files (delq nil files))
20031 (mapc
20032 (lambda (f)
20033 (when (featurep (intern (file-name-nondirectory f)))
20034 (if (and (not uncompiled)
20035 (file-exists-p (concat f ".elc")))
20036 (load (concat f ".elc") nil nil 'nosuffix)
20037 (load (concat f ".el") nil nil 'nosuffix))))
20038 files)
20039 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20040 (org-version nil 'full 'message))
20042 ;;;###autoload
20043 (defun org-customize ()
20044 "Call the customize function with org as argument."
20045 (interactive)
20046 (org-load-modules-maybe)
20047 (org-require-autoloaded-modules)
20048 (customize-browse 'org))
20050 (defun org-create-customize-menu ()
20051 "Create a full customization menu for Org-mode, insert it into the menu."
20052 (interactive)
20053 (org-load-modules-maybe)
20054 (org-require-autoloaded-modules)
20055 (if (fboundp 'customize-menu-create)
20056 (progn
20057 (easy-menu-change
20058 '("Org") "Customize"
20059 `(["Browse Org group" org-customize t]
20060 "--"
20061 ,(customize-menu-create 'org)
20062 ["Set" Custom-set t]
20063 ["Save" Custom-save t]
20064 ["Reset to Current" Custom-reset-current t]
20065 ["Reset to Saved" Custom-reset-saved t]
20066 ["Reset to Standard Settings" Custom-reset-standard t]))
20067 (message "\"Org\"-menu now contains full customization menu"))
20068 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20070 ;;;; Miscellaneous stuff
20072 ;;; Generally useful functions
20074 (defun org-get-at-bol (property)
20075 "Get text property PROPERTY at beginning of line."
20076 (get-text-property (point-at-bol) property))
20078 (defun org-find-text-property-in-string (prop s)
20079 "Return the first non-nil value of property PROP in string S."
20080 (or (get-text-property 0 prop s)
20081 (get-text-property (or (next-single-property-change 0 prop s) 0)
20082 prop s)))
20084 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20085 "Display the given MESSAGE as a warning."
20086 (if (fboundp 'display-warning)
20087 (display-warning 'org message
20088 (if (featurep 'xemacs) 'warning :warning))
20089 (let ((buf (get-buffer-create "*Org warnings*")))
20090 (with-current-buffer buf
20091 (goto-char (point-max))
20092 (insert "Warning (Org): " message)
20093 (unless (bolp)
20094 (newline)))
20095 (display-buffer buf)
20096 (sit-for 0))))
20098 (defun org-eval (form)
20099 "Eval FORM and return result."
20100 (condition-case error
20101 (eval form)
20102 (error (format "%%![Error: %s]" error))))
20104 (defun org-in-clocktable-p ()
20105 "Check if the cursor is in a clocktable."
20106 (let ((pos (point)) start)
20107 (save-excursion
20108 (end-of-line 1)
20109 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20110 (setq start (match-beginning 0))
20111 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20112 (>= (match-end 0) pos)
20113 start))))
20115 (defun org-in-commented-line ()
20116 "Is point in a line starting with `#'?"
20117 (equal (char-after (point-at-bol)) ?#))
20119 (defun org-in-indented-comment-line ()
20120 "Is point in a line starting with `#' after some white space?"
20121 (save-excursion
20122 (save-match-data
20123 (goto-char (point-at-bol))
20124 (looking-at "[ \t]*#"))))
20126 (defun org-in-verbatim-emphasis ()
20127 (save-match-data
20128 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20130 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20131 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20132 (if (and marker (marker-buffer marker)
20133 (buffer-live-p (marker-buffer marker)))
20134 (progn
20135 (org-pop-to-buffer-same-window (marker-buffer marker))
20136 (if (or (> marker (point-max)) (< marker (point-min)))
20137 (widen))
20138 (goto-char marker)
20139 (org-show-context 'org-goto))
20140 (if bookmark
20141 (bookmark-jump bookmark)
20142 (error "Cannot find location"))))
20144 (defun org-quote-csv-field (s)
20145 "Quote field for inclusion in CSV material."
20146 (if (string-match "[\",]" s)
20147 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20150 (defun org-force-self-insert (N)
20151 "Needed to enforce self-insert under remapping."
20152 (interactive "p")
20153 (self-insert-command N))
20155 (defun org-string-width (s)
20156 "Compute width of string, ignoring invisible characters.
20157 This ignores character with invisibility property `org-link', and also
20158 characters with property `org-cwidth', because these will become invisible
20159 upon the next fontification round."
20160 (let (b l)
20161 (when (or (eq t buffer-invisibility-spec)
20162 (assq 'org-link buffer-invisibility-spec))
20163 (while (setq b (text-property-any 0 (length s)
20164 'invisible 'org-link s))
20165 (setq s (concat (substring s 0 b)
20166 (substring s (or (next-single-property-change
20167 b 'invisible s) (length s)))))))
20168 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20169 (setq s (concat (substring s 0 b)
20170 (substring s (or (next-single-property-change
20171 b 'org-cwidth s) (length s))))))
20172 (setq l (string-width s) b -1)
20173 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20174 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20177 (defun org-shorten-string (s maxlength)
20178 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20179 If the string is shorter or has length MAXLENGTH, just return the
20180 original string. If it is longer, the functions finds a space in the
20181 string, breaks this string off at that locations and adds three dots
20182 as ellipsis. Including the ellipsis, the string will not be longer
20183 than MAXLENGTH. If finding a good breaking point in the string does
20184 not work, the string is just chopped off in the middle of a word
20185 if necessary."
20186 (if (<= (length s) maxlength)
20188 (let* ((n (max (- maxlength 4) 1))
20189 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20190 (if (string-match re s)
20191 (concat (match-string 1 s) "...")
20192 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20194 (defun org-get-indentation (&optional line)
20195 "Get the indentation of the current line, interpreting tabs.
20196 When LINE is given, assume it represents a line and compute its indentation."
20197 (if line
20198 (if (string-match "^ *" (org-remove-tabs line))
20199 (match-end 0))
20200 (save-excursion
20201 (beginning-of-line 1)
20202 (skip-chars-forward " \t")
20203 (current-column))))
20205 (defun org-get-string-indentation (s)
20206 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20207 (let ((n -1) (i 0) (w tab-width) c)
20208 (catch 'exit
20209 (while (< (setq n (1+ n)) (length s))
20210 (setq c (aref s n))
20211 (cond ((= c ?\ ) (setq i (1+ i)))
20212 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20213 (t (throw 'exit t)))))
20216 (defun org-remove-tabs (s &optional width)
20217 "Replace tabulators in S with spaces.
20218 Assumes that s is a single line, starting in column 0."
20219 (setq width (or width tab-width))
20220 (while (string-match "\t" s)
20221 (setq s (replace-match
20222 (make-string
20223 (- (* width (/ (+ (match-beginning 0) width) width))
20224 (match-beginning 0)) ?\ )
20225 t t s)))
20228 (defun org-fix-indentation (line ind)
20229 "Fix indentation in LINE.
20230 IND is a cons cell with target and minimum indentation.
20231 If the current indentation in LINE is smaller than the minimum,
20232 leave it alone. If it is larger than ind, set it to the target."
20233 (let* ((l (org-remove-tabs line))
20234 (i (org-get-indentation l))
20235 (i1 (car ind)) (i2 (cdr ind)))
20236 (if (>= i i2) (setq l (substring line i2)))
20237 (if (> i1 0)
20238 (concat (make-string i1 ?\ ) l)
20239 l)))
20241 (defun org-remove-indentation (code &optional n)
20242 "Remove the maximum common indentation from the lines in CODE.
20243 N may optionally be the number of spaces to remove."
20244 (with-temp-buffer
20245 (insert code)
20246 (org-do-remove-indentation n)
20247 (buffer-string)))
20249 (defun org-do-remove-indentation (&optional n)
20250 "Remove the maximum common indentation from the buffer."
20251 (untabify (point-min) (point-max))
20252 (let ((min 10000) re)
20253 (if n
20254 (setq min n)
20255 (goto-char (point-min))
20256 (while (re-search-forward "^ *[^ \n]" nil t)
20257 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20258 (unless (or (= min 0) (= min 10000))
20259 (setq re (format "^ \\{%d\\}" min))
20260 (goto-char (point-min))
20261 (while (re-search-forward re nil t)
20262 (replace-match "")
20263 (end-of-line 1))
20264 min)))
20266 (defun org-fill-template (template alist)
20267 "Find each %key of ALIST in TEMPLATE and replace it."
20268 (let ((case-fold-search nil)
20269 entry key value)
20270 (setq alist (sort (copy-sequence alist)
20271 (lambda (a b) (< (length (car a)) (length (car b))))))
20272 (while (setq entry (pop alist))
20273 (setq template
20274 (replace-regexp-in-string
20275 (concat "%" (regexp-quote (car entry)))
20276 (or (cdr entry) "") template t t)))
20277 template))
20279 (defun org-base-buffer (buffer)
20280 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20281 (if (not buffer)
20282 buffer
20283 (or (buffer-base-buffer buffer)
20284 buffer)))
20286 (defun org-trim (s)
20287 "Remove whitespace at beginning and end of string."
20288 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20289 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20292 (defun org-wrap (string &optional width lines)
20293 "Wrap string to either a number of lines, or a width in characters.
20294 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20295 that costs. If there is a word longer than WIDTH, the text is actually
20296 wrapped to the length of that word.
20297 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20298 many lines, whatever width that takes.
20299 The return value is a list of lines, without newlines at the end."
20300 (let* ((words (org-split-string string "[ \t\n]+"))
20301 (maxword (apply 'max (mapcar 'org-string-width words)))
20302 w ll)
20303 (cond (width
20304 (org-do-wrap words (max maxword width)))
20305 (lines
20306 (setq w maxword)
20307 (setq ll (org-do-wrap words maxword))
20308 (if (<= (length ll) lines)
20310 (setq ll words)
20311 (while (> (length ll) lines)
20312 (setq w (1+ w))
20313 (setq ll (org-do-wrap words w)))
20314 ll))
20315 (t (error "Cannot wrap this")))))
20317 (defun org-do-wrap (words width)
20318 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20319 (let (lines line)
20320 (while words
20321 (setq line (pop words))
20322 (while (and words (< (+ (length line) (length (car words))) width))
20323 (setq line (concat line " " (pop words))))
20324 (setq lines (push line lines)))
20325 (nreverse lines)))
20327 (defun org-split-string (string &optional separators)
20328 "Splits STRING into substrings at SEPARATORS.
20329 No empty strings are returned if there are matches at the beginning
20330 and end of string."
20331 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20332 (start 0)
20333 notfirst
20334 (list nil))
20335 (while (and (string-match rexp string
20336 (if (and notfirst
20337 (= start (match-beginning 0))
20338 (< start (length string)))
20339 (1+ start) start))
20340 (< (match-beginning 0) (length string)))
20341 (setq notfirst t)
20342 (or (eq (match-beginning 0) 0)
20343 (and (eq (match-beginning 0) (match-end 0))
20344 (eq (match-beginning 0) start))
20345 (setq list
20346 (cons (substring string start (match-beginning 0))
20347 list)))
20348 (setq start (match-end 0)))
20349 (or (eq start (length string))
20350 (setq list
20351 (cons (substring string start)
20352 list)))
20353 (nreverse list)))
20355 (defun org-quote-vert (s)
20356 "Replace \"|\" with \"\\vert\"."
20357 (while (string-match "|" s)
20358 (setq s (replace-match "\\vert" t t s)))
20361 (defun org-uuidgen-p (s)
20362 "Is S an ID created by UUIDGEN?"
20363 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20365 (defun org-in-src-block-p nil
20366 "Whether point is in a code source block."
20367 (let (ov)
20368 (when (setq ov (overlays-at (point)))
20369 (memq 'org-block-background
20370 (overlay-properties
20371 (car ov))))))
20373 (defun org-context ()
20374 "Return a list of contexts of the current cursor position.
20375 If several contexts apply, all are returned.
20376 Each context entry is a list with a symbol naming the context, and
20377 two positions indicating start and end of the context. Possible
20378 contexts are:
20380 :headline anywhere in a headline
20381 :headline-stars on the leading stars in a headline
20382 :todo-keyword on a TODO keyword (including DONE) in a headline
20383 :tags on the TAGS in a headline
20384 :priority on the priority cookie in a headline
20385 :item on the first line of a plain list item
20386 :item-bullet on the bullet/number of a plain list item
20387 :checkbox on the checkbox in a plain list item
20388 :table in an org-mode table
20389 :table-special on a special filed in a table
20390 :table-table in a table.el table
20391 :clocktable in a clocktable
20392 :src-block in a source block
20393 :link on a hyperlink
20394 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20395 :target on a <<target>>
20396 :radio-target on a <<<radio-target>>>
20397 :latex-fragment on a LaTeX fragment
20398 :latex-preview on a LaTeX fragment with overlaid preview image
20400 This function expects the position to be visible because it uses font-lock
20401 faces as a help to recognize the following contexts: :table-special, :link,
20402 and :keyword."
20403 (let* ((f (get-text-property (point) 'face))
20404 (faces (if (listp f) f (list f)))
20405 (case-fold-search t)
20406 (p (point)) clist o)
20407 ;; First the large context
20408 (cond
20409 ((org-at-heading-p t)
20410 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20411 (when (progn
20412 (beginning-of-line 1)
20413 (looking-at org-todo-line-tags-regexp))
20414 (push (org-point-in-group p 1 :headline-stars) clist)
20415 (push (org-point-in-group p 2 :todo-keyword) clist)
20416 (push (org-point-in-group p 4 :tags) clist))
20417 (goto-char p)
20418 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20419 (if (looking-at "\\[#[A-Z0-9]\\]")
20420 (push (org-point-in-group p 0 :priority) clist)))
20422 ((org-at-item-p)
20423 (push (org-point-in-group p 2 :item-bullet) clist)
20424 (push (list :item (point-at-bol)
20425 (save-excursion (org-end-of-item) (point)))
20426 clist)
20427 (and (org-at-item-checkbox-p)
20428 (push (org-point-in-group p 0 :checkbox) clist)))
20430 ((org-at-table-p)
20431 (push (list :table (org-table-begin) (org-table-end)) clist)
20432 (if (memq 'org-formula faces)
20433 (push (list :table-special
20434 (previous-single-property-change p 'face)
20435 (next-single-property-change p 'face)) clist)))
20436 ((org-at-table-p 'any)
20437 (push (list :table-table) clist)))
20438 (goto-char p)
20440 (let ((case-fold-search t))
20441 ;; New the "medium" contexts: clocktables, source blocks
20442 (cond ((org-in-clocktable-p)
20443 (push (list :clocktable
20444 (and (or (looking-at "#\\+BEGIN: clocktable")
20445 (search-backward "#+BEGIN: clocktable" nil t))
20446 (match-beginning 0))
20447 (and (re-search-forward "#\\+END:?" nil t)
20448 (match-end 0))) clist))
20449 ((org-in-src-block-p)
20450 (push (list :src-block
20451 (and (or (looking-at "#\\+BEGIN_SRC")
20452 (search-backward "#+BEGIN_SRC" nil t))
20453 (match-beginning 0))
20454 (and (search-forward "#+END_SRC" nil t)
20455 (match-beginning 0))) clist))))
20456 (goto-char p)
20458 ;; Now the small context
20459 (cond
20460 ((org-at-timestamp-p)
20461 (push (org-point-in-group p 0 :timestamp) clist))
20462 ((memq 'org-link faces)
20463 (push (list :link
20464 (previous-single-property-change p 'face)
20465 (next-single-property-change p 'face)) clist))
20466 ((memq 'org-special-keyword faces)
20467 (push (list :keyword
20468 (previous-single-property-change p 'face)
20469 (next-single-property-change p 'face)) clist))
20470 ((org-at-target-p)
20471 (push (org-point-in-group p 0 :target) clist)
20472 (goto-char (1- (match-beginning 0)))
20473 (if (looking-at org-radio-target-regexp)
20474 (push (org-point-in-group p 0 :radio-target) clist))
20475 (goto-char p))
20476 ((setq o (car (delq nil
20477 (mapcar
20478 (lambda (x)
20479 (if (memq x org-latex-fragment-image-overlays) x))
20480 (overlays-at (point))))))
20481 (push (list :latex-fragment
20482 (overlay-start o) (overlay-end o)) clist)
20483 (push (list :latex-preview
20484 (overlay-start o) (overlay-end o)) clist))
20485 ((org-inside-LaTeX-fragment-p)
20486 ;; FIXME: positions wrong.
20487 (push (list :latex-fragment (point) (point)) clist)))
20489 (setq clist (nreverse (delq nil clist)))
20490 clist))
20492 ;; FIXME: Compare with at-regexp-p Do we need both?
20493 (defun org-in-regexp (re &optional nlines visually)
20494 "Check if point is inside a match of regexp.
20495 Normally only the current line is checked, but you can include NLINES extra
20496 lines both before and after point into the search.
20497 If VISUALLY is set, require that the cursor is not after the match but
20498 really on, so that the block visually is on the match."
20499 (catch 'exit
20500 (let ((pos (point))
20501 (eol (point-at-eol (+ 1 (or nlines 0))))
20502 (inc (if visually 1 0)))
20503 (save-excursion
20504 (beginning-of-line (- 1 (or nlines 0)))
20505 (while (re-search-forward re eol t)
20506 (if (and (<= (match-beginning 0) pos)
20507 (>= (+ inc (match-end 0)) pos))
20508 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20510 (defun org-at-regexp-p (regexp)
20511 "Is point inside a match of REGEXP in the current line?"
20512 (catch 'exit
20513 (save-excursion
20514 (let ((pos (point)) (end (point-at-eol)))
20515 (beginning-of-line 1)
20516 (while (re-search-forward regexp end t)
20517 (if (and (<= (match-beginning 0) pos)
20518 (>= (match-end 0) pos))
20519 (throw 'exit t)))
20520 nil))))
20522 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20523 "Non-nil when point is between matches of START-RE and END-RE.
20525 Also return a non-nil value when point is on one of the matches.
20527 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20528 buffer positions. Default values are the positions of headlines
20529 surrounding the point.
20531 The functions returns a cons cell whose car (resp. cdr) is the
20532 position before START-RE (resp. after END-RE)."
20533 (save-match-data
20534 (let ((pos (point))
20535 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20536 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20537 beg end)
20538 (save-excursion
20539 ;; Point is on a block when on START-RE or if START-RE can be
20540 ;; found before it...
20541 (and (or (org-at-regexp-p start-re)
20542 (re-search-backward start-re limit-up t))
20543 (setq beg (match-beginning 0))
20544 ;; ... and END-RE after it...
20545 (goto-char (match-end 0))
20546 (re-search-forward end-re limit-down t)
20547 (> (setq end (match-end 0)) pos)
20548 ;; ... without another START-RE in-between.
20549 (goto-char (match-beginning 0))
20550 (not (re-search-backward start-re (1+ beg) t))
20551 ;; Return value.
20552 (cons beg end))))))
20554 (defun org-in-block-p (names)
20555 "Non-nil when point belongs to a block whose name belongs to NAMES.
20557 NAMES is a list of strings containing names of blocks.
20559 Return first block name matched, or nil. Beware that in case of
20560 nested blocks, the returned name may not belong to the closest
20561 block from point."
20562 (save-match-data
20563 (catch 'exit
20564 (let ((case-fold-search t)
20565 (lim-up (save-excursion (outline-previous-heading)))
20566 (lim-down (save-excursion (outline-next-heading))))
20567 (mapc (lambda (name)
20568 (let ((n (regexp-quote name)))
20569 (when (org-between-regexps-p
20570 (concat "^[ \t]*#\\+begin_" n)
20571 (concat "^[ \t]*#\\+end_" n)
20572 lim-up lim-down)
20573 (throw 'exit n))))
20574 names))
20575 nil)))
20577 (defun org-occur-in-agenda-files (regexp &optional nlines)
20578 "Call `multi-occur' with buffers for all agenda files."
20579 (interactive "sOrg-files matching: \np")
20580 (let* ((files (org-agenda-files))
20581 (tnames (mapcar 'file-truename files))
20582 (extra org-agenda-text-search-extra-files)
20584 (when (eq (car extra) 'agenda-archives)
20585 (setq extra (cdr extra))
20586 (setq files (org-add-archive-files files)))
20587 (while (setq f (pop extra))
20588 (unless (member (file-truename f) tnames)
20589 (add-to-list 'files f 'append)
20590 (add-to-list 'tnames (file-truename f) 'append)))
20591 (multi-occur
20592 (mapcar (lambda (x)
20593 (with-current-buffer
20594 (or (get-file-buffer x) (find-file-noselect x))
20595 (widen)
20596 (current-buffer)))
20597 files)
20598 regexp)))
20600 (if (boundp 'occur-mode-find-occurrence-hook)
20601 ;; Emacs 23
20602 (add-hook 'occur-mode-find-occurrence-hook
20603 (lambda ()
20604 (when (derived-mode-p 'org-mode)
20605 (org-reveal))))
20606 ;; Emacs 22
20607 (defadvice occur-mode-goto-occurrence
20608 (after org-occur-reveal activate)
20609 (and (derived-mode-p 'org-mode) (org-reveal)))
20610 (defadvice occur-mode-goto-occurrence-other-window
20611 (after org-occur-reveal activate)
20612 (and (derived-mode-p 'org-mode) (org-reveal)))
20613 (defadvice occur-mode-display-occurrence
20614 (after org-occur-reveal activate)
20615 (when (derived-mode-p 'org-mode)
20616 (let ((pos (occur-mode-find-occurrence)))
20617 (with-current-buffer (marker-buffer pos)
20618 (save-excursion
20619 (goto-char pos)
20620 (org-reveal)))))))
20622 (defun org-occur-link-in-agenda-files ()
20623 "Create a link and search for it in the agendas.
20624 The link is not stored in `org-stored-links', it is just created
20625 for the search purpose."
20626 (interactive)
20627 (let ((link (condition-case nil
20628 (org-store-link nil)
20629 (error "Unable to create a link to here"))))
20630 (org-occur-in-agenda-files (regexp-quote link))))
20632 (defun org-uniquify (list)
20633 "Remove duplicate elements from LIST."
20634 (let (res)
20635 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20636 res))
20638 (defun org-delete-all (elts list)
20639 "Remove all elements in ELTS from LIST."
20640 (while elts
20641 (setq list (delete (pop elts) list)))
20642 list)
20644 (defun org-count (cl-item cl-seq)
20645 "Count the number of occurrences of ITEM in SEQ.
20646 Taken from `count' in cl-seq.el with all keyword arguments removed."
20647 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20648 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20649 (while (< cl-start cl-end)
20650 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20651 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20652 (setq cl-start (1+ cl-start)))
20653 cl-count))
20655 (defun org-remove-if (predicate seq)
20656 "Remove everything from SEQ that fulfills PREDICATE."
20657 (let (res e)
20658 (while seq
20659 (setq e (pop seq))
20660 (if (not (funcall predicate e)) (push e res)))
20661 (nreverse res)))
20663 (defun org-remove-if-not (predicate seq)
20664 "Remove everything from SEQ that does not fulfill PREDICATE."
20665 (let (res e)
20666 (while seq
20667 (setq e (pop seq))
20668 (if (funcall predicate e) (push e res)))
20669 (nreverse res)))
20671 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20672 "Reduce two-argument FUNCTION across SEQ.
20673 Taken from `reduce' in cl-seq.el with all keyword arguments but
20674 \":initial-value\" removed."
20675 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20676 (cadr (memq :initial-value cl-keys)))
20677 (cl-seq (pop cl-seq))
20678 (t (funcall cl-func)))))
20679 (while cl-seq
20680 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20681 cl-accum))
20683 (defun org-back-over-empty-lines ()
20684 "Move backwards over whitespace, to the beginning of the first empty line.
20685 Returns the number of empty lines passed."
20686 (let ((pos (point)))
20687 (if (cdr (assoc 'heading org-blank-before-new-entry))
20688 (skip-chars-backward " \t\n\r")
20689 (unless (eobp)
20690 (forward-line -1)))
20691 (beginning-of-line 2)
20692 (goto-char (min (point) pos))
20693 (count-lines (point) pos)))
20695 (defun org-skip-whitespace ()
20696 (skip-chars-forward " \t\n\r"))
20698 (defun org-point-in-group (point group &optional context)
20699 "Check if POINT is in match-group GROUP.
20700 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20701 match. If the match group does not exist or point is not inside it,
20702 return nil."
20703 (and (match-beginning group)
20704 (>= point (match-beginning group))
20705 (<= point (match-end group))
20706 (if context
20707 (list context (match-beginning group) (match-end group))
20708 t)))
20710 (defun org-switch-to-buffer-other-window (&rest args)
20711 "Switch to buffer in a second window on the current frame.
20712 In particular, do not allow pop-up frames.
20713 Returns the newly created buffer."
20714 (let (pop-up-frames special-display-buffer-names special-display-regexps
20715 special-display-function)
20716 (apply 'switch-to-buffer-other-window args)))
20718 (defun org-combine-plists (&rest plists)
20719 "Create a single property list from all plists in PLISTS.
20720 The process starts by copying the first list, and then setting properties
20721 from the other lists. Settings in the last list are the most significant
20722 ones and overrule settings in the other lists."
20723 (let ((rtn (copy-sequence (pop plists)))
20724 p v ls)
20725 (while plists
20726 (setq ls (pop plists))
20727 (while ls
20728 (setq p (pop ls) v (pop ls))
20729 (setq rtn (plist-put rtn p v))))
20730 rtn))
20732 (defun org-replace-escapes (string table)
20733 "Replace %-escapes in STRING with values in TABLE.
20734 TABLE is an association list with keys like \"%a\" and string values.
20735 The sequences in STRING may contain normal field width and padding information,
20736 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20737 so values can contain further %-escapes if they are define later in TABLE."
20738 (let ((tbl (copy-alist table))
20739 (case-fold-search nil)
20740 (pchg 0)
20741 e re rpl)
20742 (while (setq e (pop tbl))
20743 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20744 (when (and (cdr e) (string-match re (cdr e)))
20745 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20746 (safe "SREF"))
20747 (add-text-properties 0 3 (list 'sref sref) safe)
20748 (setcdr e (replace-match safe t t (cdr e)))))
20749 (while (string-match re string)
20750 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20751 (cdr e)))
20752 (setq string (replace-match rpl t t string))))
20753 (while (setq pchg (next-property-change pchg string))
20754 (let ((sref (get-text-property pchg 'sref string)))
20755 (when (and sref (string-match "SREF" string pchg))
20756 (setq string (replace-match sref t t string)))))
20757 string))
20759 (defun org-sublist (list start end)
20760 "Return a section of LIST, from START to END.
20761 Counting starts at 1."
20762 (let (rtn (c start))
20763 (setq list (nthcdr (1- start) list))
20764 (while (and list (<= c end))
20765 (push (pop list) rtn)
20766 (setq c (1+ c)))
20767 (nreverse rtn)))
20769 (defun org-find-base-buffer-visiting (file)
20770 "Like `find-buffer-visiting' but always return the base buffer and
20771 not an indirect buffer."
20772 (let ((buf (or (get-file-buffer file)
20773 (find-buffer-visiting file))))
20774 (if buf
20775 (or (buffer-base-buffer buf) buf)
20776 nil)))
20778 (defun org-image-file-name-regexp (&optional extensions)
20779 "Return regexp matching the file names of images.
20780 If EXTENSIONS is given, only match these."
20781 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20782 (image-file-name-regexp)
20783 (let ((image-file-name-extensions
20784 (or extensions
20785 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20786 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20787 (concat "\\."
20788 (regexp-opt (nconc (mapcar 'upcase
20789 image-file-name-extensions)
20790 image-file-name-extensions)
20792 "\\'"))))
20794 (defun org-file-image-p (file &optional extensions)
20795 "Return non-nil if FILE is an image."
20796 (save-match-data
20797 (string-match (org-image-file-name-regexp extensions) file)))
20799 (defun org-get-cursor-date ()
20800 "Return the date at cursor in as a time.
20801 This works in the calendar and in the agenda, anywhere else it just
20802 returns the current time."
20803 (let (date day defd)
20804 (cond
20805 ((eq major-mode 'calendar-mode)
20806 (setq date (calendar-cursor-to-date)
20807 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20808 ((eq major-mode 'org-agenda-mode)
20809 (setq day (get-text-property (point) 'day))
20810 (if day
20811 (setq date (calendar-gregorian-from-absolute day)
20812 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20813 (nth 2 date))))))
20814 (or defd (current-time))))
20816 (defvar org-agenda-action-marker (make-marker)
20817 "Marker pointing to the entry for the next agenda action.")
20819 (defun org-mark-entry-for-agenda-action ()
20820 "Mark the current entry as target of an agenda action.
20821 Agenda actions are actions executed from the agenda with the key `k',
20822 which make use of the date at the cursor."
20823 (interactive)
20824 (move-marker org-agenda-action-marker
20825 (save-excursion (org-back-to-heading t) (point))
20826 (current-buffer))
20827 (message
20828 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20830 (defun org-mark-subtree (&optional up)
20831 "Mark the current subtree.
20832 This puts point at the start of the current subtree, and mark at
20833 the end. If a numeric prefix UP is given, move up into the
20834 hierarchy of headlines by UP levels before marking the subtree."
20835 (interactive "P")
20836 (org-with-limited-levels
20837 (cond ((org-at-heading-p) (beginning-of-line))
20838 ((org-before-first-heading-p) (error "Not in a subtree"))
20839 (t (outline-previous-visible-heading 1))))
20840 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20841 (if (org-called-interactively-p 'any)
20842 (call-interactively 'org-mark-element)
20843 (org-mark-element)))
20845 ;;; Indentation
20847 (defun org-indent-line ()
20848 "Indent line depending on context."
20849 (interactive)
20850 (let* ((pos (point))
20851 (itemp (org-at-item-p))
20852 (case-fold-search t)
20853 (org-drawer-regexp (or org-drawer-regexp "\000"))
20854 (inline-task-p (and (featurep 'org-inlinetask)
20855 (org-inlinetask-in-task-p)))
20856 (inline-re (and inline-task-p
20857 (org-inlinetask-outline-regexp)))
20858 column)
20859 (if (and orgstruct-is-++ (eq pos (point)))
20860 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20861 (indent-according-to-mode))
20862 (beginning-of-line 1)
20863 (cond
20864 ;; Headings
20865 ((looking-at org-outline-regexp) (setq column 0))
20866 ;; Included files
20867 ((looking-at "#\\+include:") (setq column 0))
20868 ;; Footnote definition
20869 ((looking-at org-footnote-definition-re) (setq column 0))
20870 ;; Literal examples
20871 ((looking-at "[ \t]*:\\( \\|$\\)")
20872 (setq column (org-get-indentation))) ; do nothing
20873 ;; Lists
20874 ((ignore-errors (goto-char (org-in-item-p)))
20875 (setq column (if itemp
20876 (org-get-indentation)
20877 (org-list-item-body-column (point))))
20878 (goto-char pos))
20879 ;; Drawers
20880 ((and (looking-at "[ \t]*:END:")
20881 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20882 (save-excursion
20883 (goto-char (1- (match-beginning 1)))
20884 (setq column (current-column))))
20885 ;; Special blocks
20886 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20887 (save-excursion
20888 (re-search-backward
20889 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20890 (setq column (org-get-indentation (match-string 0))))
20891 ((and (not (looking-at "[ \t]*#\\+begin_"))
20892 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20893 (save-excursion
20894 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20895 (setq column
20896 (cond ((equal (downcase (match-string 1)) "src")
20897 ;; src blocks: let `org-edit-src-exit' handle them
20898 (org-get-indentation))
20899 ((equal (downcase (match-string 1)) "example")
20900 (max (org-get-indentation)
20901 (org-get-indentation (match-string 0))))
20903 (org-get-indentation (match-string 0))))))
20904 ;; This line has nothing special, look at the previous relevant
20905 ;; line to compute indentation
20907 (beginning-of-line 0)
20908 (while (and (not (bobp))
20909 (not (looking-at org-drawer-regexp))
20910 ;; When point started in an inline task, do not move
20911 ;; above task starting line.
20912 (not (and inline-task-p (looking-at inline-re)))
20913 ;; Skip drawers, blocks, empty lines, verbatim,
20914 ;; comments, tables, footnotes definitions, lists,
20915 ;; inline tasks.
20916 (or (and (looking-at "[ \t]*:END:")
20917 (re-search-backward org-drawer-regexp nil t))
20918 (and (looking-at "[ \t]*#\\+end_")
20919 (re-search-backward "[ \t]*#\\+begin_"nil t))
20920 (looking-at "[ \t]*[\n:#|]")
20921 (looking-at org-footnote-definition-re)
20922 (and (ignore-errors (goto-char (org-in-item-p)))
20923 (goto-char
20924 (org-list-get-top-point (org-list-struct))))
20925 (and (not inline-task-p)
20926 (featurep 'org-inlinetask)
20927 (org-inlinetask-in-task-p)
20928 (or (org-inlinetask-goto-beginning) t))))
20929 (beginning-of-line 0))
20930 (cond
20931 ;; There was an heading above.
20932 ((looking-at "\\*+[ \t]+")
20933 (if (not org-adapt-indentation)
20934 (setq column 0)
20935 (goto-char (match-end 0))
20936 (setq column (current-column))))
20937 ;; A drawer had started and is unfinished
20938 ((looking-at org-drawer-regexp)
20939 (goto-char (1- (match-beginning 1)))
20940 (setq column (current-column)))
20941 ;; Else, nothing noticeable found: get indentation and go on.
20942 (t (setq column (org-get-indentation))))))
20943 ;; Now apply indentation and move cursor accordingly
20944 (goto-char pos)
20945 (if (<= (current-column) (current-indentation))
20946 (org-indent-line-to column)
20947 (save-excursion (org-indent-line-to column)))
20948 ;; Special polishing for properties, see `org-property-format'
20949 (setq column (current-column))
20950 (beginning-of-line 1)
20951 (if (looking-at
20952 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20953 (replace-match (concat (match-string 1)
20954 (format org-property-format
20955 (match-string 2) (match-string 3)))
20956 t t))
20957 (org-move-to-column column))))
20959 (defun org-indent-drawer ()
20960 "Indent the drawer at point."
20961 (interactive)
20962 (let ((p (point))
20963 (e (and (save-excursion (re-search-forward ":END:" nil t))
20964 (match-end 0)))
20965 (folded
20966 (save-excursion
20967 (end-of-line)
20968 (when (overlays-at (point))
20969 (member 'invisible (overlay-properties
20970 (car (overlays-at (point)))))))))
20971 (when folded (org-cycle))
20972 (indent-for-tab-command)
20973 (while (and (move-beginning-of-line 2) (< (point) e))
20974 (indent-for-tab-command))
20975 (goto-char p)
20976 (when folded (org-cycle)))
20977 (message "Drawer at point indented"))
20979 (defun org-indent-block ()
20980 "Indent the block at point."
20981 (interactive)
20982 (let ((p (point))
20983 (case-fold-search t)
20984 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20985 (match-end 0)))
20986 (folded
20987 (save-excursion
20988 (end-of-line)
20989 (when (overlays-at (point))
20990 (member 'invisible (overlay-properties
20991 (car (overlays-at (point)))))))))
20992 (when folded (org-cycle))
20993 (indent-for-tab-command)
20994 (while (and (move-beginning-of-line 2) (< (point) e))
20995 (indent-for-tab-command))
20996 (goto-char p)
20997 (when folded (org-cycle)))
20998 (message "Block at point indented"))
21000 (defun org-indent-region (start end)
21001 "Indent region."
21002 (interactive "r")
21003 (save-excursion
21004 (let ((line-end (org-current-line end)))
21005 (goto-char start)
21006 (while (< (org-current-line) line-end)
21007 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21008 (t (call-interactively 'org-indent-line)))
21009 (move-beginning-of-line 2)))))
21012 ;;; Filling
21014 ;; We use our own fill-paragraph and auto-fill functions.
21016 ;; `org-fill-paragraph' relies on adaptive filling and context
21017 ;; checking. Appropriate `fill-prefix' is computed with
21018 ;; `org-adaptive-fill-function'.
21020 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21021 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21022 ;; `org-adaptive-fill-function' value. Internally,
21023 ;; `org-comment-line-break-function' breaks the line.
21025 ;; `org-setup-filling' installs filling and auto-filling related
21026 ;; variables during `org-mode' initialization.
21028 (defun org-setup-filling ()
21029 (interactive)
21030 ;; Prevent auto-fill from inserting unwanted new items.
21031 (when (boundp 'fill-nobreak-predicate)
21032 (org-set-local
21033 'fill-nobreak-predicate
21034 (org-uniquify
21035 (append fill-nobreak-predicate
21036 '(org-fill-paragraph-separate-nobreak-p
21037 org-fill-line-break-nobreak-p)))))
21038 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21039 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21040 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21041 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21043 (defvar org-element-paragraph-separate) ; org-element.el
21044 (defun org-fill-paragraph-separate-nobreak-p ()
21045 "Non-nil when a line break at point would insert a new item."
21046 (looking-at (substring org-element-paragraph-separate 1)))
21048 (defun org-fill-line-break-nobreak-p ()
21049 "Non-nil when a line break at point would create an Org line break."
21050 (save-excursion
21051 (skip-chars-backward "[ \t]")
21052 (skip-chars-backward "\\\\")
21053 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21055 (declare-function message-in-body-p "message" ())
21056 (defvar org-element--affiliated-re) ; From org-element.el
21057 (defun org-adaptive-fill-function ()
21058 "Compute a fill prefix for the current line.
21059 Return fill prefix, as a string, or nil if current line isn't
21060 meant to be filled."
21061 (org-with-wide-buffer
21062 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21063 ;; FIXME: This is really the job of orgstruct++-mode
21064 (let* ((p (line-beginning-position))
21065 (element (save-excursion (beginning-of-line)
21066 (org-element-at-point)))
21067 (type (org-element-type element))
21068 (post-affiliated
21069 (save-excursion
21070 (goto-char (org-element-property :begin element))
21071 (while (looking-at org-element--affiliated-re) (forward-line))
21072 (point))))
21073 (unless (< p post-affiliated)
21074 (case type
21075 (comment (looking-at "[ \t]*# ?") (match-string 0))
21076 (footnote-definition "")
21077 ((item plain-list)
21078 (make-string (org-list-item-body-column post-affiliated) ? ))
21079 (paragraph
21080 ;; Fill prefix is usually the same as the current line,
21081 ;; except if the paragraph is at the beginning of an item.
21082 (let ((parent (org-element-property :parent element)))
21083 (cond ((eq (org-element-type parent) 'item)
21084 (make-string (org-list-item-body-column
21085 (org-element-property :begin parent))
21086 ? ))
21087 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21088 (match-string 0))
21089 (t ""))))
21090 (comment-block
21091 ;; Only fill contents if P is within block boundaries.
21092 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21093 (forward-line)
21094 (point)))
21095 (cend (save-excursion
21096 (goto-char (org-element-property :end element))
21097 (skip-chars-backward " \r\t\n")
21098 (line-beginning-position))))
21099 (when (and (>= p cbeg) (< p cend))
21100 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21101 (match-string 0)
21102 ""))))))))))
21104 (declare-function message-goto-body "message" ())
21105 (defvar message-cite-prefix-regexp) ; From message.el
21106 (defvar org-element-all-objects) ; From org-element.el
21107 (defun org-fill-paragraph (&optional justify)
21108 "Fill element at point, when applicable.
21110 This function only applies to comment blocks, comments, example
21111 blocks and paragraphs. Also, as a special case, re-align table
21112 when point is at one.
21114 If JUSTIFY is non-nil (interactively, with prefix argument),
21115 justify as well. If `sentence-end-double-space' is non-nil, then
21116 period followed by one space does not end a sentence, so don't
21117 break a line there. The variable `fill-column' controls the
21118 width for filling.
21120 For convenience, when point is at a plain list, an item or
21121 a footnote definition, try to fill the first paragraph within."
21122 ;; Falls back on message-fill-paragraph when necessary
21123 (interactive)
21124 (if (and (derived-mode-p 'message-mode)
21125 (or (not (message-in-body-p))
21126 (save-excursion (move-beginning-of-line 1)
21127 (looking-at message-cite-prefix-regexp))))
21128 (let ((fill-paragraph-function
21129 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21130 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21131 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21132 (paragraph-separate
21133 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21134 (fill-paragraph nil))
21135 (save-excursion
21136 ;; Move to end of line in order to get the first paragraph
21137 ;; within a plain list or a footnote definition.
21138 (end-of-line)
21139 (let ((element (org-element-at-point)))
21140 ;; First check if point is in a blank line at the beginning of
21141 ;; the buffer. In that case, ignore filling.
21142 (if (< (point) (org-element-property :begin element)) t
21143 (case (org-element-type element)
21144 ;; Align Org tables, leave table.el tables as-is.
21145 (table-row (org-table-align) t)
21146 (table
21147 (when (eq (org-element-property :type element) 'org)
21148 (org-table-align))
21150 (paragraph
21151 ;; Paragraphs may contain `line-break' type objects.
21152 (let ((beg (max (point-min)
21153 (org-element-property :contents-begin element)))
21154 (end (min (point-max)
21155 (org-element-property :contents-end element))))
21156 ;; Do nothing if point is at an affiliated keyword.
21157 (if (< (point) beg) t
21158 (when (derived-mode-p 'message-mode)
21159 ;; In `message-mode', do not fill following
21160 ;; citation in current paragraph nor text before
21161 ;; message body.
21162 (let ((body-start (save-excursion (message-goto-body))))
21163 (when body-start (setq beg (max body-start beg))))
21164 (when (save-excursion
21165 (re-search-forward
21166 (concat "^" message-cite-prefix-regexp) end t))
21167 (setq end (match-beginning 0))))
21168 ;; Fill paragraph, taking line breaks into
21169 ;; consideration. For that, slice the paragraph
21170 ;; using line breaks as separators, and fill the
21171 ;; parts in reverse order to avoid messing with
21172 ;; markers.
21173 (save-excursion
21174 (goto-char end)
21175 (mapc
21176 (lambda (pos)
21177 (fill-region-as-paragraph pos (point) justify)
21178 (goto-char pos))
21179 ;; Find the list of ending positions for line
21180 ;; breaks in the current paragraph. Add paragraph
21181 ;; beginning to include first slice.
21182 (nreverse
21183 (cons
21185 (org-element-map
21186 (org-element--parse-objects
21187 beg end nil org-element-all-objects)
21188 'line-break
21189 (lambda (lb) (org-element-property :end lb)))))))
21190 t)))
21191 ;; Contents of `comment-block' type elements should be
21192 ;; filled as plain text, but only if point is within block
21193 ;; markers.
21194 (comment-block
21195 (let* ((case-fold-search t)
21196 (beg (save-excursion
21197 (goto-char (org-element-property :begin element))
21198 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21199 (forward-line)
21200 (point)))
21201 (end (save-excursion
21202 (goto-char (org-element-property :end element))
21203 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21204 (line-beginning-position))))
21205 (when (and (>= (point) beg) (< (point) end))
21206 (fill-region-as-paragraph
21207 (save-excursion
21208 (end-of-line)
21209 (re-search-backward "^[ \t]*$" beg 'move)
21210 (line-beginning-position))
21211 (save-excursion
21212 (beginning-of-line)
21213 (re-search-forward "^[ \t]*$" end 'move)
21214 (line-beginning-position))
21215 justify)))
21217 ;; Fill comments.
21218 (comment (fill-comment-paragraph justify))
21219 ;; Ignore every other element.
21220 (otherwise t)))))))
21222 (defun org-auto-fill-function ()
21223 "Auto-fill function."
21224 ;; Check if auto-filling is meaningful.
21225 (let ((fc (current-fill-column)))
21226 (when (and fc (> (current-column) fc))
21227 (let ((fill-prefix (org-adaptive-fill-function)))
21228 (when fill-prefix (do-auto-fill))))))
21230 (defun org-comment-line-break-function (&optional soft)
21231 "Break line at point and indent, continuing comment if within one.
21232 The inserted newline is marked hard if variable
21233 `use-hard-newlines' is true, unless optional argument SOFT is
21234 non-nil."
21235 (if soft (insert-and-inherit ?\n) (newline 1))
21236 (save-excursion (forward-char -1) (delete-horizontal-space))
21237 (delete-horizontal-space)
21238 (indent-to-left-margin)
21239 (insert-before-markers-and-inherit fill-prefix))
21242 ;;; Comments
21244 ;; Org comments syntax is quite complex. It requires the entire line
21245 ;; to be just a comment. Also, even with the right syntax at the
21246 ;; beginning of line, some some elements (i.e. verse-block or
21247 ;; example-block) don't accept comments. Usual Emacs comment commands
21248 ;; cannot cope with those requirements. Therefore, Org replaces them.
21250 ;; Org still relies on `comment-dwim', but cannot trust
21251 ;; `comment-only-p'. So, `comment-region-function' and
21252 ;; `uncomment-region-function' both point
21253 ;; to`org-comment-or-uncomment-region'. Eventually,
21254 ;; `org-insert-comment' takes care of insertion of comments at the
21255 ;; beginning of line.
21257 ;; `org-setup-comments-handling' install comments related variables
21258 ;; during `org-mode' initialization.
21260 (defun org-setup-comments-handling ()
21261 (interactive)
21262 (org-set-local 'comment-use-syntax nil)
21263 (org-set-local 'comment-start "# ")
21264 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21265 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21266 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21267 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21269 (defun org-insert-comment ()
21270 "Insert an empty comment above current line.
21271 If the line is empty, insert comment at its beginning."
21272 (beginning-of-line)
21273 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21274 (org-indent-line)
21275 (insert "# "))
21277 (defvar comment-empty-lines) ; From newcomment.el.
21278 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21279 "Comment or uncomment each non-blank line in the region.
21280 Uncomment each non-blank line between BEG and END if it only
21281 contains commented lines. Otherwise, comment them."
21282 (save-restriction
21283 ;; Restrict region
21284 (narrow-to-region (save-excursion (goto-char beg)
21285 (skip-chars-forward " \r\t\n" end)
21286 (line-beginning-position))
21287 (save-excursion (goto-char end)
21288 (skip-chars-backward " \r\t\n" beg)
21289 (line-end-position)))
21290 (let ((uncommentp
21291 ;; UNCOMMENTP is non-nil when every non blank line between
21292 ;; BEG and END is a comment.
21293 (save-excursion
21294 (goto-char (point-min))
21295 (while (and (not (eobp))
21296 (let ((element (org-element-at-point)))
21297 (and (eq (org-element-type element) 'comment)
21298 (goto-char (min (point-max)
21299 (org-element-property
21300 :end element)))))))
21301 (eobp))))
21302 (if uncommentp
21303 ;; Only blank lines and comments in region: uncomment it.
21304 (save-excursion
21305 (goto-char (point-min))
21306 (while (not (eobp))
21307 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21308 (replace-match "" nil nil nil 1))
21309 (forward-line)))
21310 ;; Comment each line in region.
21311 (let ((min-indent (point-max)))
21312 ;; First find the minimum indentation across all lines.
21313 (save-excursion
21314 (goto-char (point-min))
21315 (while (and (not (eobp)) (not (zerop min-indent)))
21316 (unless (looking-at "[ \t]*$")
21317 (setq min-indent (min min-indent (current-indentation))))
21318 (forward-line)))
21319 ;; Then loop over all lines.
21320 (save-excursion
21321 (goto-char (point-min))
21322 (while (not (eobp))
21323 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21324 (org-move-to-column min-indent t)
21325 (insert comment-start))
21326 (forward-line))))))))
21329 ;;; Other stuff.
21331 (defun org-toggle-fixed-width-section (arg)
21332 "Toggle the fixed-width export.
21333 If there is no active region, the QUOTE keyword at the current headline is
21334 inserted or removed. When present, it causes the text between this headline
21335 and the next to be exported as fixed-width text, and unmodified.
21336 If there is an active region, this command adds or removes a colon as the
21337 first character of this line. If the first character of a line is a colon,
21338 this line is also exported in fixed-width font."
21339 (interactive "P")
21340 (let* ((cc 0)
21341 (regionp (org-region-active-p))
21342 (beg (if regionp (region-beginning) (point)))
21343 (end (if regionp (region-end)))
21344 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21345 (case-fold-search nil)
21346 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21347 off)
21348 (if regionp
21349 (save-excursion
21350 (goto-char beg)
21351 (setq cc (current-column))
21352 (beginning-of-line 1)
21353 (setq off (looking-at re))
21354 (while (> nlines 0)
21355 (setq nlines (1- nlines))
21356 (beginning-of-line 1)
21357 (cond
21358 (arg
21359 (org-move-to-column cc t)
21360 (insert ": \n")
21361 (forward-line -1))
21362 ((and off (looking-at re))
21363 (replace-match "" t t nil 1))
21364 ((not off) (org-move-to-column cc t) (insert ": ")))
21365 (forward-line 1)))
21366 (save-excursion
21367 (org-back-to-heading)
21368 (cond
21369 ((looking-at (format org-heading-keyword-regexp-format
21370 org-quote-string))
21371 (goto-char (match-end 1))
21372 (looking-at (concat " +" org-quote-string))
21373 (replace-match "" t t)
21374 (when (eolp) (insert " ")))
21375 ((looking-at org-outline-regexp)
21376 (goto-char (match-end 0))
21377 (insert org-quote-string " ")))))))
21379 (defun org-reftex-citation ()
21380 "Use reftex-citation to insert a citation into the buffer.
21381 This looks for a line like
21383 #+BIBLIOGRAPHY: foo plain option:-d
21385 and derives from it that foo.bib is the bibliography file relevant
21386 for this document. It then installs the necessary environment for RefTeX
21387 to work in this buffer and calls `reftex-citation' to insert a citation
21388 into the buffer.
21390 Export of such citations to both LaTeX and HTML is handled by the contributed
21391 package org-exp-bibtex by Taru Karttunen."
21392 (interactive)
21393 (let ((reftex-docstruct-symbol 'rds)
21394 (reftex-cite-format "\\cite{%l}")
21395 rds bib)
21396 (save-excursion
21397 (save-restriction
21398 (widen)
21399 (let ((case-fold-search t)
21400 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21401 (if (not (save-excursion
21402 (or (re-search-forward re nil t)
21403 (re-search-backward re nil t))))
21404 (error "No bibliography defined in file")
21405 (setq bib (concat (match-string 1) ".bib")
21406 rds (list (list 'bib bib)))))))
21407 (call-interactively 'reftex-citation)))
21409 ;;;; Functions extending outline functionality
21411 (defun org-beginning-of-line (&optional arg)
21412 "Go to the beginning of the current line. If that is invisible, continue
21413 to a visible line beginning. This makes the function of C-a more intuitive.
21414 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21415 first attempt, and only move to after the tags when the cursor is already
21416 beyond the end of the headline."
21417 (interactive "P")
21418 (let ((pos (point))
21419 (special (if (consp org-special-ctrl-a/e)
21420 (car org-special-ctrl-a/e)
21421 org-special-ctrl-a/e))
21422 refpos)
21423 (if (org-bound-and-true-p line-move-visual)
21424 (beginning-of-visual-line 1)
21425 (beginning-of-line 1))
21426 (if (and arg (fboundp 'move-beginning-of-line))
21427 (call-interactively 'move-beginning-of-line)
21428 (if (bobp)
21430 (backward-char 1)
21431 (if (org-truely-invisible-p)
21432 (while (and (not (bobp)) (org-truely-invisible-p))
21433 (backward-char 1)
21434 (beginning-of-line 1))
21435 (forward-char 1))))
21436 (when special
21437 (cond
21438 ((and (looking-at org-complex-heading-regexp)
21439 (= (char-after (match-end 1)) ?\ ))
21440 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21441 (point-at-eol)))
21442 (goto-char
21443 (if (eq special t)
21444 (cond ((> pos refpos) refpos)
21445 ((= pos (point)) refpos)
21446 (t (point)))
21447 (cond ((> pos (point)) (point))
21448 ((not (eq last-command this-command)) (point))
21449 (t refpos)))))
21450 ((org-at-item-p)
21451 ;; Being at an item and not looking at an the item means point
21452 ;; was previously moved to beginning of a visual line, which
21453 ;; doesn't contain the item. Therefore, do nothing special,
21454 ;; just stay here.
21455 (when (looking-at org-list-full-item-re)
21456 ;; Set special position at first white space character after
21457 ;; bullet, and check-box, if any.
21458 (let ((after-bullet
21459 (let ((box (match-end 3)))
21460 (if (not box) (match-end 1)
21461 (let ((after (char-after box)))
21462 (if (and after (= after ? )) (1+ box) box))))))
21463 ;; Special case: Move point to special position when
21464 ;; currently after it or at beginning of line.
21465 (if (eq special t)
21466 (when (or (> pos after-bullet) (= (point) pos))
21467 (goto-char after-bullet))
21468 ;; Reversed case: Move point to special position when
21469 ;; point was already at beginning of line and command is
21470 ;; repeated.
21471 (when (and (= (point) pos) (eq last-command this-command))
21472 (goto-char after-bullet))))))))
21473 (org-no-warnings
21474 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21476 (defun org-end-of-line (&optional arg)
21477 "Go to the end of the line.
21478 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21479 first attempt, and only move to after the tags when the cursor is already
21480 beyond the end of the headline."
21481 (interactive "P")
21482 (let ((special (if (consp org-special-ctrl-a/e)
21483 (cdr org-special-ctrl-a/e)
21484 org-special-ctrl-a/e)))
21485 (cond
21486 ((or (not special) arg
21487 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21488 (call-interactively
21489 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21490 ((fboundp 'move-end-of-line) 'move-end-of-line)
21491 (t 'end-of-line))))
21492 ((org-at-heading-p)
21493 (let ((pos (point)))
21494 (beginning-of-line 1)
21495 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21496 (if (eq special t)
21497 (if (or (< pos (match-beginning 1))
21498 (= pos (match-end 0)))
21499 (goto-char (match-beginning 1))
21500 (goto-char (match-end 0)))
21501 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21502 (goto-char (match-end 0))
21503 (goto-char (match-beginning 1))))
21504 (call-interactively (if (fboundp 'move-end-of-line)
21505 'move-end-of-line
21506 'end-of-line)))))
21507 ((org-at-drawer-p)
21508 (move-end-of-line 1)
21509 (when (overlays-at (1- (point))) (backward-char 1)))
21510 ;; At an item: Move before any hidden text.
21511 (t (call-interactively
21512 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21513 ((fboundp 'move-end-of-line) 'move-end-of-line)
21514 (t 'end-of-line)))))
21515 (org-no-warnings
21516 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21518 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21519 (define-key org-mode-map "\C-e" 'org-end-of-line)
21521 (defun org-backward-sentence (&optional arg)
21522 "Go to beginning of sentence, or beginning of table field.
21523 This will call `backward-sentence' or `org-table-beginning-of-field',
21524 depending on context."
21525 (interactive "P")
21526 (cond
21527 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21528 (t (call-interactively 'backward-sentence))))
21530 (defun org-forward-sentence (&optional arg)
21531 "Go to end of sentence, or end of table field.
21532 This will call `forward-sentence' or `org-table-end-of-field',
21533 depending on context."
21534 (interactive "P")
21535 (cond
21536 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21537 (t (call-interactively 'forward-sentence))))
21539 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21540 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21542 (defun org-kill-line (&optional arg)
21543 "Kill line, to tags or end of line."
21544 (interactive "P")
21545 (cond
21546 ((or (not org-special-ctrl-k)
21547 (bolp)
21548 (not (org-at-heading-p)))
21549 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21550 org-ctrl-k-protect-subtree)
21551 (if (or (eq org-ctrl-k-protect-subtree 'error)
21552 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21553 (error "C-k aborted - would kill hidden subtree")))
21554 (call-interactively
21555 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21556 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21557 (kill-region (point) (match-beginning 1))
21558 (org-set-tags nil t))
21559 (t (kill-region (point) (point-at-eol)))))
21561 (define-key org-mode-map "\C-k" 'org-kill-line)
21563 (defun org-yank (&optional arg)
21564 "Yank. If the kill is a subtree, treat it specially.
21565 This command will look at the current kill and check if is a single
21566 subtree, or a series of subtrees[1]. If it passes the test, and if the
21567 cursor is at the beginning of a line or after the stars of a currently
21568 empty headline, then the yank is handled specially. How exactly depends
21569 on the value of the following variables, both set by default.
21571 org-yank-folded-subtrees
21572 When set, the subtree(s) will be folded after insertion, but only
21573 if doing so would now swallow text after the yanked text.
21575 org-yank-adjusted-subtrees
21576 When set, the subtree will be promoted or demoted in order to
21577 fit into the local outline tree structure, which means that the level
21578 will be adjusted so that it becomes the smaller one of the two
21579 *visible* surrounding headings.
21581 Any prefix to this command will cause `yank' to be called directly with
21582 no special treatment. In particular, a simple \\[universal-argument] prefix \
21583 will just
21584 plainly yank the text as it is.
21586 \[1] The test checks if the first non-white line is a heading
21587 and if there are no other headings with fewer stars."
21588 (interactive "P")
21589 (org-yank-generic 'yank arg))
21591 (defun org-yank-generic (command arg)
21592 "Perform some yank-like command.
21594 This function implements the behavior described in the `org-yank'
21595 documentation. However, it has been generalized to work for any
21596 interactive command with similar behavior."
21598 ;; pretend to be command COMMAND
21599 (setq this-command command)
21601 (if arg
21602 (call-interactively command)
21604 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21605 (and (org-kill-is-subtree-p)
21606 (or (bolp)
21607 (and (looking-at "[ \t]*$")
21608 (string-match
21609 "\\`\\*+\\'"
21610 (buffer-substring (point-at-bol) (point)))))))
21611 swallowp)
21612 (cond
21613 ((and subtreep org-yank-folded-subtrees)
21614 (let ((beg (point))
21615 end)
21616 (if (and subtreep org-yank-adjusted-subtrees)
21617 (org-paste-subtree nil nil 'for-yank)
21618 (call-interactively command))
21620 (setq end (point))
21621 (goto-char beg)
21622 (when (and (bolp) subtreep
21623 (not (setq swallowp
21624 (org-yank-folding-would-swallow-text beg end))))
21625 (org-with-limited-levels
21626 (or (looking-at org-outline-regexp)
21627 (re-search-forward org-outline-regexp-bol end t))
21628 (while (and (< (point) end) (looking-at org-outline-regexp))
21629 (hide-subtree)
21630 (org-cycle-show-empty-lines 'folded)
21631 (condition-case nil
21632 (outline-forward-same-level 1)
21633 (error (goto-char end))))))
21634 (when swallowp
21635 (message
21636 "Inserted text not folded because that would swallow text"))
21638 (goto-char end)
21639 (skip-chars-forward " \t\n\r")
21640 (beginning-of-line 1)
21641 (push-mark beg 'nomsg)))
21642 ((and subtreep org-yank-adjusted-subtrees)
21643 (let ((beg (point-at-bol)))
21644 (org-paste-subtree nil nil 'for-yank)
21645 (push-mark beg 'nomsg)))
21647 (call-interactively command))))))
21649 (defun org-yank-folding-would-swallow-text (beg end)
21650 "Would hide-subtree at BEG swallow any text after END?"
21651 (let (level)
21652 (org-with-limited-levels
21653 (save-excursion
21654 (goto-char beg)
21655 (when (or (looking-at org-outline-regexp)
21656 (re-search-forward org-outline-regexp-bol end t))
21657 (setq level (org-outline-level)))
21658 (goto-char end)
21659 (skip-chars-forward " \t\r\n\v\f")
21660 (if (or (eobp)
21661 (and (bolp) (looking-at org-outline-regexp)
21662 (<= (org-outline-level) level)))
21663 nil ; Nothing would be swallowed
21664 t))))) ; something would swallow
21666 (define-key org-mode-map "\C-y" 'org-yank)
21668 (defun org-truely-invisible-p ()
21669 "Check if point is at a character currently not visible.
21670 This version does not only check the character property, but also
21671 `visible-mode'."
21672 ;; Early versions of noutline don't have `outline-invisible-p'.
21673 (if (org-bound-and-true-p visible-mode)
21675 (outline-invisible-p)))
21677 (defun org-invisible-p2 ()
21678 "Check if point is at a character currently not visible."
21679 (save-excursion
21680 (if (and (eolp) (not (bobp))) (backward-char 1))
21681 ;; Early versions of noutline don't have `outline-invisible-p'.
21682 (outline-invisible-p)))
21684 (defun org-back-to-heading (&optional invisible-ok)
21685 "Call `outline-back-to-heading', but provide a better error message."
21686 (condition-case nil
21687 (outline-back-to-heading invisible-ok)
21688 (error (error "Before first headline at position %d in buffer %s"
21689 (point) (current-buffer)))))
21691 (defun org-before-first-heading-p ()
21692 "Before first heading?"
21693 (save-excursion
21694 (end-of-line)
21695 (null (re-search-backward org-outline-regexp-bol nil t))))
21697 (defun org-at-heading-p (&optional ignored)
21698 (outline-on-heading-p t))
21699 ;; Compatibility alias with Org versions < 7.8.03
21700 (defalias 'org-on-heading-p 'org-at-heading-p)
21702 (defun org-at-comment-p nil
21703 "Is cursor in a line starting with a # character?"
21704 (save-excursion
21705 (beginning-of-line)
21706 (looking-at "^#")))
21708 (defun org-at-drawer-p nil
21709 "Is cursor at a drawer keyword?"
21710 (save-excursion
21711 (move-beginning-of-line 1)
21712 (looking-at org-drawer-regexp)))
21714 (defun org-at-block-p nil
21715 "Is cursor at a block keyword?"
21716 (save-excursion
21717 (move-beginning-of-line 1)
21718 (looking-at org-block-regexp)))
21720 (defun org-point-at-end-of-empty-headline ()
21721 "If point is at the end of an empty headline, return t, else nil.
21722 If the heading only contains a TODO keyword, it is still still considered
21723 empty."
21724 (and (looking-at "[ \t]*$")
21725 (when org-todo-line-regexp
21726 (save-excursion
21727 (beginning-of-line 1)
21728 (let ((case-fold-search nil))
21729 (looking-at org-todo-line-regexp)
21730 (string= (match-string 3) ""))))))
21732 (defun org-at-heading-or-item-p ()
21733 (or (org-at-heading-p) (org-at-item-p)))
21735 (defun org-at-target-p ()
21736 (or (org-in-regexp org-radio-target-regexp)
21737 (org-in-regexp org-target-regexp)))
21738 ;; Compatibility alias with Org versions < 7.8.03
21739 (defalias 'org-on-target-p 'org-at-target-p)
21741 (defun org-up-heading-all (arg)
21742 "Move to the heading line of which the present line is a subheading.
21743 This function considers both visible and invisible heading lines.
21744 With argument, move up ARG levels."
21745 (if (fboundp 'outline-up-heading-all)
21746 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21747 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21749 (defun org-up-heading-safe ()
21750 "Move to the heading line of which the present line is a subheading.
21751 This version will not throw an error. It will return the level of the
21752 headline found, or nil if no higher level is found.
21754 Also, this function will be a lot faster than `outline-up-heading',
21755 because it relies on stars being the outline starters. This can really
21756 make a significant difference in outlines with very many siblings."
21757 (let (start-level re)
21758 (org-back-to-heading t)
21759 (setq start-level (funcall outline-level))
21760 (if (equal start-level 1)
21762 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21763 (if (re-search-backward re nil t)
21764 (funcall outline-level)))))
21766 (defun org-first-sibling-p ()
21767 "Is this heading the first child of its parents?"
21768 (interactive)
21769 (let ((re org-outline-regexp-bol)
21770 level l)
21771 (unless (org-at-heading-p t)
21772 (error "Not at a heading"))
21773 (setq level (funcall outline-level))
21774 (save-excursion
21775 (if (not (re-search-backward re nil t))
21777 (setq l (funcall outline-level))
21778 (< l level)))))
21780 (defun org-goto-sibling (&optional previous)
21781 "Goto the next sibling, even if it is invisible.
21782 When PREVIOUS is set, go to the previous sibling instead. Returns t
21783 when a sibling was found. When none is found, return nil and don't
21784 move point."
21785 (let ((fun (if previous 're-search-backward 're-search-forward))
21786 (pos (point))
21787 (re org-outline-regexp-bol)
21788 level l)
21789 (when (condition-case nil (org-back-to-heading t) (error nil))
21790 (setq level (funcall outline-level))
21791 (catch 'exit
21792 (or previous (forward-char 1))
21793 (while (funcall fun re nil t)
21794 (setq l (funcall outline-level))
21795 (when (< l level) (goto-char pos) (throw 'exit nil))
21796 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21797 (goto-char pos)
21798 nil))))
21800 (defun org-show-siblings ()
21801 "Show all siblings of the current headline."
21802 (save-excursion
21803 (while (org-goto-sibling) (org-flag-heading nil)))
21804 (save-excursion
21805 (while (org-goto-sibling 'previous)
21806 (org-flag-heading nil))))
21808 (defun org-goto-first-child ()
21809 "Goto the first child, even if it is invisible.
21810 Return t when a child was found. Otherwise don't move point and
21811 return nil."
21812 (let (level (pos (point)) (re org-outline-regexp-bol))
21813 (when (condition-case nil (org-back-to-heading t) (error nil))
21814 (setq level (outline-level))
21815 (forward-char 1)
21816 (if (and (re-search-forward re nil t) (> (outline-level) level))
21817 (progn (goto-char (match-beginning 0)) t)
21818 (goto-char pos) nil))))
21820 (defun org-show-hidden-entry ()
21821 "Show an entry where even the heading is hidden."
21822 (save-excursion
21823 (org-show-entry)))
21825 (defun org-flag-heading (flag &optional entry)
21826 "Flag the current heading. FLAG non-nil means make invisible.
21827 When ENTRY is non-nil, show the entire entry."
21828 (save-excursion
21829 (org-back-to-heading t)
21830 ;; Check if we should show the entire entry
21831 (if entry
21832 (progn
21833 (org-show-entry)
21834 (save-excursion
21835 (and (outline-next-heading)
21836 (org-flag-heading nil))))
21837 (outline-flag-region (max (point-min) (1- (point)))
21838 (save-excursion (outline-end-of-heading) (point))
21839 flag))))
21841 (defun org-get-next-sibling ()
21842 "Move to next heading of the same level, and return point.
21843 If there is no such heading, return nil.
21844 This is like outline-next-sibling, but invisible headings are ok."
21845 (let ((level (funcall outline-level)))
21846 (outline-next-heading)
21847 (while (and (not (eobp)) (> (funcall outline-level) level))
21848 (outline-next-heading))
21849 (if (or (eobp) (< (funcall outline-level) level))
21851 (point))))
21853 (defun org-get-last-sibling ()
21854 "Move to previous heading of the same level, and return point.
21855 If there is no such heading, return nil."
21856 (let ((opoint (point))
21857 (level (funcall outline-level)))
21858 (outline-previous-heading)
21859 (when (and (/= (point) opoint) (outline-on-heading-p t))
21860 (while (and (> (funcall outline-level) level)
21861 (not (bobp)))
21862 (outline-previous-heading))
21863 (if (< (funcall outline-level) level)
21865 (point)))))
21867 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21868 "Goto to the end of a subtree."
21869 ;; This contains an exact copy of the original function, but it uses
21870 ;; `org-back-to-heading', to make it work also in invisible
21871 ;; trees. And is uses an invisible-ok argument.
21872 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21873 ;; Furthermore, when used inside Org, finding the end of a large subtree
21874 ;; with many children and grandchildren etc, this can be much faster
21875 ;; than the outline version.
21876 (org-back-to-heading invisible-ok)
21877 (let ((first t)
21878 (level (funcall outline-level)))
21879 (if (and (derived-mode-p 'org-mode) (< level 1000))
21880 ;; A true heading (not a plain list item), in Org-mode
21881 ;; This means we can easily find the end by looking
21882 ;; only for the right number of stars. Using a regexp to do
21883 ;; this is so much faster than using a Lisp loop.
21884 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21885 (forward-char 1)
21886 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21887 ;; something else, do it the slow way
21888 (while (and (not (eobp))
21889 (or first (> (funcall outline-level) level)))
21890 (setq first nil)
21891 (outline-next-heading)))
21892 (unless to-heading
21893 (if (memq (preceding-char) '(?\n ?\^M))
21894 (progn
21895 ;; Go to end of line before heading
21896 (forward-char -1)
21897 (if (memq (preceding-char) '(?\n ?\^M))
21898 ;; leave blank line before heading
21899 (forward-char -1))))))
21900 (point))
21902 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21903 "Use Org version in org-mode, for dramatic speed-up."
21904 (if (derived-mode-p 'org-mode)
21905 (progn
21906 (org-end-of-subtree nil t)
21907 (unless (eobp) (backward-char 1)))
21908 ad-do-it))
21910 (defun org-end-of-meta-data-and-drawers ()
21911 "Jump to the first text after meta data and drawers in the current entry.
21912 This will move over empty lines, lines with planning time stamps,
21913 clocking lines, and drawers."
21914 (org-back-to-heading t)
21915 (let ((end (save-excursion (outline-next-heading) (point)))
21916 (re (concat "\\(" org-drawer-regexp "\\)"
21917 "\\|" "[ \t]*" org-keyword-time-regexp)))
21918 (forward-line 1)
21919 (while (re-search-forward re end t)
21920 (if (not (match-end 1))
21921 ;; empty or planning line
21922 (forward-line 1)
21923 ;; a drawer, find the end
21924 (re-search-forward "^[ \t]*:END:" end 'move)
21925 (forward-line 1)))
21926 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21927 (point)))
21929 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21930 "Move forward to the arg'th subheading at same level as this one.
21931 Stop at the first and last subheadings of a superior heading.
21932 Normally this only looks at visible headings, but when INVISIBLE-OK is
21933 non-nil it will also look at invisible ones."
21934 (interactive "p")
21935 (org-back-to-heading invisible-ok)
21936 (org-at-heading-p)
21937 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21938 (re (format "^\\*\\{1,%d\\} " level))
21940 (forward-char 1)
21941 (while (> arg 0)
21942 (while (and (re-search-forward re nil 'move)
21943 (setq l (- (match-end 0) (match-beginning 0) 1))
21944 (= l level)
21945 (not invisible-ok)
21946 (progn (backward-char 1) (outline-invisible-p)))
21947 (if (< l level) (setq arg 1)))
21948 (setq arg (1- arg)))
21949 (beginning-of-line 1)))
21951 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21952 "Move backward to the arg'th subheading at same level as this one.
21953 Stop at the first and last subheadings of a superior heading."
21954 (interactive "p")
21955 (org-back-to-heading)
21956 (org-at-heading-p)
21957 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21958 (re (format "^\\*\\{1,%d\\} " level))
21960 (while (> arg 0)
21961 (while (and (re-search-backward re nil 'move)
21962 (setq l (- (match-end 0) (match-beginning 0) 1))
21963 (= l level)
21964 (not invisible-ok)
21965 (outline-invisible-p))
21966 (if (< l level) (setq arg 1)))
21967 (setq arg (1- arg)))))
21969 ;;;###autoload
21970 (defun org-forward-element ()
21971 "Move forward by one element.
21972 Move to the next element at the same level, when possible."
21973 (interactive)
21974 (cond ((eobp) (error "Cannot move further down"))
21975 ((org-with-limited-levels (org-at-heading-p))
21976 (let ((origin (point)))
21977 (org-forward-heading-same-level 1)
21978 (unless (org-with-limited-levels (org-at-heading-p))
21979 (goto-char origin)
21980 (error "Cannot move further down"))))
21982 (let* ((elem (org-element-at-point))
21983 (end (org-element-property :end elem))
21984 (parent (org-element-property :parent elem)))
21985 (if (and parent (= (org-element-property :contents-end parent) end))
21986 (goto-char (org-element-property :end parent))
21987 (goto-char end))))))
21989 ;;;###autoload
21990 (defun org-backward-element ()
21991 "Move backward by one element.
21992 Move to the previous element at the same level, when possible."
21993 (interactive)
21994 (cond ((bobp) (error "Cannot move further up"))
21995 ((org-with-limited-levels (org-at-heading-p))
21996 ;; At an headline, move to the previous one, if any, or stay
21997 ;; here.
21998 (let ((origin (point)))
21999 (org-backward-heading-same-level 1)
22000 (unless (org-with-limited-levels (org-at-heading-p))
22001 (goto-char origin)
22002 (error "Cannot move further up"))))
22004 (let* ((trail (org-element-at-point 'keep-trail))
22005 (elem (car trail))
22006 (prev-elem (nth 1 trail))
22007 (beg (org-element-property :begin elem)))
22008 (cond
22009 ;; Move to beginning of current element if point isn't
22010 ;; there already.
22011 ((/= (point) beg) (goto-char beg))
22012 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22013 ((org-before-first-heading-p) (goto-char (point-min)))
22014 (t (org-back-to-heading)))))))
22016 ;;;###autoload
22017 (defun org-up-element ()
22018 "Move to upper element."
22019 (interactive)
22020 (if (org-with-limited-levels (org-at-heading-p))
22021 (unless (org-up-heading-safe) (error "No surrounding element"))
22022 (let* ((elem (org-element-at-point))
22023 (parent (org-element-property :parent elem)))
22024 (if parent (goto-char (org-element-property :begin parent))
22025 (if (org-with-limited-levels (org-before-first-heading-p))
22026 (error "No surrounding element")
22027 (org-with-limited-levels (org-back-to-heading)))))))
22029 ;;;###autoload
22030 (defvar org-element-greater-elements)
22031 (defun org-down-element ()
22032 "Move to inner element."
22033 (interactive)
22034 (let ((element (org-element-at-point)))
22035 (cond
22036 ((memq (org-element-type element) '(plain-list table))
22037 (goto-char (org-element-property :contents-begin element))
22038 (forward-char))
22039 ((memq (org-element-type element) org-element-greater-elements)
22040 ;; If contents are hidden, first disclose them.
22041 (when (org-element-property :hiddenp element) (org-cycle))
22042 (goto-char (or (org-element-property :contents-begin element)
22043 (error "No content for this element"))))
22044 (t (error "No inner element")))))
22046 ;;;###autoload
22047 (defun org-drag-element-backward ()
22048 "Move backward element at point."
22049 (interactive)
22050 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22051 (let* ((trail (org-element-at-point 'keep-trail))
22052 (elem (car trail))
22053 (prev-elem (nth 1 trail)))
22054 ;; Error out if no previous element or previous element is
22055 ;; a parent of the current one.
22056 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22057 (error "Cannot drag element backward")
22058 (let ((pos (point)))
22059 (org-element-swap-A-B prev-elem elem)
22060 (goto-char (+ (org-element-property :begin prev-elem)
22061 (- pos (org-element-property :begin elem)))))))))
22063 ;;;###autoload
22064 (defun org-drag-element-forward ()
22065 "Move forward element at point."
22066 (interactive)
22067 (let* ((pos (point))
22068 (elem (org-element-at-point)))
22069 (when (= (point-max) (org-element-property :end elem))
22070 (error "Cannot drag element forward"))
22071 (goto-char (org-element-property :end elem))
22072 (let ((next-elem (org-element-at-point)))
22073 (when (or (org-element-nested-p elem next-elem)
22074 (and (eq (org-element-type next-elem) 'headline)
22075 (not (eq (org-element-type elem) 'headline))))
22076 (goto-char pos)
22077 (error "Cannot drag element forward"))
22078 ;; Compute new position of point: it's shifted by NEXT-ELEM
22079 ;; body's length (without final blanks) and by the length of
22080 ;; blanks between ELEM and NEXT-ELEM.
22081 (let ((size-next (- (save-excursion
22082 (goto-char (org-element-property :end next-elem))
22083 (skip-chars-backward " \r\t\n")
22084 (forward-line)
22085 ;; Small correction if buffer doesn't end
22086 ;; with a newline character.
22087 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22088 (org-element-property :begin next-elem)))
22089 (size-blank (- (org-element-property :end elem)
22090 (save-excursion
22091 (goto-char (org-element-property :end elem))
22092 (skip-chars-backward " \r\t\n")
22093 (forward-line)
22094 (point)))))
22095 (org-element-swap-A-B elem next-elem)
22096 (goto-char (+ pos size-next size-blank))))))
22098 ;;;###autoload
22099 (defun org-mark-element ()
22100 "Put point at beginning of this element, mark at end.
22102 Interactively, if this command is repeated or (in Transient Mark
22103 mode) if the mark is active, it marks the next element after the
22104 ones already marked."
22105 (interactive)
22106 (let (deactivate-mark)
22107 (if (and (org-called-interactively-p 'any)
22108 (or (and (eq last-command this-command) (mark t))
22109 (and transient-mark-mode mark-active)))
22110 (set-mark
22111 (save-excursion
22112 (goto-char (mark))
22113 (goto-char (org-element-property :end (org-element-at-point)))))
22114 (let ((element (org-element-at-point)))
22115 (end-of-line)
22116 (push-mark (org-element-property :end element) t t)
22117 (goto-char (org-element-property :begin element))))))
22119 ;;;###autoload
22120 (defun org-narrow-to-element ()
22121 "Narrow buffer to current element."
22122 (interactive)
22123 (let ((elem (org-element-at-point)))
22124 (cond
22125 ((eq (car elem) 'headline)
22126 (narrow-to-region
22127 (org-element-property :begin elem)
22128 (org-element-property :end elem)))
22129 ((memq (car elem) org-element-greater-elements)
22130 (narrow-to-region
22131 (org-element-property :contents-begin elem)
22132 (org-element-property :contents-end elem)))
22134 (narrow-to-region
22135 (org-element-property :begin elem)
22136 (org-element-property :end elem))))))
22138 ;;;###autoload
22139 (defun org-transpose-element ()
22140 "Transpose current and previous elements, keeping blank lines between.
22141 Point is moved after both elements."
22142 (interactive)
22143 (org-skip-whitespace)
22144 (let ((end (org-element-property :end (org-element-at-point))))
22145 (org-drag-element-backward)
22146 (goto-char end)))
22148 ;;;###autoload
22149 (defun org-unindent-buffer ()
22150 "Un-indent the visible part of the buffer.
22151 Relative indentation (between items, inside blocks, etc.) isn't
22152 modified."
22153 (interactive)
22154 (unless (eq major-mode 'org-mode)
22155 (error "Cannot un-indent a buffer not in Org mode"))
22156 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22157 unindent-tree ; For byte-compiler.
22158 (unindent-tree
22159 (function
22160 (lambda (contents)
22161 (mapc
22162 (lambda (element)
22163 (if (memq (org-element-type element) '(headline section))
22164 (funcall unindent-tree (org-element-contents element))
22165 (save-excursion
22166 (save-restriction
22167 (narrow-to-region
22168 (org-element-property :begin element)
22169 (org-element-property :end element))
22170 (org-do-remove-indentation)))))
22171 (reverse contents))))))
22172 (funcall unindent-tree (org-element-contents parse-tree))))
22174 (defun org-show-subtree ()
22175 "Show everything after this heading at deeper levels."
22176 (interactive)
22177 (outline-flag-region
22178 (point)
22179 (save-excursion
22180 (org-end-of-subtree t t))
22181 nil))
22183 (defun org-show-entry ()
22184 "Show the body directly following this heading.
22185 Show the heading too, if it is currently invisible."
22186 (interactive)
22187 (save-excursion
22188 (condition-case nil
22189 (progn
22190 (org-back-to-heading t)
22191 (outline-flag-region
22192 (max (point-min) (1- (point)))
22193 (save-excursion
22194 (if (re-search-forward
22195 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22196 (match-beginning 1)
22197 (point-max)))
22198 nil)
22199 (org-cycle-hide-drawers 'children))
22200 (error nil))))
22202 (defun org-make-options-regexp (kwds &optional extra)
22203 "Make a regular expression for keyword lines."
22204 (concat
22205 "^#\\+\\("
22206 (mapconcat 'regexp-quote kwds "\\|")
22207 (if extra (concat "\\|" extra))
22208 "\\):[ \t]*\\(.*\\)"))
22210 ;; Make isearch reveal the necessary context
22211 (defun org-isearch-end ()
22212 "Reveal context after isearch exits."
22213 (when isearch-success ; only if search was successful
22214 (if (featurep 'xemacs)
22215 ;; Under XEmacs, the hook is run in the correct place,
22216 ;; we directly show the context.
22217 (org-show-context 'isearch)
22218 ;; In Emacs the hook runs *before* restoring the overlays.
22219 ;; So we have to use a one-time post-command-hook to do this.
22220 ;; (Emacs 22 has a special variable, see function `org-mode')
22221 (unless (and (boundp 'isearch-mode-end-hook-quit)
22222 isearch-mode-end-hook-quit)
22223 ;; Only when the isearch was not quitted.
22224 (org-add-hook 'post-command-hook 'org-isearch-post-command
22225 'append 'local)))))
22227 (defun org-isearch-post-command ()
22228 "Remove self from hook, and show context."
22229 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22230 (org-show-context 'isearch))
22233 ;;;; Integration with and fixes for other packages
22235 ;;; Imenu support
22237 (defvar org-imenu-markers nil
22238 "All markers currently used by Imenu.")
22239 (make-variable-buffer-local 'org-imenu-markers)
22241 (defun org-imenu-new-marker (&optional pos)
22242 "Return a new marker for use by Imenu, and remember the marker."
22243 (let ((m (make-marker)))
22244 (move-marker m (or pos (point)))
22245 (push m org-imenu-markers)
22248 (defun org-imenu-get-tree ()
22249 "Produce the index for Imenu."
22250 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22251 (setq org-imenu-markers nil)
22252 (let* ((n org-imenu-depth)
22253 (re (concat "^" (org-get-limited-outline-regexp)))
22254 (subs (make-vector (1+ n) nil))
22255 (last-level 0)
22256 m level head)
22257 (save-excursion
22258 (save-restriction
22259 (widen)
22260 (goto-char (point-max))
22261 (while (re-search-backward re nil t)
22262 (setq level (org-reduced-level (funcall outline-level)))
22263 (when (and (<= level n)
22264 (looking-at org-complex-heading-regexp))
22265 (setq head (org-link-display-format
22266 (org-match-string-no-properties 4))
22267 m (org-imenu-new-marker))
22268 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22269 (if (>= level last-level)
22270 (push (cons head m) (aref subs level))
22271 (push (cons head (aref subs (1+ level))) (aref subs level))
22272 (loop for i from (1+ level) to n do (aset subs i nil)))
22273 (setq last-level level)))))
22274 (aref subs 1)))
22276 (eval-after-load "imenu"
22277 '(progn
22278 (add-hook 'imenu-after-jump-hook
22279 (lambda ()
22280 (if (derived-mode-p 'org-mode)
22281 (org-show-context 'org-goto))))))
22283 (defun org-link-display-format (link)
22284 "Replace a link with either the description, or the link target
22285 if no description is present"
22286 (save-match-data
22287 (if (string-match org-bracket-link-analytic-regexp link)
22288 (replace-match (if (match-end 5)
22289 (match-string 5 link)
22290 (concat (match-string 1 link)
22291 (match-string 3 link)))
22292 nil t link)
22293 link)))
22295 (defun org-toggle-link-display ()
22296 "Toggle the literal or descriptive display of links."
22297 (interactive)
22298 (if org-descriptive-links
22299 (progn (org-remove-from-invisibility-spec '(org-link))
22300 (org-restart-font-lock)
22301 (setq org-descriptive-links nil))
22302 (progn (add-to-invisibility-spec '(org-link))
22303 (org-restart-font-lock)
22304 (setq org-descriptive-links t))))
22306 ;; Speedbar support
22308 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22309 "Overlay marking the agenda restriction line in speedbar.")
22310 (overlay-put org-speedbar-restriction-lock-overlay
22311 'face 'org-agenda-restriction-lock)
22312 (overlay-put org-speedbar-restriction-lock-overlay
22313 'help-echo "Agendas are currently limited to this item.")
22314 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22316 (defun org-speedbar-set-agenda-restriction ()
22317 "Restrict future agenda commands to the location at point in speedbar.
22318 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22319 (interactive)
22320 (require 'org-agenda)
22321 (let (p m tp np dir txt)
22322 (cond
22323 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22324 'org-imenu t))
22325 (setq m (get-text-property p 'org-imenu-marker))
22326 (with-current-buffer (marker-buffer m)
22327 (goto-char m)
22328 (org-agenda-set-restriction-lock 'subtree)))
22329 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22330 'speedbar-function 'speedbar-find-file))
22331 (setq tp (previous-single-property-change
22332 (1+ p) 'speedbar-function)
22333 np (next-single-property-change
22334 tp 'speedbar-function)
22335 dir (speedbar-line-directory)
22336 txt (buffer-substring-no-properties (or tp (point-min))
22337 (or np (point-max))))
22338 (with-current-buffer (find-file-noselect
22339 (let ((default-directory dir))
22340 (expand-file-name txt)))
22341 (unless (derived-mode-p 'org-mode)
22342 (error "Cannot restrict to non-Org-mode file"))
22343 (org-agenda-set-restriction-lock 'file)))
22344 (t (error "Don't know how to restrict Org-mode's agenda")))
22345 (move-overlay org-speedbar-restriction-lock-overlay
22346 (point-at-bol) (point-at-eol))
22347 (setq current-prefix-arg nil)
22348 (org-agenda-maybe-redo)))
22350 (eval-after-load "speedbar"
22351 '(progn
22352 (speedbar-add-supported-extension ".org")
22353 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22354 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22355 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22356 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22357 (add-hook 'speedbar-visiting-tag-hook
22358 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22360 ;;; Fixes and Hacks for problems with other packages
22362 ;; Make flyspell not check words in links, to not mess up our keymap
22363 (defun org-mode-flyspell-verify ()
22364 "Don't let flyspell put overlays at active buttons, or on
22365 {todo,all-time,additional-option-like}-keywords."
22366 (let ((pos (max (1- (point)) (point-min)))
22367 (word (thing-at-point 'word)))
22368 (and (not (get-text-property pos 'keymap))
22369 (not (get-text-property pos 'org-no-flyspell))
22370 (not (member word org-todo-keywords-1))
22371 (not (member word org-all-time-keywords))
22372 (not (member word org-options-keywords))
22373 (not (member word (mapcar 'car org-startup-options)))
22374 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22376 (defun org-remove-flyspell-overlays-in (beg end)
22377 "Remove flyspell overlays in region."
22378 (and (org-bound-and-true-p flyspell-mode)
22379 (fboundp 'flyspell-delete-region-overlays)
22380 (flyspell-delete-region-overlays beg end))
22381 (add-text-properties beg end '(org-no-flyspell t)))
22383 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22384 (eval-after-load "bookmark"
22385 '(if (boundp 'bookmark-after-jump-hook)
22386 ;; We can use the hook
22387 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22388 ;; Hook not available, use advice
22389 (defadvice bookmark-jump (after org-make-visible activate)
22390 "Make the position visible."
22391 (org-bookmark-jump-unhide))))
22393 ;; Make sure saveplace shows the location if it was hidden
22394 (eval-after-load "saveplace"
22395 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22396 "Make the position visible."
22397 (org-bookmark-jump-unhide)))
22399 ;; Make sure ecb shows the location if it was hidden
22400 (eval-after-load "ecb"
22401 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22402 "Make hierarchy visible when jumping into location from ECB tree buffer."
22403 (if (derived-mode-p 'org-mode)
22404 (org-show-context))))
22406 (defun org-bookmark-jump-unhide ()
22407 "Unhide the current position, to show the bookmark location."
22408 (and (derived-mode-p 'org-mode)
22409 (or (outline-invisible-p)
22410 (save-excursion (goto-char (max (point-min) (1- (point))))
22411 (outline-invisible-p)))
22412 (org-show-context 'bookmark-jump)))
22414 ;; Make session.el ignore our circular variable
22415 (eval-after-load "session"
22416 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22418 ;;;; Experimental code
22420 (defun org-closed-in-range ()
22421 "Sparse tree of items closed in a certain time range.
22422 Still experimental, may disappear in the future."
22423 (interactive)
22424 ;; Get the time interval from the user.
22425 (let* ((time1 (org-float-time
22426 (org-read-date nil 'to-time nil "Starting date: ")))
22427 (time2 (org-float-time
22428 (org-read-date nil 'to-time nil "End date:")))
22429 ;; callback function
22430 (callback (lambda ()
22431 (let ((time
22432 (org-float-time
22433 (apply 'encode-time
22434 (org-parse-time-string
22435 (match-string 1))))))
22436 ;; check if time in interval
22437 (and (>= time time1) (<= time time2))))))
22438 ;; make tree, check each match with the callback
22439 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22441 ;;;; Finish up
22443 (provide 'org)
22445 (run-hooks 'org-load-hook)
22447 ;;; org.el ends here