Export back-ends: add entry in `org-export-dispatch' when loaded
[org-mode.git] / lisp / org.el
blobfef7597b0a330a1b947cd0712637f2bcd292f35b
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol "^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias)
102 (unless (boundp 'calendar-view-holidays-initially-flag)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially))
105 (unless (boundp 'calendar-view-diary-initially-flag)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially))
108 (unless (boundp 'diary-fancy-buffer)
109 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
111 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
115 (declare-function org-at-clock-log-p "org-clock" ())
116 (declare-function org-clock-timestamps-up "org-clock" ())
117 (declare-function org-clock-timestamps-down "org-clock" ())
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :version "24.1"
151 :type '(alist :tag "Babel Languages"
152 :key-type
153 (choice
154 (const :tag "Awk" awk)
155 (const :tag "C" C)
156 (const :tag "R" R)
157 (const :tag "Asymptote" asymptote)
158 (const :tag "Calc" calc)
159 (const :tag "Clojure" clojure)
160 (const :tag "CSS" css)
161 (const :tag "Ditaa" ditaa)
162 (const :tag "Dot" dot)
163 (const :tag "Emacs Lisp" emacs-lisp)
164 (const :tag "Fortran" fortran)
165 (const :tag "Gnuplot" gnuplot)
166 (const :tag "Haskell" haskell)
167 (const :tag "IO" io)
168 (const :tag "Java" java)
169 (const :tag "Javascript" js)
170 (const :tag "LaTeX" latex)
171 (const :tag "Ledger" ledger)
172 (const :tag "Lilypond" lilypond)
173 (const :tag "Lisp" lisp)
174 (const :tag "Maxima" maxima)
175 (const :tag "Matlab" matlab)
176 (const :tag "Mscgen" mscgen)
177 (const :tag "Ocaml" ocaml)
178 (const :tag "Octave" octave)
179 (const :tag "Org" org)
180 (const :tag "Perl" perl)
181 (const :tag "Pico Lisp" picolisp)
182 (const :tag "PlantUML" plantuml)
183 (const :tag "Python" python)
184 (const :tag "Ruby" ruby)
185 (const :tag "Sass" sass)
186 (const :tag "Scala" scala)
187 (const :tag "Scheme" scheme)
188 (const :tag "Screen" screen)
189 (const :tag "Shell Script" sh)
190 (const :tag "Shen" shen)
191 (const :tag "Sql" sql)
192 (const :tag "Sqlite" sqlite))
193 :value-type (boolean :tag "Activate" :value t)))
195 ;;;; Customization variables
196 (defcustom org-clone-delete-id nil
197 "Remove ID property of clones of a subtree.
198 When non-nil, clones of a subtree don't inherit the ID property.
199 Otherwise they inherit the ID property with a new unique
200 identifier."
201 :type 'boolean
202 :version "24.1"
203 :group 'org-id)
205 ;;; Version
206 (require 'org-compat)
207 (org-check-version)
208 ;;;###autoload
209 (defun org-version (&optional here full message)
210 "Show the org-mode version in the echo area.
211 With prefix argument HERE, insert it at point.
212 When FULL is non-nil, use a verbose version string.
213 When MESSAGE is non-nil, display a message with the version."
214 (interactive "P")
215 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
216 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
217 (org-trash (or
218 (and (fboundp 'org-release) (fboundp 'org-git-version))
219 (load (concat org-dir "org-version.el")
220 'noerror 'nomessage 'nosuffix)))
221 (org-version (org-release))
222 (git-version (org-git-version))
223 (version (format "Org-mode version %s (%s @ %s)"
224 org-version
225 git-version
226 (if org-install-dir
227 (if (string= org-dir org-install-dir)
228 org-install-dir
229 (concat "mixed installation! " org-install-dir " and " org-dir))
230 "org-install.el can not be found!")))
231 (_version (if full version org-version)))
232 (if (org-called-interactively-p 'interactive)
233 (if here
234 (insert version)
235 (message version))
236 (if message (message _version))
237 _version)))
239 (defconst org-version (org-version))
241 ;;; Compatibility constants
243 ;;; The custom variables
245 (defgroup org nil
246 "Outline-based notes management and organizer."
247 :tag "Org"
248 :group 'outlines
249 :group 'calendar)
251 (defcustom org-mode-hook nil
252 "Mode hook for Org-mode, run after the mode was turned on."
253 :group 'org
254 :type 'hook)
256 (defcustom org-load-hook nil
257 "Hook that is run after org.el has been loaded."
258 :group 'org
259 :type 'hook)
261 (defcustom org-log-buffer-setup-hook nil
262 "Hook that is run after an Org log buffer is created."
263 :group 'org
264 :version "24.1"
265 :type 'hook)
267 (defvar org-modules) ; defined below
268 (defvar org-modules-loaded nil
269 "Have the modules been loaded already?")
271 (defun org-load-modules-maybe (&optional force)
272 "Load all extensions listed in `org-modules'."
273 (when (or force (not org-modules-loaded))
274 (mapc (lambda (ext)
275 (condition-case nil (require ext)
276 (error (message "Problems while trying to load feature `%s'" ext))))
277 org-modules)
278 (setq org-modules-loaded t)))
280 (defun org-set-modules (var value)
281 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
282 (set var value)
283 (when (featurep 'org)
284 (org-load-modules-maybe 'force)))
286 (when (org-bound-and-true-p org-modules)
287 (let ((a (member 'org-infojs org-modules)))
288 (and a (setcar a 'org-jsinfo))))
290 (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)
291 "Modules that should always be loaded together with org.el.
292 If a description starts with <C>, the file is not part of Emacs
293 and loading it will require that you have downloaded and properly installed
294 the org-mode distribution.
296 You can also use this system to load external packages (i.e. neither Org
297 core modules, nor modules from the CONTRIB directory). Just add symbols
298 to the end of the list. If the package is called org-xyz.el, then you need
299 to add the symbol `xyz', and the package must have a call to
301 (provide 'org-xyz)"
302 :group 'org
303 :set 'org-set-modules
304 :type
305 '(set :greedy t
306 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
307 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
308 (const :tag " crypt: Encryption of subtrees" org-crypt)
309 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
310 (const :tag " docview: Links to doc-view buffers" org-docview)
311 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
312 (const :tag " id: Global IDs for identifying entries" org-id)
313 (const :tag " info: Links to Info nodes" org-info)
314 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
315 (const :tag " habit: Track your consistency with habits" org-habit)
316 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
317 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
318 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
319 (const :tag " mew Links to Mew folders/messages" org-mew)
320 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
321 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
322 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
323 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
324 (const :tag " vm: Links to VM folders/messages" org-vm)
325 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
326 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
327 (const :tag " mouse: Additional mouse support" org-mouse)
328 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
330 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
331 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
332 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
333 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
334 (const :tag "C collector: Collect properties into tables" org-collector)
335 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
336 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
337 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
338 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
339 (const :tag "C eval: Include command output as text" org-eval)
340 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
341 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
342 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
343 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
344 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
346 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
348 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
349 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
350 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
351 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
352 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
353 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
354 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
355 (const :tag "C mtags: Support for muse-like tags" org-mtags)
356 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
357 (const :tag "C registry: A registry for Org-mode links" org-registry)
358 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
359 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
360 (const :tag "C secretary: Team management with org-mode" org-secretary)
361 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
362 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
363 (const :tag "C track: Keep up with Org-mode development" org-track)
364 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
365 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
366 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
368 (defcustom org-support-shift-select nil
369 "Non-nil means make shift-cursor commands select text when possible.
371 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
372 start selecting a region, or enlarge regions started in this way.
373 In Org-mode, in special contexts, these same keys are used for
374 other purposes, important enough to compete with shift selection.
375 Org tries to balance these needs by supporting `shift-select-mode'
376 outside these special contexts, under control of this variable.
378 The default of this variable is nil, to avoid confusing behavior. Shifted
379 cursor keys will then execute Org commands in the following contexts:
380 - on a headline, changing TODO state (left/right) and priority (up/down)
381 - on a time stamp, changing the time
382 - in a plain list item, changing the bullet type
383 - in a property definition line, switching between allowed values
384 - in the BEGIN line of a clock table (changing the time block).
385 Outside these contexts, the commands will throw an error.
387 When this variable is t and the cursor is not in a special
388 context, Org-mode will support shift-selection for making and
389 enlarging regions. To make this more effective, the bullet
390 cycling will no longer happen anywhere in an item line, but only
391 if the cursor is exactly on the bullet.
393 If you set this variable to the symbol `always', then the keys
394 will not be special in headlines, property lines, and item lines,
395 to make shift selection work there as well. If this is what you
396 want, you can use the following alternative commands: `C-c C-t'
397 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
398 can be used to switch TODO sets, `C-c -' to cycle item bullet
399 types, and properties can be edited by hand or in column view.
401 However, when the cursor is on a timestamp, shift-cursor commands
402 will still edit the time stamp - this is just too good to give up.
404 XEmacs user should have this variable set to nil, because
405 `shift-select-mode' is in Emacs 23 or later only."
406 :group 'org
407 :type '(choice
408 (const :tag "Never" nil)
409 (const :tag "When outside special context" t)
410 (const :tag "Everywhere except timestamps" always)))
412 (defcustom org-loop-over-headlines-in-active-region nil
413 "Shall some commands act upon headlines in the active region?
415 When set to `t', some commands will be performed in all headlines
416 within the active region.
418 When set to `start-level', some commands will be performed in all
419 headlines within the active region, provided that these headlines
420 are of the same level than the first one.
422 When set to a string, those commands will be performed on the
423 matching headlines within the active region. Such string must be
424 a tags/property/todo match as it is used in the agenda tags view.
426 The list of commands is: `org-schedule', `org-deadline',
427 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
428 `org-archive-to-archive-sibling'. The archiving commands skip
429 already archived entries."
430 :type '(choice (const :tag "Don't loop" nil)
431 (const :tag "All headlines in active region" t)
432 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
433 (string :tag "Tags/Property/Todo matcher"))
434 :version "24.1"
435 :group 'org-todo
436 :group 'org-archive)
438 (defgroup org-startup nil
439 "Options concerning startup of Org-mode."
440 :tag "Org Startup"
441 :group 'org)
443 (defcustom org-startup-folded t
444 "Non-nil means entering Org-mode will switch to OVERVIEW.
445 This can also be configured on a per-file basis by adding one of
446 the following lines anywhere in the buffer:
448 #+STARTUP: fold (or `overview', this is equivalent)
449 #+STARTUP: nofold (or `showall', this is equivalent)
450 #+STARTUP: content
451 #+STARTUP: showeverything"
452 :group 'org-startup
453 :type '(choice
454 (const :tag "nofold: show all" nil)
455 (const :tag "fold: overview" t)
456 (const :tag "content: all headlines" content)
457 (const :tag "show everything, even drawers" showeverything)))
459 (defcustom org-startup-truncated t
460 "Non-nil means entering Org-mode will set `truncate-lines'.
461 This is useful since some lines containing links can be very long and
462 uninteresting. Also tables look terrible when wrapped."
463 :group 'org-startup
464 :type 'boolean)
466 (defcustom org-startup-indented nil
467 "Non-nil means turn on `org-indent-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
471 #+STARTUP: indent
472 #+STARTUP: noindent"
473 :group 'org-structure
474 :type '(choice
475 (const :tag "Not" nil)
476 (const :tag "Globally (slow on startup in large files)" t)))
478 (defcustom org-use-sub-superscripts t
479 "Non-nil means interpret \"_\" and \"^\" for export.
480 When this option is turned on, you can use TeX-like syntax for sub- and
481 superscripts. Several characters after \"_\" or \"^\" will be
482 considered as a single item - so grouping with {} is normally not
483 needed. For example, the following things will be parsed as single
484 sub- or superscripts.
486 10^24 or 10^tau several digits will be considered 1 item.
487 10^-12 or 10^-tau a leading sign with digits or a word
488 x^2-y^3 will be read as x^2 - y^3, because items are
489 terminated by almost any nonword/nondigit char.
490 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
492 Still, ambiguity is possible - so when in doubt use {} to enclose the
493 sub/superscript. If you set this variable to the symbol `{}',
494 the braces are *required* in order to trigger interpretations as
495 sub/superscript. This can be helpful in documents that need \"_\"
496 frequently in plain text.
498 Not all export backends support this, but HTML does.
500 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
501 :group 'org-startup
502 :group 'org-export-translation
503 :version "24.1"
504 :type '(choice
505 (const :tag "Always interpret" t)
506 (const :tag "Only with braces" {})
507 (const :tag "Never interpret" nil)))
509 (if (fboundp 'defvaralias)
510 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
513 (defcustom org-startup-with-beamer-mode nil
514 "Non-nil means turn on `org-beamer-mode' on startup.
515 This can also be configured on a per-file basis by adding one of
516 the following lines anywhere in the buffer:
518 #+STARTUP: beamer"
519 :group 'org-startup
520 :version "24.1"
521 :type 'boolean)
523 (defcustom org-startup-align-all-tables nil
524 "Non-nil means align all tables when visiting a file.
525 This is useful when the column width in tables is forced with <N> cookies
526 in table fields. Such tables will look correct only after the first re-align.
527 This can also be configured on a per-file basis by adding one of
528 the following lines anywhere in the buffer:
529 #+STARTUP: align
530 #+STARTUP: noalign"
531 :group 'org-startup
532 :type 'boolean)
534 (defcustom org-startup-with-inline-images nil
535 "Non-nil means show inline images when loading a new Org file.
536 This can also be configured on a per-file basis by adding one of
537 the following lines anywhere in the buffer:
538 #+STARTUP: inlineimages
539 #+STARTUP: noinlineimages"
540 :group 'org-startup
541 :version "24.1"
542 :type 'boolean)
544 (defcustom org-insert-mode-line-in-empty-file nil
545 "Non-nil means insert the first line setting Org-mode in empty files.
546 When the function `org-mode' is called interactively in an empty file, this
547 normally means that the file name does not automatically trigger Org-mode.
548 To ensure that the file will always be in Org-mode in the future, a
549 line enforcing Org-mode will be inserted into the buffer, if this option
550 has been set."
551 :group 'org-startup
552 :type 'boolean)
554 (defcustom org-replace-disputed-keys nil
555 "Non-nil means use alternative key bindings for some keys.
556 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
557 These keys are also used by other packages like shift-selection-mode'
558 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
559 If you want to use Org-mode together with one of these other modes,
560 or more generally if you would like to move some Org-mode commands to
561 other keys, set this variable and configure the keys with the variable
562 `org-disputed-keys'.
564 This option is only relevant at load-time of Org-mode, and must be set
565 *before* org.el is loaded. Changing it requires a restart of Emacs to
566 become effective."
567 :group 'org-startup
568 :type 'boolean)
570 (defcustom org-use-extra-keys nil
571 "Non-nil means use extra key sequence definitions for certain commands.
572 This happens automatically if you run XEmacs or if `window-system'
573 is nil. This variable lets you do the same manually. You must
574 set it before loading org.
576 Example: on Carbon Emacs 22 running graphically, with an external
577 keyboard on a Powerbook, the default way of setting M-left might
578 not work for either Alt or ESC. Setting this variable will make
579 it work for ESC."
580 :group 'org-startup
581 :type 'boolean)
583 (if (fboundp 'defvaralias)
584 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
586 (defcustom org-disputed-keys
587 '(([(shift up)] . [(meta p)])
588 ([(shift down)] . [(meta n)])
589 ([(shift left)] . [(meta -)])
590 ([(shift right)] . [(meta +)])
591 ([(control shift right)] . [(meta shift +)])
592 ([(control shift left)] . [(meta shift -)]))
593 "Keys for which Org-mode and other modes compete.
594 This is an alist, cars are the default keys, second element specifies
595 the alternative to use when `org-replace-disputed-keys' is t.
597 Keys can be specified in any syntax supported by `define-key'.
598 The value of this option takes effect only at Org-mode's startup,
599 therefore you'll have to restart Emacs to apply it after changing."
600 :group 'org-startup
601 :type 'alist)
603 (defun org-key (key)
604 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
605 Or return the original if not disputed.
606 Also apply the translations defined in `org-xemacs-key-equivalents'."
607 (when org-replace-disputed-keys
608 (let* ((nkey (key-description key))
609 (x (org-find-if (lambda (x)
610 (equal (key-description (car x)) nkey))
611 org-disputed-keys)))
612 (setq key (if x (cdr x) key))))
613 (when (featurep 'xemacs)
614 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
615 key)
617 (defun org-find-if (predicate seq)
618 (catch 'exit
619 (while seq
620 (if (funcall predicate (car seq))
621 (throw 'exit (car seq))
622 (pop seq)))))
624 (defun org-defkey (keymap key def)
625 "Define a key, possibly translated, as returned by `org-key'."
626 (define-key keymap (org-key key) def))
628 (defcustom org-ellipsis nil
629 "The ellipsis to use in the Org-mode outline.
630 When nil, just use the standard three dots. When a string, use that instead,
631 When a face, use the standard 3 dots, but with the specified face.
632 The change affects only Org-mode (which will then use its own display table).
633 Changing this requires executing `M-x org-mode' in a buffer to become
634 effective."
635 :group 'org-startup
636 :type '(choice (const :tag "Default" nil)
637 (face :tag "Face" :value org-warning)
638 (string :tag "String" :value "...#")))
640 (defvar org-display-table nil
641 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
643 (defgroup org-keywords nil
644 "Keywords in Org-mode."
645 :tag "Org Keywords"
646 :group 'org)
648 (defcustom org-deadline-string "DEADLINE:"
649 "String to mark deadline entries.
650 A deadline is this string, followed by a time stamp. Should be a word,
651 terminated by a colon. You can insert a schedule keyword and
652 a timestamp with \\[org-deadline].
653 Changes become only effective after restarting Emacs."
654 :group 'org-keywords
655 :type 'string)
657 (defcustom org-scheduled-string "SCHEDULED:"
658 "String to mark scheduled TODO entries.
659 A schedule is this string, followed by a time stamp. Should be a word,
660 terminated by a colon. You can insert a schedule keyword and
661 a timestamp with \\[org-schedule].
662 Changes become only effective after restarting Emacs."
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-closed-string "CLOSED:"
667 "String used as the prefix for timestamps logging closing a TODO entry."
668 :group 'org-keywords
669 :type 'string)
671 (defcustom org-clock-string "CLOCK:"
672 "String used as prefix for timestamps clocking work hours on an item."
673 :group 'org-keywords
674 :type 'string)
676 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
677 org-scheduled-string "\\|"
678 org-deadline-string "\\|"
679 org-closed-string "\\|"
680 org-clock-string "\\)")
681 "Matches a line with planning or clock info.")
683 (defcustom org-comment-string "COMMENT"
684 "Entries starting with this keyword will never be exported.
685 An entry can be toggled between COMMENT and normal with
686 \\[org-toggle-comment].
687 Changes become only effective after restarting Emacs."
688 :group 'org-keywords
689 :type 'string)
691 (defcustom org-quote-string "QUOTE"
692 "Entries starting with this keyword will be exported in fixed-width font.
693 Quoting applies only to the text in the entry following the headline, and does
694 not extend beyond the next headline, even if that is lower level.
695 An entry can be toggled between QUOTE and normal with
696 \\[org-toggle-fixed-width-section]."
697 :group 'org-keywords
698 :type 'string)
700 (defconst org-repeat-re
701 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
702 "Regular expression for specifying repeated events.
703 After a match, group 1 contains the repeat expression.")
705 (defgroup org-structure nil
706 "Options concerning the general structure of Org-mode files."
707 :tag "Org Structure"
708 :group 'org)
710 (defgroup org-reveal-location nil
711 "Options about how to make context of a location visible."
712 :tag "Org Reveal Location"
713 :group 'org-structure)
715 (defconst org-context-choice
716 '(choice
717 (const :tag "Always" t)
718 (const :tag "Never" nil)
719 (repeat :greedy t :tag "Individual contexts"
720 (cons
721 (choice :tag "Context"
722 (const agenda)
723 (const org-goto)
724 (const occur-tree)
725 (const tags-tree)
726 (const link-search)
727 (const mark-goto)
728 (const bookmark-jump)
729 (const isearch)
730 (const default))
731 (boolean))))
732 "Contexts for the reveal options.")
734 (defcustom org-show-hierarchy-above '((default . t))
735 "Non-nil means show full hierarchy when revealing a location.
736 Org-mode often shows locations in an org-mode file which might have
737 been invisible before. When this is set, the hierarchy of headings
738 above the exposed location is shown.
739 Turning this off for example for sparse trees makes them very compact.
740 Instead of t, this can also be an alist specifying this option for different
741 contexts. Valid contexts are
742 agenda when exposing an entry from the agenda
743 org-goto when using the command `org-goto' on key C-c C-j
744 occur-tree when using the command `org-occur' on key C-c /
745 tags-tree when constructing a sparse tree based on tags matches
746 link-search when exposing search matches associated with a link
747 mark-goto when exposing the jump goal of a mark
748 bookmark-jump when exposing a bookmark location
749 isearch when exiting from an incremental search
750 default default for all contexts not set explicitly"
751 :group 'org-reveal-location
752 :type org-context-choice)
754 (defcustom org-show-following-heading '((default . nil))
755 "Non-nil means show following heading when revealing a location.
756 Org-mode often shows locations in an org-mode file which might have
757 been invisible before. When this is set, the heading following the
758 match is shown.
759 Turning this off for example for sparse trees makes them very compact,
760 but makes it harder to edit the location of the match. In such a case,
761 use the command \\[org-reveal] to show more context.
762 Instead of t, this can also be an alist specifying this option for different
763 contexts. See `org-show-hierarchy-above' for valid contexts."
764 :group 'org-reveal-location
765 :type org-context-choice)
767 (defcustom org-show-siblings '((default . nil) (isearch t))
768 "Non-nil means show all sibling heading when revealing a location.
769 Org-mode often shows locations in an org-mode file which might have
770 been invisible before. When this is set, the sibling of the current entry
771 heading are all made visible. If `org-show-hierarchy-above' is t,
772 the same happens on each level of the hierarchy above the current entry.
774 By default this is on for the isearch context, off for all other contexts.
775 Turning this off for example for sparse trees makes them very compact,
776 but makes it harder to edit the location of the match. In such a case,
777 use the command \\[org-reveal] to show more context.
778 Instead of t, this can also be an alist specifying this option for different
779 contexts. See `org-show-hierarchy-above' for valid contexts."
780 :group 'org-reveal-location
781 :type org-context-choice)
783 (defcustom org-show-entry-below '((default . nil))
784 "Non-nil means show the entry below a headline when revealing a location.
785 Org-mode often shows locations in an org-mode file which might have
786 been invisible before. When this is set, the text below the headline that is
787 exposed is also shown.
789 By default this is off for all contexts.
790 Instead of t, this can also be an alist specifying this option for different
791 contexts. See `org-show-hierarchy-above' for valid contexts."
792 :group 'org-reveal-location
793 :type org-context-choice)
795 (defcustom org-indirect-buffer-display 'other-window
796 "How should indirect tree buffers be displayed?
797 This applies to indirect buffers created with the commands
798 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
799 Valid values are:
800 current-window Display in the current window
801 other-window Just display in another window.
802 dedicated-frame Create one new frame, and re-use it each time.
803 new-frame Make a new frame each time. Note that in this case
804 previously-made indirect buffers are kept, and you need to
805 kill these buffers yourself."
806 :group 'org-structure
807 :group 'org-agenda-windows
808 :type '(choice
809 (const :tag "In current window" current-window)
810 (const :tag "In current frame, other window" other-window)
811 (const :tag "Each time a new frame" new-frame)
812 (const :tag "One dedicated frame" dedicated-frame)))
814 (defcustom org-use-speed-commands nil
815 "Non-nil means activate single letter commands at beginning of a headline.
816 This may also be a function to test for appropriate locations where speed
817 commands should be active."
818 :group 'org-structure
819 :type '(choice
820 (const :tag "Never" nil)
821 (const :tag "At beginning of headline stars" t)
822 (function)))
824 (defcustom org-speed-commands-user nil
825 "Alist of additional speed commands.
826 This list will be checked before `org-speed-commands-default'
827 when the variable `org-use-speed-commands' is non-nil
828 and when the cursor is at the beginning of a headline.
829 The car if each entry is a string with a single letter, which must
830 be assigned to `self-insert-command' in the global map.
831 The cdr is either a command to be called interactively, a function
832 to be called, or a form to be evaluated.
833 An entry that is just a list with a single string will be interpreted
834 as a descriptive headline that will be added when listing the speed
835 commands in the Help buffer using the `?' speed command."
836 :group 'org-structure
837 :type '(repeat :value ("k" . ignore)
838 (choice :value ("k" . ignore)
839 (list :tag "Descriptive Headline" (string :tag "Headline"))
840 (cons :tag "Letter and Command"
841 (string :tag "Command letter")
842 (choice
843 (function)
844 (sexp))))))
846 (defgroup org-cycle nil
847 "Options concerning visibility cycling in Org-mode."
848 :tag "Org Cycle"
849 :group 'org-structure)
851 (defcustom org-cycle-skip-children-state-if-no-children t
852 "Non-nil means skip CHILDREN state in entries that don't have any."
853 :group 'org-cycle
854 :type 'boolean)
856 (defcustom org-cycle-max-level nil
857 "Maximum level which should still be subject to visibility cycling.
858 Levels higher than this will, for cycling, be treated as text, not a headline.
859 When `org-odd-levels-only' is set, a value of N in this variable actually
860 means 2N-1 stars as the limiting headline.
861 When nil, cycle all levels.
862 Note that the limiting level of cycling is also influenced by
863 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
864 `org-inlinetask-min-level' is, cycling will be limited to levels one less
865 than its value."
866 :group 'org-cycle
867 :type '(choice
868 (const :tag "No limit" nil)
869 (integer :tag "Maximum level")))
871 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
872 "Names of drawers. Drawers are not opened by cycling on the headline above.
873 Drawers only open with a TAB on the drawer line itself. A drawer looks like
874 this:
875 :DRAWERNAME:
876 .....
877 :END:
878 The drawer \"PROPERTIES\" is special for capturing properties through
879 the property API.
881 Drawers can be defined on the per-file basis with a line like:
883 #+DRAWERS: HIDDEN STATE PROPERTIES"
884 :group 'org-structure
885 :group 'org-cycle
886 :type '(repeat (string :tag "Drawer Name")))
888 (defcustom org-hide-block-startup nil
889 "Non-nil means entering Org-mode will fold all blocks.
890 This can also be set in on a per-file basis with
892 #+STARTUP: hideblocks
893 #+STARTUP: showblocks"
894 :group 'org-startup
895 :group 'org-cycle
896 :type 'boolean)
898 (defcustom org-cycle-global-at-bob nil
899 "Cycle globally if cursor is at beginning of buffer and not at a headline.
900 This makes it possible to do global cycling without having to use S-TAB or
901 \\[universal-argument] TAB. For this special case to work, the first line \
902 of the buffer
903 must not be a headline - it may be empty or some other text. When used in
904 this way, `org-cycle-hook' is disables temporarily, to make sure the
905 cursor stays at the beginning of the buffer.
906 When this option is nil, don't do anything special at the beginning
907 of the buffer."
908 :group 'org-cycle
909 :type 'boolean)
911 (defcustom org-cycle-level-after-item/entry-creation t
912 "Non-nil means cycle entry level or item indentation in new empty entries.
914 When the cursor is at the end of an empty headline, i.e with only stars
915 and maybe a TODO keyword, TAB will then switch the entry to become a child,
916 and then all possible ancestor states, before returning to the original state.
917 This makes data entry extremely fast: M-RET to create a new headline,
918 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
920 When the cursor is at the end of an empty plain list item, one TAB will
921 make it a subitem, two or more tabs will back up to make this an item
922 higher up in the item hierarchy."
923 :group 'org-cycle
924 :type 'boolean)
926 (defcustom org-cycle-emulate-tab t
927 "Where should `org-cycle' emulate TAB.
928 nil Never
929 white Only in completely white lines
930 whitestart Only at the beginning of lines, before the first non-white char
931 t Everywhere except in headlines
932 exc-hl-bol Everywhere except at the start of a headline
933 If TAB is used in a place where it does not emulate TAB, the current subtree
934 visibility is cycled."
935 :group 'org-cycle
936 :type '(choice (const :tag "Never" nil)
937 (const :tag "Only in completely white lines" white)
938 (const :tag "Before first char in a line" whitestart)
939 (const :tag "Everywhere except in headlines" t)
940 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
943 (defcustom org-cycle-separator-lines 2
944 "Number of empty lines needed to keep an empty line between collapsed trees.
945 If you leave an empty line between the end of a subtree and the following
946 headline, this empty line is hidden when the subtree is folded.
947 Org-mode will leave (exactly) one empty line visible if the number of
948 empty lines is equal or larger to the number given in this variable.
949 So the default 2 means at least 2 empty lines after the end of a subtree
950 are needed to produce free space between a collapsed subtree and the
951 following headline.
953 If the number is negative, and the number of empty lines is at least -N,
954 all empty lines are shown.
956 Special case: when 0, never leave empty lines in collapsed view."
957 :group 'org-cycle
958 :type 'integer)
959 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
961 (defcustom org-pre-cycle-hook nil
962 "Hook that is run before visibility cycling is happening.
963 The function(s) in this hook must accept a single argument which indicates
964 the new state that will be set right after running this hook. The
965 argument is a symbol. Before a global state change, it can have the values
966 `overview', `content', or `all'. Before a local state change, it can have
967 the values `folded', `children', or `subtree'."
968 :group 'org-cycle
969 :type 'hook)
971 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
972 org-cycle-hide-drawers
973 org-cycle-show-empty-lines
974 org-optimize-window-after-visibility-change)
975 "Hook that is run after `org-cycle' has changed the buffer visibility.
976 The function(s) in this hook must accept a single argument which indicates
977 the new state that was set by the most recent `org-cycle' command. The
978 argument is a symbol. After a global state change, it can have the values
979 `overview', `content', or `all'. After a local state change, it can have
980 the values `folded', `children', or `subtree'."
981 :group 'org-cycle
982 :type 'hook)
984 (defgroup org-edit-structure nil
985 "Options concerning structure editing in Org-mode."
986 :tag "Org Edit Structure"
987 :group 'org-structure)
989 (defcustom org-odd-levels-only nil
990 "Non-nil means skip even levels and only use odd levels for the outline.
991 This has the effect that two stars are being added/taken away in
992 promotion/demotion commands. It also influences how levels are
993 handled by the exporters.
994 Changing it requires restart of `font-lock-mode' to become effective
995 for fontification also in regions already fontified.
996 You may also set this on a per-file basis by adding one of the following
997 lines to the buffer:
999 #+STARTUP: odd
1000 #+STARTUP: oddeven"
1001 :group 'org-edit-structure
1002 :group 'org-appearance
1003 :type 'boolean)
1005 (defcustom org-adapt-indentation t
1006 "Non-nil means adapt indentation to outline node level.
1008 When this variable is set, Org assumes that you write outlines by
1009 indenting text in each node to align with the headline (after the stars).
1010 The following issues are influenced by this variable:
1012 - When this is set and the *entire* text in an entry is indented, the
1013 indentation is increased by one space in a demotion command, and
1014 decreased by one in a promotion command. If any line in the entry
1015 body starts with text at column 0, indentation is not changed at all.
1017 - Property drawers and planning information is inserted indented when
1018 this variable s set. When nil, they will not be indented.
1020 - TAB indents a line relative to context. The lines below a headline
1021 will be indented when this variable is set.
1023 Note that this is all about true indentation, by adding and removing
1024 space characters. See also `org-indent.el' which does level-dependent
1025 indentation in a virtual way, i.e. at display time in Emacs."
1026 :group 'org-edit-structure
1027 :type 'boolean)
1029 (defcustom org-special-ctrl-a/e nil
1030 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1032 When t, `C-a' will bring back the cursor to the beginning of the
1033 headline text, i.e. after the stars and after a possible TODO
1034 keyword. In an item, this will be the position after bullet and
1035 check-box, if any. When the cursor is already at that position,
1036 another `C-a' will bring it to the beginning of the line.
1038 `C-e' will jump to the end of the headline, ignoring the presence
1039 of tags in the headline. A second `C-e' will then jump to the
1040 true end of the line, after any tags. This also means that, when
1041 this variable is non-nil, `C-e' also will never jump beyond the
1042 end of the heading of a folded section, i.e. not after the
1043 ellipses.
1045 When set to the symbol `reversed', the first `C-a' or `C-e' works
1046 normally, going to the true line boundary first. Only a directly
1047 following, identical keypress will bring the cursor to the
1048 special positions.
1050 This may also be a cons cell where the behavior for `C-a' and
1051 `C-e' is set separately."
1052 :group 'org-edit-structure
1053 :type '(choice
1054 (const :tag "off" nil)
1055 (const :tag "on: after stars/bullet and before tags first" t)
1056 (const :tag "reversed: true line boundary first" reversed)
1057 (cons :tag "Set C-a and C-e separately"
1058 (choice :tag "Special C-a"
1059 (const :tag "off" nil)
1060 (const :tag "on: after stars/bullet first" t)
1061 (const :tag "reversed: before stars/bullet first" reversed))
1062 (choice :tag "Special C-e"
1063 (const :tag "off" nil)
1064 (const :tag "on: before tags first" t)
1065 (const :tag "reversed: after tags first" reversed)))))
1066 (if (fboundp 'defvaralias)
1067 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1069 (defcustom org-special-ctrl-k nil
1070 "Non-nil means `C-k' will behave specially in headlines.
1071 When nil, `C-k' will call the default `kill-line' command.
1072 When t, the following will happen while the cursor is in the headline:
1074 - When the cursor is at the beginning of a headline, kill the entire
1075 line and possible the folded subtree below the line.
1076 - When in the middle of the headline text, kill the headline up to the tags.
1077 - When after the headline text, kill the tags."
1078 :group 'org-edit-structure
1079 :type 'boolean)
1081 (defcustom org-ctrl-k-protect-subtree nil
1082 "Non-nil means, do not delete a hidden subtree with C-k.
1083 When set to the symbol `error', simply throw an error when C-k is
1084 used to kill (part-of) a headline that has hidden text behind it.
1085 Any other non-nil value will result in a query to the user, if it is
1086 OK to kill that hidden subtree. When nil, kill without remorse."
1087 :group 'org-edit-structure
1088 :version "24.1"
1089 :type '(choice
1090 (const :tag "Do not protect hidden subtrees" nil)
1091 (const :tag "Protect hidden subtrees with a security query" t)
1092 (const :tag "Never kill a hidden subtree with C-k" error)))
1094 (defcustom org-catch-invisible-edits nil
1095 "Check if in invisible region before inserting or deleting a character.
1096 Valid values are:
1098 nil Do not check, so just do invisible edits.
1099 error Throw an error and do nothing.
1100 show Make point visible, and do the requested edit.
1101 show-and-error Make point visible, then throw an error and abort the edit.
1102 smart Make point visible, and do insertion/deletion if it is
1103 adjacent to visible text and the change feels predictable.
1104 Never delete a previously invisible character or add in the
1105 middle or right after an invisible region. Basically, this
1106 allows insertion and backward-delete right before ellipses.
1107 FIXME: maybe in this case we should not even show?"
1108 :group 'org-edit-structure
1109 :version "24.1"
1110 :type '(choice
1111 (const :tag "Do not check" nil)
1112 (const :tag "Throw error when trying to edit" error)
1113 (const :tag "Unhide, but do not do the edit" show-and-error)
1114 (const :tag "Show invisible part and do the edit" show)
1115 (const :tag "Be smart and do the right thing" smart)))
1117 (defcustom org-yank-folded-subtrees t
1118 "Non-nil means when yanking subtrees, fold them.
1119 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1120 it starts with a heading and all other headings in it are either children
1121 or siblings, then fold all the subtrees. However, do this only if no
1122 text after the yank would be swallowed into a folded tree by this action."
1123 :group 'org-edit-structure
1124 :type 'boolean)
1126 (defcustom org-yank-adjusted-subtrees nil
1127 "Non-nil means when yanking subtrees, adjust the level.
1128 With this setting, `org-paste-subtree' is used to insert the subtree, see
1129 this function for details."
1130 :group 'org-edit-structure
1131 :type 'boolean)
1133 (defcustom org-M-RET-may-split-line '((default . t))
1134 "Non-nil means M-RET will split the line at the cursor position.
1135 When nil, it will go to the end of the line before making a
1136 new line.
1137 You may also set this option in a different way for different
1138 contexts. Valid contexts are:
1140 headline when creating a new headline
1141 item when creating a new item
1142 table in a table field
1143 default the value to be used for all contexts not explicitly
1144 customized"
1145 :group 'org-structure
1146 :group 'org-table
1147 :type '(choice
1148 (const :tag "Always" t)
1149 (const :tag "Never" nil)
1150 (repeat :greedy t :tag "Individual contexts"
1151 (cons
1152 (choice :tag "Context"
1153 (const headline)
1154 (const item)
1155 (const table)
1156 (const default))
1157 (boolean)))))
1160 (defcustom org-insert-heading-respect-content nil
1161 "Non-nil means insert new headings after the current subtree.
1162 When nil, the new heading is created directly after the current line.
1163 The commands \\[org-insert-heading-respect-content] and
1164 \\[org-insert-todo-heading-respect-content] turn this variable on
1165 for the duration of the command."
1166 :group 'org-structure
1167 :type 'boolean)
1169 (defcustom org-blank-before-new-entry '((heading . auto)
1170 (plain-list-item . auto))
1171 "Should `org-insert-heading' leave a blank line before new heading/item?
1172 The value is an alist, with `heading' and `plain-list-item' as CAR,
1173 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1174 which case Org will look at the surrounding headings/items and try to
1175 make an intelligent decision whether to insert a blank line or not.
1177 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1178 set, the setting here is ignored and no empty line is inserted, to avoid
1179 breaking the list structure."
1180 :group 'org-edit-structure
1181 :type '(list
1182 (cons (const heading)
1183 (choice (const :tag "Never" nil)
1184 (const :tag "Always" t)
1185 (const :tag "Auto" auto)))
1186 (cons (const plain-list-item)
1187 (choice (const :tag "Never" nil)
1188 (const :tag "Always" t)
1189 (const :tag "Auto" auto)))))
1191 (defcustom org-insert-heading-hook nil
1192 "Hook being run after inserting a new heading."
1193 :group 'org-edit-structure
1194 :type 'hook)
1196 (defcustom org-enable-fixed-width-editor t
1197 "Non-nil means lines starting with \":\" are treated as fixed-width.
1198 This currently only means they are never auto-wrapped.
1199 When nil, such lines will be treated like ordinary lines.
1200 See also the QUOTE keyword."
1201 :group 'org-edit-structure
1202 :type 'boolean)
1204 (defcustom org-goto-auto-isearch t
1205 "Non-nil means typing characters in `org-goto' starts incremental search."
1206 :group 'org-edit-structure
1207 :type 'boolean)
1209 (defgroup org-sparse-trees nil
1210 "Options concerning sparse trees in Org-mode."
1211 :tag "Org Sparse Trees"
1212 :group 'org-structure)
1214 (defcustom org-highlight-sparse-tree-matches t
1215 "Non-nil means highlight all matches that define a sparse tree.
1216 The highlights will automatically disappear the next time the buffer is
1217 changed by an edit command."
1218 :group 'org-sparse-trees
1219 :type 'boolean)
1221 (defcustom org-remove-highlights-with-change t
1222 "Non-nil means any change to the buffer will remove temporary highlights.
1223 Such highlights are created by `org-occur' and `org-clock-display'.
1224 When nil, `C-c C-c needs to be used to get rid of the highlights.
1225 The highlights created by `org-preview-latex-fragment' always need
1226 `C-c C-c' to be removed."
1227 :group 'org-sparse-trees
1228 :group 'org-time
1229 :type 'boolean)
1232 (defcustom org-occur-hook '(org-first-headline-recenter)
1233 "Hook that is run after `org-occur' has constructed a sparse tree.
1234 This can be used to recenter the window to show as much of the structure
1235 as possible."
1236 :group 'org-sparse-trees
1237 :type 'hook)
1239 (defgroup org-imenu-and-speedbar nil
1240 "Options concerning imenu and speedbar in Org-mode."
1241 :tag "Org Imenu and Speedbar"
1242 :group 'org-structure)
1244 (defcustom org-imenu-depth 2
1245 "The maximum level for Imenu access to Org-mode headlines.
1246 This also applied for speedbar access."
1247 :group 'org-imenu-and-speedbar
1248 :type 'integer)
1250 (defgroup org-table nil
1251 "Options concerning tables in Org-mode."
1252 :tag "Org Table"
1253 :group 'org)
1255 (defcustom org-enable-table-editor 'optimized
1256 "Non-nil means lines starting with \"|\" are handled by the table editor.
1257 When nil, such lines will be treated like ordinary lines.
1259 When equal to the symbol `optimized', the table editor will be optimized to
1260 do the following:
1261 - Automatic overwrite mode in front of whitespace in table fields.
1262 This makes the structure of the table stay in tact as long as the edited
1263 field does not exceed the column width.
1264 - Minimize the number of realigns. Normally, the table is aligned each time
1265 TAB or RET are pressed to move to another field. With optimization this
1266 happens only if changes to a field might have changed the column width.
1267 Optimization requires replacing the functions `self-insert-command',
1268 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1269 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1270 very good at guessing when a re-align will be necessary, but you can always
1271 force one with \\[org-ctrl-c-ctrl-c].
1273 If you would like to use the optimized version in Org-mode, but the
1274 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1276 This variable can be used to turn on and off the table editor during a session,
1277 but in order to toggle optimization, a restart is required.
1279 See also the variable `org-table-auto-blank-field'."
1280 :group 'org-table
1281 :type '(choice
1282 (const :tag "off" nil)
1283 (const :tag "on" t)
1284 (const :tag "on, optimized" optimized)))
1286 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1287 (version<= emacs-version "24.1"))
1288 "Non-nil means cluster self-insert commands for undo when possible.
1289 If this is set, then, like in the Emacs command loop, 20 consecutive
1290 characters will be undone together.
1291 This is configurable, because there is some impact on typing performance."
1292 :group 'org-table
1293 :type 'boolean)
1295 (defcustom org-table-tab-recognizes-table.el t
1296 "Non-nil means TAB will automatically notice a table.el table.
1297 When it sees such a table, it moves point into it and - if necessary -
1298 calls `table-recognize-table'."
1299 :group 'org-table-editing
1300 :type 'boolean)
1302 (defgroup org-link nil
1303 "Options concerning links in Org-mode."
1304 :tag "Org Link"
1305 :group 'org)
1307 (defvar org-link-abbrev-alist-local nil
1308 "Buffer-local version of `org-link-abbrev-alist', which see.
1309 The value of this is taken from the #+LINK lines.")
1310 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1312 (defcustom org-link-abbrev-alist nil
1313 "Alist of link abbreviations.
1314 The car of each element is a string, to be replaced at the start of a link.
1315 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1316 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1318 [[linkkey:tag][description]]
1320 The 'linkkey' must be a word word, starting with a letter, followed
1321 by letters, numbers, '-' or '_'.
1323 If REPLACE is a string, the tag will simply be appended to create the link.
1324 If the string contains \"%s\", the tag will be inserted there. If the string
1325 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1326 at that point (see the function `url-hexify-string'). If the string contains
1327 the specifier \"%(my-function)\", then the custom function `my-function' will
1328 be invoked: this function takes the tag as its only argument and must return
1329 a string.
1331 REPLACE may also be a function that will be called with the tag as the
1332 only argument to create the link, which should be returned as a string.
1334 See the manual for examples."
1335 :group 'org-link
1336 :type '(repeat
1337 (cons
1338 (string :tag "Protocol")
1339 (choice
1340 (string :tag "Format")
1341 (function)))))
1343 (defcustom org-descriptive-links t
1344 "Non-nil means Org will display descriptive links.
1345 E.g. [[http://orgmode.org][Org website]] will be displayed as
1346 \"Org Website\", hiding the link itself and just displaying its
1347 description. When set to `nil', Org will display the full links
1348 literally.
1350 You can interactively set the value of this variable by calling
1351 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1352 :group 'org-link
1353 :type 'boolean)
1355 (defcustom org-link-file-path-type 'adaptive
1356 "How the path name in file links should be stored.
1357 Valid values are:
1359 relative Relative to the current directory, i.e. the directory of the file
1360 into which the link is being inserted.
1361 absolute Absolute path, if possible with ~ for home directory.
1362 noabbrev Absolute path, no abbreviation of home directory.
1363 adaptive Use relative path for files in the current directory and sub-
1364 directories of it. For other files, use an absolute path."
1365 :group 'org-link
1366 :type '(choice
1367 (const relative)
1368 (const absolute)
1369 (const noabbrev)
1370 (const adaptive)))
1372 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1373 "Types of links that should be activated in Org-mode files.
1374 This is a list of symbols, each leading to the activation of a certain link
1375 type. In principle, it does not hurt to turn on most link types - there may
1376 be a small gain when turning off unused link types. The types are:
1378 bracket The recommended [[link][description]] or [[link]] links with hiding.
1379 angle Links in angular brackets that may contain whitespace like
1380 <bbdb:Carsten Dominik>.
1381 plain Plain links in normal text, no whitespace, like http://google.com.
1382 radio Text that is matched by a radio target, see manual for details.
1383 tag Tag settings in a headline (link to tag search).
1384 date Time stamps (link to calendar).
1385 footnote Footnote labels.
1387 Changing this variable requires a restart of Emacs to become effective."
1388 :group 'org-link
1389 :type '(set :greedy t
1390 (const :tag "Double bracket links" bracket)
1391 (const :tag "Angular bracket links" angle)
1392 (const :tag "Plain text links" plain)
1393 (const :tag "Radio target matches" radio)
1394 (const :tag "Tags" tag)
1395 (const :tag "Timestamps" date)
1396 (const :tag "Footnotes" footnote)))
1398 (defcustom org-make-link-description-function nil
1399 "Function to use to generate link descriptions from links.
1400 If nil the link location will be used. This function must take
1401 two parameters; the first is the link and the second the
1402 description `org-insert-link' has generated, and should return the
1403 description to use."
1404 :group 'org-link
1405 :type 'function)
1407 (defgroup org-link-store nil
1408 "Options concerning storing links in Org-mode."
1409 :tag "Org Store Link"
1410 :group 'org-link)
1412 (defcustom org-url-hexify-p t
1413 "When non-nil, hexify URL when creating a link."
1414 :type 'boolean
1415 ;; :version "24.3"
1416 :group 'org-link-store)
1418 (defcustom org-email-link-description-format "Email %c: %.30s"
1419 "Format of the description part of a link to an email or usenet message.
1420 The following %-escapes will be replaced by corresponding information:
1422 %F full \"From\" field
1423 %f name, taken from \"From\" field, address if no name
1424 %T full \"To\" field
1425 %t first name in \"To\" field, address if no name
1426 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1427 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1428 %s subject
1429 %d date
1430 %m message-id.
1432 You may use normal field width specification between the % and the letter.
1433 This is for example useful to limit the length of the subject.
1435 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1436 :group 'org-link-store
1437 :type 'string)
1439 (defcustom org-from-is-user-regexp
1440 (let (r1 r2)
1441 (when (and user-mail-address (not (string= user-mail-address "")))
1442 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1443 (when (and user-full-name (not (string= user-full-name "")))
1444 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1445 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1446 "Regexp matched against the \"From:\" header of an email or usenet message.
1447 It should match if the message is from the user him/herself."
1448 :group 'org-link-store
1449 :type 'regexp)
1451 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1452 "Non-nil means storing a link to an Org file will use entry IDs.
1454 Note that before this variable is even considered, org-id must be loaded,
1455 so please customize `org-modules' and turn it on.
1457 The variable can have the following values:
1459 t Create an ID if needed to make a link to the current entry.
1461 create-if-interactive
1462 If `org-store-link' is called directly (interactively, as a user
1463 command), do create an ID to support the link. But when doing the
1464 job for remember, only use the ID if it already exists. The
1465 purpose of this setting is to avoid proliferation of unwanted
1466 IDs, just because you happen to be in an Org file when you
1467 call `org-capture' that automatically and preemptively creates a
1468 link. If you do want to get an ID link in a remember template to
1469 an entry not having an ID, create it first by explicitly creating
1470 a link to it, using `C-c C-l' first.
1472 create-if-interactive-and-no-custom-id
1473 Like create-if-interactive, but do not create an ID if there is
1474 a CUSTOM_ID property defined in the entry. This is the default.
1476 use-existing
1477 Use existing ID, do not create one.
1479 nil Never use an ID to make a link, instead link using a text search for
1480 the headline text."
1481 :group 'org-link-store
1482 :type '(choice
1483 (const :tag "Create ID to make link" t)
1484 (const :tag "Create if storing link interactively"
1485 create-if-interactive)
1486 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1487 create-if-interactive-and-no-custom-id)
1488 (const :tag "Only use existing" use-existing)
1489 (const :tag "Do not use ID to create link" nil)))
1491 (defcustom org-context-in-file-links t
1492 "Non-nil means file links from `org-store-link' contain context.
1493 A search string will be added to the file name with :: as separator and
1494 used to find the context when the link is activated by the command
1495 `org-open-at-point'. When this option is t, the entire active region
1496 will be placed in the search string of the file link. If set to a
1497 positive integer, only the first n lines of context will be stored.
1499 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1500 negates this setting for the duration of the command."
1501 :group 'org-link-store
1502 :type '(choice boolean integer))
1504 (defcustom org-keep-stored-link-after-insertion nil
1505 "Non-nil means keep link in list for entire session.
1507 The command `org-store-link' adds a link pointing to the current
1508 location to an internal list. These links accumulate during a session.
1509 The command `org-insert-link' can be used to insert links into any
1510 Org-mode file (offering completion for all stored links). When this
1511 option is nil, every link which has been inserted once using \\[org-insert-link]
1512 will be removed from the list, to make completing the unused links
1513 more efficient."
1514 :group 'org-link-store
1515 :type 'boolean)
1517 (defgroup org-link-follow nil
1518 "Options concerning following links in Org-mode."
1519 :tag "Org Follow Link"
1520 :group 'org-link)
1522 (defcustom org-link-translation-function nil
1523 "Function to translate links with different syntax to Org syntax.
1524 This can be used to translate links created for example by the Planner
1525 or emacs-wiki packages to Org syntax.
1526 The function must accept two parameters, a TYPE containing the link
1527 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1528 which is everything after the link protocol. It should return a cons
1529 with possibly modified values of type and path.
1530 Org contains a function for this, so if you set this variable to
1531 `org-translate-link-from-planner', you should be able follow many
1532 links created by planner."
1533 :group 'org-link-follow
1534 :type 'function)
1536 (defcustom org-follow-link-hook nil
1537 "Hook that is run after a link has been followed."
1538 :group 'org-link-follow
1539 :type 'hook)
1541 (defcustom org-tab-follows-link nil
1542 "Non-nil means on links TAB will follow the link.
1543 Needs to be set before org.el is loaded.
1544 This really should not be used, it does not make sense, and the
1545 implementation is bad."
1546 :group 'org-link-follow
1547 :type 'boolean)
1549 (defcustom org-return-follows-link nil
1550 "Non-nil means on links RET will follow the link."
1551 :group 'org-link-follow
1552 :type 'boolean)
1554 (defcustom org-mouse-1-follows-link
1555 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1556 "Non-nil means mouse-1 on a link will follow the link.
1557 A longer mouse click will still set point. Does not work on XEmacs.
1558 Needs to be set before org.el is loaded."
1559 :group 'org-link-follow
1560 :type 'boolean)
1562 (defcustom org-mark-ring-length 4
1563 "Number of different positions to be recorded in the ring.
1564 Changing this requires a restart of Emacs to work correctly."
1565 :group 'org-link-follow
1566 :type 'integer)
1568 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1569 "Non-nil means internal links in Org files must exactly match a headline.
1570 When nil, the link search tries to match a phrase with all words
1571 in the search text."
1572 :group 'org-link-follow
1573 :version "24.1"
1574 :type '(choice
1575 (const :tag "Use fuzzy text search" nil)
1576 (const :tag "Match only exact headline" t)
1577 (const :tag "Match exact headline or query to create it"
1578 query-to-create)))
1580 (defcustom org-link-frame-setup
1581 '((vm . vm-visit-folder-other-frame)
1582 (vm-imap . vm-visit-imap-folder-other-frame)
1583 (gnus . org-gnus-no-new-news)
1584 (file . find-file-other-window)
1585 (wl . wl-other-frame))
1586 "Setup the frame configuration for following links.
1587 When following a link with Emacs, it may often be useful to display
1588 this link in another window or frame. This variable can be used to
1589 set this up for the different types of links.
1590 For VM, use any of
1591 `vm-visit-folder'
1592 `vm-visit-folder-other-window'
1593 `vm-visit-folder-other-frame'
1594 For Gnus, use any of
1595 `gnus'
1596 `gnus-other-frame'
1597 `org-gnus-no-new-news'
1598 For FILE, use any of
1599 `find-file'
1600 `find-file-other-window'
1601 `find-file-other-frame'
1602 For Wanderlust use any of
1603 `wl'
1604 `wl-other-frame'
1605 For the calendar, use the variable `calendar-setup'.
1606 For BBDB, it is currently only possible to display the matches in
1607 another window."
1608 :group 'org-link-follow
1609 :type '(list
1610 (cons (const vm)
1611 (choice
1612 (const vm-visit-folder)
1613 (const vm-visit-folder-other-window)
1614 (const vm-visit-folder-other-frame)))
1615 (cons (const gnus)
1616 (choice
1617 (const gnus)
1618 (const gnus-other-frame)
1619 (const org-gnus-no-new-news)))
1620 (cons (const file)
1621 (choice
1622 (const find-file)
1623 (const find-file-other-window)
1624 (const find-file-other-frame)))
1625 (cons (const wl)
1626 (choice
1627 (const wl)
1628 (const wl-other-frame)))))
1630 (defcustom org-display-internal-link-with-indirect-buffer nil
1631 "Non-nil means use indirect buffer to display infile links.
1632 Activating internal links (from one location in a file to another location
1633 in the same file) normally just jumps to the location. When the link is
1634 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1635 is displayed in
1636 another window. When this option is set, the other window actually displays
1637 an indirect buffer clone of the current buffer, to avoid any visibility
1638 changes to the current buffer."
1639 :group 'org-link-follow
1640 :type 'boolean)
1642 (defcustom org-open-non-existing-files nil
1643 "Non-nil means `org-open-file' will open non-existing files.
1644 When nil, an error will be generated.
1645 This variable applies only to external applications because they
1646 might choke on non-existing files. If the link is to a file that
1647 will be opened in Emacs, the variable is ignored."
1648 :group 'org-link-follow
1649 :type 'boolean)
1651 (defcustom org-open-directory-means-index-dot-org nil
1652 "Non-nil means a link to a directory really means to index.org.
1653 When nil, following a directory link will run dired or open a finder/explorer
1654 window on that directory."
1655 :group 'org-link-follow
1656 :type 'boolean)
1658 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1659 "Function and arguments to call for following mailto links.
1660 This is a list with the first element being a Lisp function, and the
1661 remaining elements being arguments to the function. In string arguments,
1662 %a will be replaced by the address, and %s will be replaced by the subject
1663 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1664 :group 'org-link-follow
1665 :type '(choice
1666 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1667 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1668 (const :tag "message-mail" (message-mail "%a" "%s"))
1669 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1671 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1672 "Non-nil means ask for confirmation before executing shell links.
1673 Shell links can be dangerous: just think about a link
1675 [[shell:rm -rf ~/*][Google Search]]
1677 This link would show up in your Org-mode document as \"Google Search\",
1678 but really it would remove your entire home directory.
1679 Therefore we advise against setting this variable to nil.
1680 Just change it to `y-or-n-p' if you want to confirm with a
1681 single keystroke rather than having to type \"yes\"."
1682 :group 'org-link-follow
1683 :type '(choice
1684 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1685 (const :tag "with y-or-n (faster)" y-or-n-p)
1686 (const :tag "no confirmation (dangerous)" nil)))
1687 (put 'org-confirm-shell-link-function
1688 'safe-local-variable
1689 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1691 (defcustom org-confirm-shell-link-not-regexp ""
1692 "A regexp to skip confirmation for shell links."
1693 :group 'org-link-follow
1694 :version "24.1"
1695 :type 'regexp)
1697 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1698 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1699 Elisp links can be dangerous: just think about a link
1701 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1703 This link would show up in your Org-mode document as \"Google Search\",
1704 but really it would remove your entire home directory.
1705 Therefore we advise against setting this variable to nil.
1706 Just change it to `y-or-n-p' if you want to confirm with a
1707 single keystroke rather than having to type \"yes\"."
1708 :group 'org-link-follow
1709 :type '(choice
1710 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1711 (const :tag "with y-or-n (faster)" y-or-n-p)
1712 (const :tag "no confirmation (dangerous)" nil)))
1713 (put 'org-confirm-shell-link-function
1714 'safe-local-variable
1715 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1717 (defcustom org-confirm-elisp-link-not-regexp ""
1718 "A regexp to skip confirmation for Elisp links."
1719 :group 'org-link-follow
1720 :version "24.1"
1721 :type 'regexp)
1723 (defconst org-file-apps-defaults-gnu
1724 '((remote . emacs)
1725 (system . mailcap)
1726 (t . mailcap))
1727 "Default file applications on a UNIX or GNU/Linux system.
1728 See `org-file-apps'.")
1730 (defconst org-file-apps-defaults-macosx
1731 '((remote . emacs)
1732 (t . "open %s")
1733 (system . "open %s")
1734 ("ps.gz" . "gv %s")
1735 ("eps.gz" . "gv %s")
1736 ("dvi" . "xdvi %s")
1737 ("fig" . "xfig %s"))
1738 "Default file applications on a MacOS X system.
1739 The system \"open\" is known as a default, but we use X11 applications
1740 for some files for which the OS does not have a good default.
1741 See `org-file-apps'.")
1743 (defconst org-file-apps-defaults-windowsnt
1744 (list
1745 '(remote . emacs)
1746 (cons t
1747 (list (if (featurep 'xemacs)
1748 'mswindows-shell-execute
1749 'w32-shell-execute)
1750 "open" 'file))
1751 (cons 'system
1752 (list (if (featurep 'xemacs)
1753 'mswindows-shell-execute
1754 'w32-shell-execute)
1755 "open" 'file)))
1756 "Default file applications on a Windows NT system.
1757 The system \"open\" is used for most files.
1758 See `org-file-apps'.")
1760 (defcustom org-file-apps
1762 (auto-mode . emacs)
1763 ("\\.mm\\'" . default)
1764 ("\\.x?html?\\'" . default)
1765 ("\\.pdf\\'" . default)
1767 "External applications for opening `file:path' items in a document.
1768 Org-mode uses system defaults for different file types, but
1769 you can use this variable to set the application for a given file
1770 extension. The entries in this list are cons cells where the car identifies
1771 files and the cdr the corresponding command. Possible values for the
1772 file identifier are
1773 \"string\" A string as a file identifier can be interpreted in different
1774 ways, depending on its contents:
1776 - Alphanumeric characters only:
1777 Match links with this file extension.
1778 Example: (\"pdf\" . \"evince %s\")
1779 to open PDFs with evince.
1781 - Regular expression: Match links where the
1782 filename matches the regexp. If you want to
1783 use groups here, use shy groups.
1785 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1786 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1787 to open *.html and *.xhtml with firefox.
1789 - Regular expression which contains (non-shy) groups:
1790 Match links where the whole link, including \"::\", and
1791 anything after that, matches the regexp.
1792 In a custom command string, %1, %2, etc. are replaced with
1793 the parts of the link that were matched by the groups.
1794 For backwards compatibility, if a command string is given
1795 that does not use any of the group matches, this case is
1796 handled identically to the second one (i.e. match against
1797 file name only).
1798 In a custom lisp form, you can access the group matches with
1799 (match-string n link).
1801 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1802 to open [[file:document.pdf::5]] with evince at page 5.
1804 `directory' Matches a directory
1805 `remote' Matches a remote file, accessible through tramp or efs.
1806 Remote files most likely should be visited through Emacs
1807 because external applications cannot handle such paths.
1808 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1809 so all files Emacs knows how to handle. Using this with
1810 command `emacs' will open most files in Emacs. Beware that this
1811 will also open html files inside Emacs, unless you add
1812 (\"html\" . default) to the list as well.
1813 t Default for files not matched by any of the other options.
1814 `system' The system command to open files, like `open' on Windows
1815 and Mac OS X, and mailcap under GNU/Linux. This is the command
1816 that will be selected if you call `C-c C-o' with a double
1817 \\[universal-argument] \\[universal-argument] prefix.
1819 Possible values for the command are:
1820 `emacs' The file will be visited by the current Emacs process.
1821 `default' Use the default application for this file type, which is the
1822 association for t in the list, most likely in the system-specific
1823 part.
1824 This can be used to overrule an unwanted setting in the
1825 system-specific variable.
1826 `system' Use the system command for opening files, like \"open\".
1827 This command is specified by the entry whose car is `system'.
1828 Most likely, the system-specific version of this variable
1829 does define this command, but you can overrule/replace it
1830 here.
1831 string A command to be executed by a shell; %s will be replaced
1832 by the path to the file.
1833 sexp A Lisp form which will be evaluated. The file path will
1834 be available in the Lisp variable `file'.
1835 For more examples, see the system specific constants
1836 `org-file-apps-defaults-macosx'
1837 `org-file-apps-defaults-windowsnt'
1838 `org-file-apps-defaults-gnu'."
1839 :group 'org-link-follow
1840 :type '(repeat
1841 (cons (choice :value ""
1842 (string :tag "Extension")
1843 (const :tag "System command to open files" system)
1844 (const :tag "Default for unrecognized files" t)
1845 (const :tag "Remote file" remote)
1846 (const :tag "Links to a directory" directory)
1847 (const :tag "Any files that have Emacs modes"
1848 auto-mode))
1849 (choice :value ""
1850 (const :tag "Visit with Emacs" emacs)
1851 (const :tag "Use default" default)
1852 (const :tag "Use the system command" system)
1853 (string :tag "Command")
1854 (sexp :tag "Lisp form")))))
1856 (defcustom org-doi-server-url "http://dx.doi.org/"
1857 "The URL of the DOI server."
1858 :type 'string
1859 ;; :version "24.3"
1860 :group 'org-link-follow)
1862 (defgroup org-refile nil
1863 "Options concerning refiling entries in Org-mode."
1864 :tag "Org Refile"
1865 :group 'org)
1867 (defcustom org-directory "~/org"
1868 "Directory with org files.
1869 This is just a default location to look for Org files. There is no need
1870 at all to put your files into this directory. It is only used in the
1871 following situations:
1873 1. When a remember template specifies a target file that is not an
1874 absolute path. The path will then be interpreted relative to
1875 `org-directory'
1876 2. When a remember note is filed away in an interactive way (when exiting the
1877 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1878 with `org-directory' as the default path."
1879 :group 'org-refile
1880 :group 'org-remember
1881 :type 'directory)
1883 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1884 "Default target for storing notes.
1885 Used as a fall back file for org-remember.el and org-capture.el, for
1886 templates that do not specify a target file."
1887 :group 'org-refile
1888 :group 'org-remember
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-refile
1919 :type '(choice
1920 (const :tag "Reverse always" t)
1921 (const :tag "Reverse never" nil)
1922 (repeat :tag "By file name regexp"
1923 (cons regexp boolean))))
1925 (defcustom org-log-refile nil
1926 "Information to record when a task is refiled.
1928 Possible values are:
1930 nil Don't add anything
1931 time Add a time stamp to the task
1932 note Prompt for a note and add it with template `org-log-note-headings'
1934 This option can also be set with on a per-file-basis with
1936 #+STARTUP: nologrefile
1937 #+STARTUP: logrefile
1938 #+STARTUP: lognoterefile
1940 You can have local logging settings for a subtree by setting the LOGGING
1941 property to one or more of these keywords.
1943 When bulk-refiling from the agenda, the value `note' is forbidden and
1944 will temporarily be changed to `time'."
1945 :group 'org-refile
1946 :group 'org-progress
1947 :version "24.1"
1948 :type '(choice
1949 (const :tag "No logging" nil)
1950 (const :tag "Record timestamp" time)
1951 (const :tag "Record timestamp with note." note)))
1953 (defcustom org-refile-targets nil
1954 "Targets for refiling entries with \\[org-refile].
1955 This is a list of cons cells. Each cell contains:
1956 - a specification of the files to be considered, either a list of files,
1957 or a symbol whose function or variable value will be used to retrieve
1958 a file name or a list of file names. If you use `org-agenda-files' for
1959 that, all agenda files will be scanned for targets. Nil means consider
1960 headings in the current buffer.
1961 - A specification of how to find candidate refile targets. This may be
1962 any of:
1963 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1964 This tag has to be present in all target headlines, inheritance will
1965 not be considered.
1966 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1967 todo keyword.
1968 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1969 headlines that are refiling targets.
1970 - a cons cell (:level . N). Any headline of level N is considered a target.
1971 Note that, when `org-odd-levels-only' is set, level corresponds to
1972 order in hierarchy, not to the number of stars.
1973 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1974 Note that, when `org-odd-levels-only' is set, level corresponds to
1975 order in hierarchy, not to the number of stars.
1977 Each element of this list generates a set of possible targets.
1978 The union of these sets is presented (with completion) to
1979 the user by `org-refile'.
1981 You can set the variable `org-refile-target-verify-function' to a function
1982 to verify each headline found by the simple criteria above.
1984 When this variable is nil, all top-level headlines in the current buffer
1985 are used, equivalent to the value `((nil . (:level . 1))'."
1986 :group 'org-refile
1987 :type '(repeat
1988 (cons
1989 (choice :value org-agenda-files
1990 (const :tag "All agenda files" org-agenda-files)
1991 (const :tag "Current buffer" nil)
1992 (function) (variable) (file))
1993 (choice :tag "Identify target headline by"
1994 (cons :tag "Specific tag" (const :value :tag) (string))
1995 (cons :tag "TODO keyword" (const :value :todo) (string))
1996 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1997 (cons :tag "Level number" (const :value :level) (integer))
1998 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2000 (defcustom org-refile-target-verify-function nil
2001 "Function to verify if the headline at point should be a refile target.
2002 The function will be called without arguments, with point at the
2003 beginning of the headline. It should return t and leave point
2004 where it is if the headline is a valid target for refiling.
2006 If the target should not be selected, the function must return nil.
2007 In addition to this, it may move point to a place from where the search
2008 should be continued. For example, the function may decide that the entire
2009 subtree of the current entry should be excluded and move point to the end
2010 of the subtree."
2011 :group 'org-refile
2012 :type 'function)
2014 (defcustom org-refile-use-cache nil
2015 "Non-nil means cache refile targets to speed up the process.
2016 The cache for a particular file will be updated automatically when
2017 the buffer has been killed, or when any of the marker used for flagging
2018 refile targets no longer points at a live buffer.
2019 If you have added new entries to a buffer that might themselves be targets,
2020 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2021 find that easier, `C-u C-u C-u C-c C-w'."
2022 :group 'org-refile
2023 :version "24.1"
2024 :type 'boolean)
2026 (defcustom org-refile-use-outline-path nil
2027 "Non-nil means provide refile targets as paths.
2028 So a level 3 headline will be available as level1/level2/level3.
2030 When the value is `file', also include the file name (without directory)
2031 into the path. In this case, you can also stop the completion after
2032 the file name, to get entries inserted as top level in the file.
2034 When `full-file-path', include the full file path."
2035 :group 'org-refile
2036 :type '(choice
2037 (const :tag "Not" nil)
2038 (const :tag "Yes" t)
2039 (const :tag "Start with file name" file)
2040 (const :tag "Start with full file path" full-file-path)))
2042 (defcustom org-outline-path-complete-in-steps t
2043 "Non-nil means complete the outline path in hierarchical steps.
2044 When Org-mode uses the refile interface to select an outline path
2045 \(see variable `org-refile-use-outline-path'), the completion of
2046 the path can be done is a single go, or if can be done in steps down
2047 the headline hierarchy. Going in steps is probably the best if you
2048 do not use a special completion package like `ido' or `icicles'.
2049 However, when using these packages, going in one step can be very
2050 fast, while still showing the whole path to the entry."
2051 :group 'org-refile
2052 :type 'boolean)
2054 (defcustom org-refile-allow-creating-parent-nodes nil
2055 "Non-nil means allow to create new nodes as refile targets.
2056 New nodes are then created by adding \"/new node name\" to the completion
2057 of an existing node. When the value of this variable is `confirm',
2058 new node creation must be confirmed by the user (recommended)
2059 When nil, the completion must match an existing entry.
2061 Note that, if the new heading is not seen by the criteria
2062 listed in `org-refile-targets', multiple instances of the same
2063 heading would be created by trying again to file under the new
2064 heading."
2065 :group 'org-refile
2066 :type '(choice
2067 (const :tag "Never" nil)
2068 (const :tag "Always" t)
2069 (const :tag "Prompt for confirmation" confirm)))
2071 (defcustom org-refile-active-region-within-subtree nil
2072 "Non-nil means also refile active region within a subtree.
2074 By default `org-refile' doesn't allow refiling regions if they
2075 don't contain a set of subtrees, but it might be convenient to
2076 do so sometimes: in that case, the first line of the region is
2077 converted to a headline before refiling."
2078 :group 'org-refile
2079 :version "24.1"
2080 :type 'boolean)
2082 (defgroup org-todo nil
2083 "Options concerning TODO items in Org-mode."
2084 :tag "Org TODO"
2085 :group 'org)
2087 (defgroup org-progress nil
2088 "Options concerning Progress logging in Org-mode."
2089 :tag "Org Progress"
2090 :group 'org-time)
2092 (defvar org-todo-interpretation-widgets
2093 '((:tag "Sequence (cycling hits every state)" sequence)
2094 (:tag "Type (cycling directly to DONE)" type))
2095 "The available interpretation symbols for customizing `org-todo-keywords'.
2096 Interested libraries should add to this list.")
2098 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2099 "List of TODO entry keyword sequences and their interpretation.
2100 \\<org-mode-map>This is a list of sequences.
2102 Each sequence starts with a symbol, either `sequence' or `type',
2103 indicating if the keywords should be interpreted as a sequence of
2104 action steps, or as different types of TODO items. The first
2105 keywords are states requiring action - these states will select a headline
2106 for inclusion into the global TODO list Org-mode produces. If one of
2107 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2108 signify that no further action is necessary. If \"|\" is not found,
2109 the last keyword is treated as the only DONE state of the sequence.
2111 The command \\[org-todo] cycles an entry through these states, and one
2112 additional state where no keyword is present. For details about this
2113 cycling, see the manual.
2115 TODO keywords and interpretation can also be set on a per-file basis with
2116 the special #+SEQ_TODO and #+TYP_TODO lines.
2118 Each keyword can optionally specify a character for fast state selection
2119 \(in combination with the variable `org-use-fast-todo-selection')
2120 and specifiers for state change logging, using the same syntax that
2121 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2122 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2123 indicates to record a time stamp each time this state is selected.
2125 Each keyword may also specify if a timestamp or a note should be
2126 recorded when entering or leaving the state, by adding additional
2127 characters in the parenthesis after the keyword. This looks like this:
2128 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2129 record only the time of the state change. With X and Y being either
2130 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2131 Y when leaving the state if and only if the *target* state does not
2132 define X. You may omit any of the fast-selection key or X or /Y,
2133 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2135 For backward compatibility, this variable may also be just a list
2136 of keywords. In this case the interpretation (sequence or type) will be
2137 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2138 :group 'org-todo
2139 :group 'org-keywords
2140 :type '(choice
2141 (repeat :tag "Old syntax, just keywords"
2142 (string :tag "Keyword"))
2143 (repeat :tag "New syntax"
2144 (cons
2145 (choice
2146 :tag "Interpretation"
2147 ;;Quick and dirty way to see
2148 ;;`org-todo-interpretations'. This takes the
2149 ;;place of item arguments
2150 :convert-widget
2151 (lambda (widget)
2152 (widget-put widget
2153 :args (mapcar
2154 #'(lambda (x)
2155 (widget-convert
2156 (cons 'const x)))
2157 org-todo-interpretation-widgets))
2158 widget))
2159 (repeat
2160 (string :tag "Keyword"))))))
2162 (defvar org-todo-keywords-1 nil
2163 "All TODO and DONE keywords active in a buffer.")
2164 (make-variable-buffer-local 'org-todo-keywords-1)
2165 (defvar org-todo-keywords-for-agenda nil)
2166 (defvar org-done-keywords-for-agenda nil)
2167 (defvar org-drawers-for-agenda nil)
2168 (defvar org-todo-keyword-alist-for-agenda nil)
2169 (defvar org-tag-alist-for-agenda nil)
2170 (defvar org-agenda-contributing-files nil)
2171 (defvar org-not-done-keywords nil)
2172 (make-variable-buffer-local 'org-not-done-keywords)
2173 (defvar org-done-keywords nil)
2174 (make-variable-buffer-local 'org-done-keywords)
2175 (defvar org-todo-heads nil)
2176 (make-variable-buffer-local 'org-todo-heads)
2177 (defvar org-todo-sets nil)
2178 (make-variable-buffer-local 'org-todo-sets)
2179 (defvar org-todo-log-states nil)
2180 (make-variable-buffer-local 'org-todo-log-states)
2181 (defvar org-todo-kwd-alist nil)
2182 (make-variable-buffer-local 'org-todo-kwd-alist)
2183 (defvar org-todo-key-alist nil)
2184 (make-variable-buffer-local 'org-todo-key-alist)
2185 (defvar org-todo-key-trigger nil)
2186 (make-variable-buffer-local 'org-todo-key-trigger)
2188 (defcustom org-todo-interpretation 'sequence
2189 "Controls how TODO keywords are interpreted.
2190 This variable is in principle obsolete and is only used for
2191 backward compatibility, if the interpretation of todo keywords is
2192 not given already in `org-todo-keywords'. See that variable for
2193 more information."
2194 :group 'org-todo
2195 :group 'org-keywords
2196 :type '(choice (const sequence)
2197 (const type)))
2199 (defcustom org-use-fast-todo-selection t
2200 "Non-nil means use the fast todo selection scheme with C-c C-t.
2201 This variable describes if and under what circumstances the cycling
2202 mechanism for TODO keywords will be replaced by a single-key, direct
2203 selection scheme.
2205 When nil, fast selection is never used.
2207 When the symbol `prefix', it will be used when `org-todo' is called
2208 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2209 `C-u t' in an agenda buffer.
2211 When t, fast selection is used by default. In this case, the prefix
2212 argument forces cycling instead.
2214 In all cases, the special interface is only used if access keys have
2215 actually been assigned by the user, i.e. if keywords in the configuration
2216 are followed by a letter in parenthesis, like TODO(t)."
2217 :group 'org-todo
2218 :type '(choice
2219 (const :tag "Never" nil)
2220 (const :tag "By default" t)
2221 (const :tag "Only with C-u C-c C-t" prefix)))
2223 (defcustom org-provide-todo-statistics t
2224 "Non-nil means update todo statistics after insert and toggle.
2225 ALL-HEADLINES means update todo statistics by including headlines
2226 with no TODO keyword as well, counting them as not done.
2227 A list of TODO keywords means the same, but skip keywords that are
2228 not in this list.
2230 When this is set, todo statistics is updated in the parent of the
2231 current entry each time a todo state is changed."
2232 :group 'org-todo
2233 :type '(choice
2234 (const :tag "Yes, only for TODO entries" t)
2235 (const :tag "Yes, including all entries" 'all-headlines)
2236 (repeat :tag "Yes, for TODOs in this list"
2237 (string :tag "TODO keyword"))
2238 (other :tag "No TODO statistics" nil)))
2240 (defcustom org-hierarchical-todo-statistics t
2241 "Non-nil means TODO statistics covers just direct children.
2242 When nil, all entries in the subtree are considered.
2243 This has only an effect if `org-provide-todo-statistics' is set.
2244 To set this to nil for only a single subtree, use a COOKIE_DATA
2245 property and include the word \"recursive\" into the value."
2246 :group 'org-todo
2247 :type 'boolean)
2249 (defcustom org-after-todo-state-change-hook nil
2250 "Hook which is run after the state of a TODO item was changed.
2251 The new state (a string with a TODO keyword, or nil) is available in the
2252 Lisp variable `org-state'."
2253 :group 'org-todo
2254 :type 'hook)
2256 (defvar org-blocker-hook nil
2257 "Hook for functions that are allowed to block a state change.
2259 Each function gets as its single argument a property list, see
2260 `org-trigger-hook' for more information about this list.
2262 If any of the functions in this hook returns nil, the state change
2263 is blocked.")
2265 (defvar org-trigger-hook nil
2266 "Hook for functions that are triggered by a state change.
2268 Each function gets as its single argument a property list with at least
2269 the following elements:
2271 (:type type-of-change :position pos-at-entry-start
2272 :from old-state :to new-state)
2274 Depending on the type, more properties may be present.
2276 This mechanism is currently implemented for:
2278 TODO state changes
2279 ------------------
2280 :type todo-state-change
2281 :from previous state (keyword as a string), or nil, or a symbol
2282 'todo' or 'done', to indicate the general type of state.
2283 :to new state, like in :from")
2285 (defcustom org-enforce-todo-dependencies nil
2286 "Non-nil means undone TODO entries will block switching the parent to DONE.
2287 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2288 be blocked if any prior sibling is not yet done.
2289 Finally, if the parent is blocked because of ordered siblings of its own,
2290 the child will also be blocked."
2291 :set (lambda (var val)
2292 (set var val)
2293 (if val
2294 (add-hook 'org-blocker-hook
2295 'org-block-todo-from-children-or-siblings-or-parent)
2296 (remove-hook 'org-blocker-hook
2297 'org-block-todo-from-children-or-siblings-or-parent)))
2298 :group 'org-todo
2299 :type 'boolean)
2301 (defcustom org-enforce-todo-checkbox-dependencies nil
2302 "Non-nil means unchecked boxes will block switching the parent to DONE.
2303 When this is nil, checkboxes have no influence on switching TODO states.
2304 When non-nil, you first need to check off all check boxes before the TODO
2305 entry can be switched to DONE.
2306 This variable needs to be set before org.el is loaded, and you need to
2307 restart Emacs after a change to make the change effective. The only way
2308 to change is while Emacs is running is through the customize interface."
2309 :set (lambda (var val)
2310 (set var val)
2311 (if val
2312 (add-hook 'org-blocker-hook
2313 'org-block-todo-from-checkboxes)
2314 (remove-hook 'org-blocker-hook
2315 'org-block-todo-from-checkboxes)))
2316 :group 'org-todo
2317 :type 'boolean)
2319 (defcustom org-treat-insert-todo-heading-as-state-change nil
2320 "Non-nil means inserting a TODO heading is treated as state change.
2321 So when the command \\[org-insert-todo-heading] is used, state change
2322 logging will apply if appropriate. When nil, the new TODO item will
2323 be inserted directly, and no logging will take place."
2324 :group 'org-todo
2325 :type 'boolean)
2327 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2328 "Non-nil means switching TODO states with S-cursor counts as state change.
2329 This is the default behavior. However, setting this to nil allows a
2330 convenient way to select a TODO state and bypass any logging associated
2331 with that."
2332 :group 'org-todo
2333 :type 'boolean)
2335 (defcustom org-todo-state-tags-triggers nil
2336 "Tag changes that should be triggered by TODO state changes.
2337 This is a list. Each entry is
2339 (state-change (tag . flag) .......)
2341 State-change can be a string with a state, and empty string to indicate the
2342 state that has no TODO keyword, or it can be one of the symbols `todo'
2343 or `done', meaning any not-done or done state, respectively."
2344 :group 'org-todo
2345 :group 'org-tags
2346 :type '(repeat
2347 (cons (choice :tag "When changing to"
2348 (const :tag "Not-done state" todo)
2349 (const :tag "Done state" done)
2350 (string :tag "State"))
2351 (repeat
2352 (cons :tag "Tag action"
2353 (string :tag "Tag")
2354 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2356 (defcustom org-log-done nil
2357 "Information to record when a task moves to the DONE state.
2359 Possible values are:
2361 nil Don't add anything, just change the keyword
2362 time Add a time stamp to the task
2363 note Prompt for a note and add it with template `org-log-note-headings'
2365 This option can also be set with on a per-file-basis with
2367 #+STARTUP: nologdone
2368 #+STARTUP: logdone
2369 #+STARTUP: lognotedone
2371 You can have local logging settings for a subtree by setting the LOGGING
2372 property to one or more of these keywords."
2373 :group 'org-todo
2374 :group 'org-progress
2375 :type '(choice
2376 (const :tag "No logging" nil)
2377 (const :tag "Record CLOSED timestamp" time)
2378 (const :tag "Record CLOSED timestamp with note." note)))
2380 ;; Normalize old uses of org-log-done.
2381 (cond
2382 ((eq org-log-done t) (setq org-log-done 'time))
2383 ((and (listp org-log-done) (memq 'done org-log-done))
2384 (setq org-log-done 'note)))
2386 (defcustom org-log-reschedule nil
2387 "Information to record when the scheduling date of a tasks is modified.
2389 Possible values are:
2391 nil Don't add anything, just change the date
2392 time Add a time stamp to the task
2393 note Prompt for a note and add it with template `org-log-note-headings'
2395 This option can also be set with on a per-file-basis with
2397 #+STARTUP: nologreschedule
2398 #+STARTUP: logreschedule
2399 #+STARTUP: lognotereschedule"
2400 :group 'org-todo
2401 :group 'org-progress
2402 :type '(choice
2403 (const :tag "No logging" nil)
2404 (const :tag "Record timestamp" time)
2405 (const :tag "Record timestamp with note." note)))
2407 (defcustom org-log-redeadline nil
2408 "Information to record when the deadline date of a tasks is modified.
2410 Possible values are:
2412 nil Don't add anything, just change the date
2413 time Add a time stamp to the task
2414 note Prompt for a note and add it with template `org-log-note-headings'
2416 This option can also be set with on a per-file-basis with
2418 #+STARTUP: nologredeadline
2419 #+STARTUP: logredeadline
2420 #+STARTUP: lognoteredeadline
2422 You can have local logging settings for a subtree by setting the LOGGING
2423 property to one or more of these keywords."
2424 :group 'org-todo
2425 :group 'org-progress
2426 :type '(choice
2427 (const :tag "No logging" nil)
2428 (const :tag "Record timestamp" time)
2429 (const :tag "Record timestamp with note." note)))
2431 (defcustom org-log-note-clock-out nil
2432 "Non-nil means record a note when clocking out of an item.
2433 This can also be configured on a per-file basis by adding one of
2434 the following lines anywhere in the buffer:
2436 #+STARTUP: lognoteclock-out
2437 #+STARTUP: nolognoteclock-out"
2438 :group 'org-todo
2439 :group 'org-progress
2440 :type 'boolean)
2442 (defcustom org-log-done-with-time t
2443 "Non-nil means the CLOSED time stamp will contain date and time.
2444 When nil, only the date will be recorded."
2445 :group 'org-progress
2446 :type 'boolean)
2448 (defcustom org-log-note-headings
2449 '((done . "CLOSING NOTE %t")
2450 (state . "State %-12s from %-12S %t")
2451 (note . "Note taken on %t")
2452 (reschedule . "Rescheduled from %S on %t")
2453 (delschedule . "Not scheduled, was %S on %t")
2454 (redeadline . "New deadline from %S on %t")
2455 (deldeadline . "Removed deadline, was %S on %t")
2456 (refile . "Refiled on %t")
2457 (clock-out . ""))
2458 "Headings for notes added to entries.
2459 The value is an alist, with the car being a symbol indicating the note
2460 context, and the cdr is the heading to be used. The heading may also be the
2461 empty string.
2462 %t in the heading will be replaced by a time stamp.
2463 %T will be an active time stamp instead the default inactive one
2464 %d will be replaced by a short-format time stamp.
2465 %D will be replaced by an active short-format time stamp.
2466 %s will be replaced by the new TODO state, in double quotes.
2467 %S will be replaced by the old TODO state, in double quotes.
2468 %u will be replaced by the user name.
2469 %U will be replaced by the full user name.
2471 In fact, it is not a good idea to change the `state' entry, because
2472 agenda log mode depends on the format of these entries."
2473 :group 'org-todo
2474 :group 'org-progress
2475 :type '(list :greedy t
2476 (cons (const :tag "Heading when closing an item" done) string)
2477 (cons (const :tag
2478 "Heading when changing todo state (todo sequence only)"
2479 state) string)
2480 (cons (const :tag "Heading when just taking a note" note) string)
2481 (cons (const :tag "Heading when clocking out" clock-out) string)
2482 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2483 (cons (const :tag "Heading when rescheduling" reschedule) string)
2484 (cons (const :tag "Heading when changing deadline" redeadline) string)
2485 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2486 (cons (const :tag "Heading when refiling" refile) string)))
2488 (unless (assq 'note org-log-note-headings)
2489 (push '(note . "%t") org-log-note-headings))
2491 (defcustom org-log-into-drawer nil
2492 "Non-nil means insert state change notes and time stamps into a drawer.
2493 When nil, state changes notes will be inserted after the headline and
2494 any scheduling and clock lines, but not inside a drawer.
2496 The value of this variable should be the name of the drawer to use.
2497 LOGBOOK is proposed as the default drawer for this purpose, you can
2498 also set this to a string to define the drawer of your choice.
2500 A value of t is also allowed, representing \"LOGBOOK\".
2502 If this variable is set, `org-log-state-notes-insert-after-drawers'
2503 will be ignored.
2505 You can set the property LOG_INTO_DRAWER to overrule this setting for
2506 a subtree."
2507 :group 'org-todo
2508 :group 'org-progress
2509 :type '(choice
2510 (const :tag "Not into a drawer" nil)
2511 (const :tag "LOGBOOK" t)
2512 (string :tag "Other")))
2514 (if (fboundp 'defvaralias)
2515 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2517 (defun org-log-into-drawer ()
2518 "Return the value of `org-log-into-drawer', but let properties overrule.
2519 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2520 used instead of the default value."
2521 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2522 (cond
2523 ((or (not p) (equal p "nil")) org-log-into-drawer)
2524 ((equal p "t") "LOGBOOK")
2525 (t p))))
2527 (defcustom org-log-state-notes-insert-after-drawers nil
2528 "Non-nil means insert state change notes after any drawers in entry.
2529 Only the drawers that *immediately* follow the headline and the
2530 deadline/scheduled line are skipped.
2531 When nil, insert notes right after the heading and perhaps the line
2532 with deadline/scheduling if present.
2534 This variable will have no effect if `org-log-into-drawer' is
2535 set."
2536 :group 'org-todo
2537 :group 'org-progress
2538 :type 'boolean)
2540 (defcustom org-log-states-order-reversed t
2541 "Non-nil means the latest state note will be directly after heading.
2542 When nil, the state change notes will be ordered according to time."
2543 :group 'org-todo
2544 :group 'org-progress
2545 :type 'boolean)
2547 (defcustom org-todo-repeat-to-state nil
2548 "The TODO state to which a repeater should return the repeating task.
2549 By default this is the first task in a TODO sequence, or the previous state
2550 in a TODO_TYP set. But you can specify another task here.
2551 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2552 :group 'org-todo
2553 :version "24.1"
2554 :type '(choice (const :tag "Head of sequence" nil)
2555 (string :tag "Specific state")))
2557 (defcustom org-log-repeat 'time
2558 "Non-nil means record moving through the DONE state when triggering repeat.
2559 An auto-repeating task is immediately switched back to TODO when
2560 marked DONE. If you are not logging state changes (by adding \"@\"
2561 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2562 record a closing note, there will be no record of the task moving
2563 through DONE. This variable forces taking a note anyway.
2565 nil Don't force a record
2566 time Record a time stamp
2567 note Prompt for a note and add it with template `org-log-note-headings'
2569 This option can also be set with on a per-file-basis with
2571 #+STARTUP: nologrepeat
2572 #+STARTUP: logrepeat
2573 #+STARTUP: lognoterepeat
2575 You can have local logging settings for a subtree by setting the LOGGING
2576 property to one or more of these keywords."
2577 :group 'org-todo
2578 :group 'org-progress
2579 :type '(choice
2580 (const :tag "Don't force a record" nil)
2581 (const :tag "Force recording the DONE state" time)
2582 (const :tag "Force recording a note with the DONE state" note)))
2585 (defgroup org-priorities nil
2586 "Priorities in Org-mode."
2587 :tag "Org Priorities"
2588 :group 'org-todo)
2590 (defcustom org-enable-priority-commands t
2591 "Non-nil means priority commands are active.
2592 When nil, these commands will be disabled, so that you never accidentally
2593 set a priority."
2594 :group 'org-priorities
2595 :type 'boolean)
2597 (defcustom org-highest-priority ?A
2598 "The highest priority of TODO items. A character like ?A, ?B etc.
2599 Must have a smaller ASCII number than `org-lowest-priority'."
2600 :group 'org-priorities
2601 :type 'character)
2603 (defcustom org-lowest-priority ?C
2604 "The lowest priority of TODO items. A character like ?A, ?B etc.
2605 Must have a larger ASCII number than `org-highest-priority'."
2606 :group 'org-priorities
2607 :type 'character)
2609 (defcustom org-default-priority ?B
2610 "The default priority of TODO items.
2611 This is the priority an item gets if no explicit priority is given.
2612 When starting to cycle on an empty priority the first step in the cycle
2613 depends on `org-priority-start-cycle-with-default'. The resulting first
2614 step priority must not exceed the range from `org-highest-priority' to
2615 `org-lowest-priority' which means that `org-default-priority' has to be
2616 in this range exclusive or inclusive the range boundaries. Else the
2617 first step refuses to set the default and the second will fall back
2618 to (depending on the command used) the highest or lowest priority."
2619 :group 'org-priorities
2620 :type 'character)
2622 (defcustom org-priority-start-cycle-with-default t
2623 "Non-nil means start with default priority when starting to cycle.
2624 When this is nil, the first step in the cycle will be (depending on the
2625 command used) one higher or lower than the default priority.
2626 See also `org-default-priority'."
2627 :group 'org-priorities
2628 :type 'boolean)
2630 (defcustom org-get-priority-function nil
2631 "Function to extract the priority from a string.
2632 The string is normally the headline. If this is nil Org computes the
2633 priority from the priority cookie like [#A] in the headline. It returns
2634 an integer, increasing by 1000 for each priority level.
2635 The user can set a different function here, which should take a string
2636 as an argument and return the numeric priority."
2637 :group 'org-priorities
2638 :version "24.1"
2639 :type 'function)
2641 (defgroup org-time nil
2642 "Options concerning time stamps and deadlines in Org-mode."
2643 :tag "Org Time"
2644 :group 'org)
2646 (defcustom org-insert-labeled-timestamps-at-point nil
2647 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2648 When nil, these labeled time stamps are forces into the second line of an
2649 entry, just after the headline. When scheduling from the global TODO list,
2650 the time stamp will always be forced into the second line."
2651 :group 'org-time
2652 :type 'boolean)
2654 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2655 "Formats for `format-time-string' which are used for time stamps.
2656 It is not recommended to change this constant.")
2658 (defcustom org-time-stamp-rounding-minutes '(0 5)
2659 "Number of minutes to round time stamps to.
2660 These are two values, the first applies when first creating a time stamp.
2661 The second applies when changing it with the commands `S-up' and `S-down'.
2662 When changing the time stamp, this means that it will change in steps
2663 of N minutes, as given by the second value.
2665 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2666 numbers should be factors of 60, so for example 5, 10, 15.
2668 When this is larger than 1, you can still force an exact time stamp by using
2669 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2670 and by using a prefix arg to `S-up/down' to specify the exact number
2671 of minutes to shift."
2672 :group 'org-time
2673 :get #'(lambda (var) ; Make sure both elements are there
2674 (if (integerp (default-value var))
2675 (list (default-value var) 5)
2676 (default-value var)))
2677 :type '(list
2678 (integer :tag "when inserting times")
2679 (integer :tag "when modifying times")))
2681 ;; Normalize old customizations of this variable.
2682 (when (integerp org-time-stamp-rounding-minutes)
2683 (setq org-time-stamp-rounding-minutes
2684 (list org-time-stamp-rounding-minutes
2685 org-time-stamp-rounding-minutes)))
2687 (defcustom org-display-custom-times nil
2688 "Non-nil means overlay custom formats over all time stamps.
2689 The formats are defined through the variable `org-time-stamp-custom-formats'.
2690 To turn this on on a per-file basis, insert anywhere in the file:
2691 #+STARTUP: customtime"
2692 :group 'org-time
2693 :set 'set-default
2694 :type 'sexp)
2695 (make-variable-buffer-local 'org-display-custom-times)
2697 (defcustom org-time-stamp-custom-formats
2698 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2699 "Custom formats for time stamps. See `format-time-string' for the syntax.
2700 These are overlaid over the default ISO format if the variable
2701 `org-display-custom-times' is set. Time like %H:%M should be at the
2702 end of the second format. The custom formats are also honored by export
2703 commands, if custom time display is turned on at the time of export."
2704 :group 'org-time
2705 :type 'sexp)
2707 (defun org-time-stamp-format (&optional long inactive)
2708 "Get the right format for a time string."
2709 (let ((f (if long (cdr org-time-stamp-formats)
2710 (car org-time-stamp-formats))))
2711 (if inactive
2712 (concat "[" (substring f 1 -1) "]")
2713 f)))
2715 (defcustom org-time-clocksum-format "%d:%02d"
2716 "The format string used when creating CLOCKSUM lines.
2717 This is also used when org-mode generates a time duration."
2718 :group 'org-time
2719 :type 'string)
2721 (defcustom org-time-clocksum-use-fractional nil
2722 "If non-nil, \\[org-clock-display] uses fractional times.
2723 org-mode generates a time duration."
2724 :group 'org-time
2725 :type 'boolean)
2727 (defcustom org-time-clocksum-fractional-format "%.2f"
2728 "The format string used when creating CLOCKSUM lines, or when
2729 org-mode generates a time duration."
2730 :group 'org-time
2731 :type 'string)
2733 (defcustom org-deadline-warning-days 14
2734 "No. of days before expiration during which a deadline becomes active.
2735 This variable governs the display in sparse trees and in the agenda.
2736 When 0 or negative, it means use this number (the absolute value of it)
2737 even if a deadline has a different individual lead time specified.
2739 Custom commands can set this variable in the options section."
2740 :group 'org-time
2741 :group 'org-agenda-daily/weekly
2742 :type 'integer)
2744 (defcustom org-read-date-prefer-future t
2745 "Non-nil means assume future for incomplete date input from user.
2746 This affects the following situations:
2747 1. The user gives a month but not a year.
2748 For example, if it is April and you enter \"feb 2\", this will be read
2749 as Feb 2, *next* year. \"May 5\", however, will be this year.
2750 2. The user gives a day, but no month.
2751 For example, if today is the 15th, and you enter \"3\", Org-mode will
2752 read this as the third of *next* month. However, if you enter \"17\",
2753 it will be considered as *this* month.
2755 If you set this variable to the symbol `time', then also the following
2756 will work:
2758 3. If the user gives a time.
2759 If the time is before now, it will be interpreted as tomorrow.
2761 Currently none of this works for ISO week specifications.
2763 When this option is nil, the current day, month and year will always be
2764 used as defaults.
2766 See also `org-agenda-jump-prefer-future'."
2767 :group 'org-time
2768 :type '(choice
2769 (const :tag "Never" nil)
2770 (const :tag "Check month and day" t)
2771 (const :tag "Check month, day, and time" time)))
2773 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2774 "Should the agenda jump command prefer the future for incomplete dates?
2775 The default is to do the same as configured in `org-read-date-prefer-future'.
2776 But you can also set a deviating value here.
2777 This may t or nil, or the symbol `org-read-date-prefer-future'."
2778 :group 'org-agenda
2779 :group 'org-time
2780 :version "24.1"
2781 :type '(choice
2782 (const :tag "Use org-read-date-prefer-future"
2783 org-read-date-prefer-future)
2784 (const :tag "Never" nil)
2785 (const :tag "Always" t)))
2787 (defcustom org-read-date-force-compatible-dates t
2788 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2790 Depending on the system Emacs is running on, certain dates cannot
2791 be represented with the type used internally to represent time.
2792 Dates between 1970-1-1 and 2038-1-1 can always be represented
2793 correctly. Some systems allow for earlier dates, some for later,
2794 some for both. One way to find out it to insert any date into an
2795 Org buffer, putting the cursor on the year and hitting S-up and
2796 S-down to test the range.
2798 When this variable is set to t, the date/time prompt will not let
2799 you specify dates outside the 1970-2037 range, so it is certain that
2800 these dates will work in whatever version of Emacs you are
2801 running, and also that you can move a file from one Emacs implementation
2802 to another. WHenever Org is forcing the year for you, it will display
2803 a message and beep.
2805 When this variable is nil, Org will check if the date is
2806 representable in the specific Emacs implementation you are using.
2807 If not, it will force a year, usually the current year, and beep
2808 to remind you. Currently this setting is not recommended because
2809 the likelihood that you will open your Org files in an Emacs that
2810 has limited date range is not negligible.
2812 A workaround for this problem is to use diary sexp dates for time
2813 stamps outside of this range."
2814 :group 'org-time
2815 :version "24.1"
2816 :type 'boolean)
2818 (defcustom org-read-date-display-live t
2819 "Non-nil means display current interpretation of date prompt live.
2820 This display will be in an overlay, in the minibuffer."
2821 :group 'org-time
2822 :type 'boolean)
2824 (defcustom org-read-date-popup-calendar t
2825 "Non-nil means pop up a calendar when prompting for a date.
2826 In the calendar, the date can be selected with mouse-1. However, the
2827 minibuffer will also be active, and you can simply enter the date as well.
2828 When nil, only the minibuffer will be available."
2829 :group 'org-time
2830 :type 'boolean)
2831 (if (fboundp 'defvaralias)
2832 (defvaralias 'org-popup-calendar-for-date-prompt
2833 'org-read-date-popup-calendar))
2835 (defcustom org-read-date-minibuffer-setup-hook nil
2836 "Hook to be used to set up keys for the date/time interface.
2837 Add key definitions to `minibuffer-local-map', which will be a temporary
2838 copy."
2839 :group 'org-time
2840 :type 'hook)
2842 (defcustom org-extend-today-until 0
2843 "The hour when your day really ends. Must be an integer.
2844 This has influence for the following applications:
2845 - When switching the agenda to \"today\". It it is still earlier than
2846 the time given here, the day recognized as TODAY is actually yesterday.
2847 - When a date is read from the user and it is still before the time given
2848 here, the current date and time will be assumed to be yesterday, 23:59.
2849 Also, timestamps inserted in remember templates follow this rule.
2851 IMPORTANT: This is a feature whose implementation is and likely will
2852 remain incomplete. Really, it is only here because past midnight seems to
2853 be the favorite working time of John Wiegley :-)"
2854 :group 'org-time
2855 :type 'integer)
2857 (defcustom org-use-effective-time nil
2858 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2859 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2860 \"effective time\" of any timestamps between midnight and 8am will be
2861 23:59 of the previous day."
2862 :group 'org-time
2863 :version "24.1"
2864 :type 'boolean)
2866 (defcustom org-edit-timestamp-down-means-later nil
2867 "Non-nil means S-down will increase the time in a time stamp.
2868 When nil, S-up will increase."
2869 :group 'org-time
2870 :type 'boolean)
2872 (defcustom org-calendar-follow-timestamp-change t
2873 "Non-nil means make the calendar window follow timestamp changes.
2874 When a timestamp is modified and the calendar window is visible, it will be
2875 moved to the new date."
2876 :group 'org-time
2877 :type 'boolean)
2879 (defgroup org-tags nil
2880 "Options concerning tags in Org-mode."
2881 :tag "Org Tags"
2882 :group 'org)
2884 (defcustom org-tag-alist nil
2885 "List of tags allowed in Org-mode files.
2886 When this list is nil, Org-mode will base TAG input on what is already in the
2887 buffer.
2888 The value of this variable is an alist, the car of each entry must be a
2889 keyword as a string, the cdr may be a character that is used to select
2890 that tag through the fast-tag-selection interface.
2891 See the manual for details."
2892 :group 'org-tags
2893 :type '(repeat
2894 (choice
2895 (cons (string :tag "Tag name")
2896 (character :tag "Access char"))
2897 (list :tag "Start radio group"
2898 (const :startgroup)
2899 (option (string :tag "Group description")))
2900 (list :tag "End radio group"
2901 (const :endgroup)
2902 (option (string :tag "Group description")))
2903 (const :tag "New line" (:newline)))))
2905 (defcustom org-tag-persistent-alist nil
2906 "List of tags that will always appear in all Org-mode files.
2907 This is in addition to any in buffer settings or customizations
2908 of `org-tag-alist'.
2909 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2910 The value of this variable is an alist, the car of each entry must be a
2911 keyword as a string, the cdr may be a character that is used to select
2912 that tag through the fast-tag-selection interface.
2913 See the manual for details.
2914 To disable these tags on a per-file basis, insert anywhere in the file:
2915 #+STARTUP: noptag"
2916 :group 'org-tags
2917 :type '(repeat
2918 (choice
2919 (cons (string :tag "Tag name")
2920 (character :tag "Access char"))
2921 (const :tag "Start radio group" (:startgroup))
2922 (const :tag "End radio group" (:endgroup))
2923 (const :tag "New line" (:newline)))))
2925 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2926 "If non-nil, always offer completion for all tags of all agenda files.
2927 Instead of customizing this variable directly, you might want to
2928 set it locally for capture buffers, because there no list of
2929 tags in that file can be created dynamically (there are none).
2931 (add-hook 'org-capture-mode-hook
2932 (lambda ()
2933 (set (make-local-variable
2934 'org-complete-tags-always-offer-all-agenda-tags)
2935 t)))"
2936 :group 'org-tags
2937 :version "24.1"
2938 :type 'boolean)
2940 (defvar org-file-tags nil
2941 "List of tags that can be inherited by all entries in the file.
2942 The tags will be inherited if the variable `org-use-tag-inheritance'
2943 says they should be.
2944 This variable is populated from #+FILETAGS lines.")
2946 (defcustom org-use-fast-tag-selection 'auto
2947 "Non-nil means use fast tag selection scheme.
2948 This is a special interface to select and deselect tags with single keys.
2949 When nil, fast selection is never used.
2950 When the symbol `auto', fast selection is used if and only if selection
2951 characters for tags have been configured, either through the variable
2952 `org-tag-alist' or through a #+TAGS line in the buffer.
2953 When t, fast selection is always used and selection keys are assigned
2954 automatically if necessary."
2955 :group 'org-tags
2956 :type '(choice
2957 (const :tag "Always" t)
2958 (const :tag "Never" nil)
2959 (const :tag "When selection characters are configured" 'auto)))
2961 (defcustom org-fast-tag-selection-single-key nil
2962 "Non-nil means fast tag selection exits after first change.
2963 When nil, you have to press RET to exit it.
2964 During fast tag selection, you can toggle this flag with `C-c'.
2965 This variable can also have the value `expert'. In this case, the window
2966 displaying the tags menu is not even shown, until you press C-c again."
2967 :group 'org-tags
2968 :type '(choice
2969 (const :tag "No" nil)
2970 (const :tag "Yes" t)
2971 (const :tag "Expert" expert)))
2973 (defvar org-fast-tag-selection-include-todo nil
2974 "Non-nil means fast tags selection interface will also offer TODO states.
2975 This is an undocumented feature, you should not rely on it.")
2977 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2978 "The column to which tags should be indented in a headline.
2979 If this number is positive, it specifies the column. If it is negative,
2980 it means that the tags should be flushright to that column. For example,
2981 -80 works well for a normal 80 character screen.
2982 When 0, place tags directly after headline text, with only one space in
2983 between."
2984 :group 'org-tags
2985 :type 'integer)
2987 (defcustom org-auto-align-tags t
2988 "Non-nil keeps tags aligned when modifying headlines.
2989 Some operations (i.e. demoting) change the length of a headline and
2990 therefore shift the tags around. With this option turned on, after
2991 each such operation the tags are again aligned to `org-tags-column'."
2992 :group 'org-tags
2993 :type 'boolean)
2995 (defcustom org-use-tag-inheritance t
2996 "Non-nil means tags in levels apply also for sublevels.
2997 When nil, only the tags directly given in a specific line apply there.
2998 This may also be a list of tags that should be inherited, or a regexp that
2999 matches tags that should be inherited. Additional control is possible
3000 with the variable `org-tags-exclude-from-inheritance' which gives an
3001 explicit list of tags to be excluded from inheritance., even if the value of
3002 `org-use-tag-inheritance' would select it for inheritance.
3004 If this option is t, a match early-on in a tree can lead to a large
3005 number of matches in the subtree when constructing the agenda or creating
3006 a sparse tree. If you only want to see the first match in a tree during
3007 a search, check out the variable `org-tags-match-list-sublevels'."
3008 :group 'org-tags
3009 :type '(choice
3010 (const :tag "Not" nil)
3011 (const :tag "Always" t)
3012 (repeat :tag "Specific tags" (string :tag "Tag"))
3013 (regexp :tag "Tags matched by regexp")))
3015 (defcustom org-tags-exclude-from-inheritance nil
3016 "List of tags that should never be inherited.
3017 This is a way to exclude a few tags from inheritance. For way to do
3018 the opposite, to actively allow inheritance for selected tags,
3019 see the variable `org-use-tag-inheritance'."
3020 :group 'org-tags
3021 :type '(repeat (string :tag "Tag")))
3023 (defun org-tag-inherit-p (tag)
3024 "Check if TAG is one that should be inherited."
3025 (cond
3026 ((member tag org-tags-exclude-from-inheritance) nil)
3027 ((eq org-use-tag-inheritance t) t)
3028 ((not org-use-tag-inheritance) nil)
3029 ((stringp org-use-tag-inheritance)
3030 (string-match org-use-tag-inheritance tag))
3031 ((listp org-use-tag-inheritance)
3032 (member tag org-use-tag-inheritance))
3033 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3035 (defcustom org-tags-match-list-sublevels t
3036 "Non-nil means list also sublevels of headlines matching a search.
3037 This variable applies to tags/property searches, and also to stuck
3038 projects because this search is based on a tags match as well.
3040 When set to the symbol `indented', sublevels are indented with
3041 leading dots.
3043 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3044 the sublevels of a headline matching a tag search often also match
3045 the same search. Listing all of them can create very long lists.
3046 Setting this variable to nil causes subtrees of a match to be skipped.
3048 This variable is semi-obsolete and probably should always be true. It
3049 is better to limit inheritance to certain tags using the variables
3050 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3051 :group 'org-tags
3052 :type '(choice
3053 (const :tag "No, don't list them" nil)
3054 (const :tag "Yes, do list them" t)
3055 (const :tag "List them, indented with leading dots" indented)))
3057 (defcustom org-tags-sort-function nil
3058 "When set, tags are sorted using this function as a comparator."
3059 :group 'org-tags
3060 :type '(choice
3061 (const :tag "No sorting" nil)
3062 (const :tag "Alphabetical" string<)
3063 (const :tag "Reverse alphabetical" string>)
3064 (function :tag "Custom function" nil)))
3066 (defvar org-tags-history nil
3067 "History of minibuffer reads for tags.")
3068 (defvar org-last-tags-completion-table nil
3069 "The last used completion table for tags.")
3070 (defvar org-after-tags-change-hook nil
3071 "Hook that is run after the tags in a line have changed.")
3073 (defgroup org-properties nil
3074 "Options concerning properties in Org-mode."
3075 :tag "Org Properties"
3076 :group 'org)
3078 (defcustom org-property-format "%-10s %s"
3079 "How property key/value pairs should be formatted by `indent-line'.
3080 When `indent-line' hits a property definition, it will format the line
3081 according to this format, mainly to make sure that the values are
3082 lined-up with respect to each other."
3083 :group 'org-properties
3084 :type 'string)
3086 (defcustom org-properties-postprocess-alist nil
3087 "Alist of properties and functions to adjust inserted values.
3088 Elements of this alist must be of the form
3090 ([string] [function])
3092 where [string] must be a property name and [function] must be a
3093 lambda expression: this lambda expression must take one argument,
3094 the value to adjust, and return the new value as a string.
3096 For example, this element will allow the property \"Remaining\"
3097 to be updated wrt the relation between the \"Effort\" property
3098 and the clock summary:
3100 ((\"Remaining\" (lambda(value)
3101 (let ((clocksum (org-clock-sum-current-item))
3102 (effort (org-duration-string-to-minutes
3103 (org-entry-get (point) \"Effort\"))))
3104 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3105 :group 'org-properties
3106 :version "24.1"
3107 :type '(alist :key-type (string :tag "Property")
3108 :value-type (function :tag "Function")))
3110 (defcustom org-use-property-inheritance nil
3111 "Non-nil means properties apply also for sublevels.
3113 This setting is chiefly used during property searches. Turning it on can
3114 cause significant overhead when doing a search, which is why it is not
3115 on by default.
3117 When nil, only the properties directly given in the current entry count.
3118 When t, every property is inherited. The value may also be a list of
3119 properties that should have inheritance, or a regular expression matching
3120 properties that should be inherited.
3122 However, note that some special properties use inheritance under special
3123 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3124 and the properties ending in \"_ALL\" when they are used as descriptor
3125 for valid values of a property.
3127 Note for programmers:
3128 When querying an entry with `org-entry-get', you can control if inheritance
3129 should be used. By default, `org-entry-get' looks only at the local
3130 properties. You can request inheritance by setting the inherit argument
3131 to t (to force inheritance) or to `selective' (to respect the setting
3132 in this variable)."
3133 :group 'org-properties
3134 :type '(choice
3135 (const :tag "Not" nil)
3136 (const :tag "Always" t)
3137 (repeat :tag "Specific properties" (string :tag "Property"))
3138 (regexp :tag "Properties matched by regexp")))
3140 (defun org-property-inherit-p (property)
3141 "Check if PROPERTY is one that should be inherited."
3142 (cond
3143 ((eq org-use-property-inheritance t) t)
3144 ((not org-use-property-inheritance) nil)
3145 ((stringp org-use-property-inheritance)
3146 (string-match org-use-property-inheritance property))
3147 ((listp org-use-property-inheritance)
3148 (member property org-use-property-inheritance))
3149 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3151 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3152 "The default column format, if no other format has been defined.
3153 This variable can be set on the per-file basis by inserting a line
3155 #+COLUMNS: %25ITEM ....."
3156 :group 'org-properties
3157 :type 'string)
3159 (defcustom org-columns-ellipses ".."
3160 "The ellipses to be used when a field in column view is truncated.
3161 When this is the empty string, as many characters as possible are shown,
3162 but then there will be no visual indication that the field has been truncated.
3163 When this is a string of length N, the last N characters of a truncated
3164 field are replaced by this string. If the column is narrower than the
3165 ellipses string, only part of the ellipses string will be shown."
3166 :group 'org-properties
3167 :type 'string)
3169 (defcustom org-columns-modify-value-for-display-function nil
3170 "Function that modifies values for display in column view.
3171 For example, it can be used to cut out a certain part from a time stamp.
3172 The function must take 2 arguments:
3174 column-title The title of the column (*not* the property name)
3175 value The value that should be modified.
3177 The function should return the value that should be displayed,
3178 or nil if the normal value should be used."
3179 :group 'org-properties
3180 :type 'function)
3182 (defcustom org-effort-property "Effort"
3183 "The property that is being used to keep track of effort estimates.
3184 Effort estimates given in this property need to have the format H:MM."
3185 :group 'org-properties
3186 :group 'org-progress
3187 :type '(string :tag "Property"))
3189 (defconst org-global-properties-fixed
3190 '(("VISIBILITY_ALL" . "folded children content all")
3191 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3192 "List of property/value pairs that can be inherited by any entry.
3194 These are fixed values, for the preset properties. The user variable
3195 that can be used to add to this list is `org-global-properties'.
3197 The entries in this list are cons cells where the car is a property
3198 name and cdr is a string with the value. If the value represents
3199 multiple items like an \"_ALL\" property, separate the items by
3200 spaces.")
3202 (defcustom org-global-properties nil
3203 "List of property/value pairs that can be inherited by any entry.
3205 This list will be combined with the constant `org-global-properties-fixed'.
3207 The entries in this list are cons cells where the car is a property
3208 name and cdr is a string with the value.
3210 You can set buffer-local values for the same purpose in the variable
3211 `org-file-properties' this by adding lines like
3213 #+PROPERTY: NAME VALUE"
3214 :group 'org-properties
3215 :type '(repeat
3216 (cons (string :tag "Property")
3217 (string :tag "Value"))))
3219 (defvar org-file-properties nil
3220 "List of property/value pairs that can be inherited by any entry.
3221 Valid for the current buffer.
3222 This variable is populated from #+PROPERTY lines.")
3223 (make-variable-buffer-local 'org-file-properties)
3225 (defgroup org-agenda nil
3226 "Options concerning agenda views in Org-mode."
3227 :tag "Org Agenda"
3228 :group 'org)
3230 (defvar org-category nil
3231 "Variable used by org files to set a category for agenda display.
3232 Such files should use a file variable to set it, for example
3234 # -*- mode: org; org-category: \"ELisp\"
3236 or contain a special line
3238 #+CATEGORY: ELisp
3240 If the file does not specify a category, then file's base name
3241 is used instead.")
3242 (make-variable-buffer-local 'org-category)
3243 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3245 (defcustom org-agenda-files nil
3246 "The files to be used for agenda display.
3247 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3248 \\[org-remove-file]. You can also use customize to edit the list.
3250 If an entry is a directory, all files in that directory that are matched by
3251 `org-agenda-file-regexp' will be part of the file list.
3253 If the value of the variable is not a list but a single file name, then
3254 the list of agenda files is actually stored and maintained in that file, one
3255 agenda file per line. In this file paths can be given relative to
3256 `org-directory'. Tilde expansion and environment variable substitution
3257 are also made."
3258 :group 'org-agenda
3259 :type '(choice
3260 (repeat :tag "List of files and directories" file)
3261 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3263 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3264 "Regular expression to match files for `org-agenda-files'.
3265 If any element in the list in that variable contains a directory instead
3266 of a normal file, all files in that directory that are matched by this
3267 regular expression will be included."
3268 :group 'org-agenda
3269 :type 'regexp)
3271 (defcustom org-agenda-text-search-extra-files nil
3272 "List of extra files to be searched by text search commands.
3273 These files will be search in addition to the agenda files by the
3274 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3275 Note that these files will only be searched for text search commands,
3276 not for the other agenda views like todo lists, tag searches or the weekly
3277 agenda. This variable is intended to list notes and possibly archive files
3278 that should also be searched by these two commands.
3279 In fact, if the first element in the list is the symbol `agenda-archives',
3280 than all archive files of all agenda files will be added to the search
3281 scope."
3282 :group 'org-agenda
3283 :type '(set :greedy t
3284 (const :tag "Agenda Archives" agenda-archives)
3285 (repeat :inline t (file))))
3287 (if (fboundp 'defvaralias)
3288 (defvaralias 'org-agenda-multi-occur-extra-files
3289 'org-agenda-text-search-extra-files))
3291 (defcustom org-agenda-skip-unavailable-files nil
3292 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3293 A nil value means to remove them, after a query, from the list."
3294 :group 'org-agenda
3295 :type 'boolean)
3297 (defcustom org-calendar-to-agenda-key [?c]
3298 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3299 The command `org-calendar-goto-agenda' will be bound to this key. The
3300 default is the character `c' because then `c' can be used to switch back and
3301 forth between agenda and calendar."
3302 :group 'org-agenda
3303 :type 'sexp)
3305 (defcustom org-calendar-agenda-action-key [?k]
3306 "The key to be installed in `calendar-mode-map' for agenda-action.
3307 The command `org-agenda-action' will be bound to this key. The
3308 default is the character `k' because we use the same key in the agenda."
3309 :group 'org-agenda
3310 :type 'sexp)
3312 (defcustom org-calendar-insert-diary-entry-key [?i]
3313 "The key to be installed in `calendar-mode-map' for adding diary entries.
3314 This option is irrelevant until `org-agenda-diary-file' has been configured
3315 to point to an Org-mode file. When that is the case, the command
3316 `org-agenda-diary-entry' will be bound to the key given here, by default
3317 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3318 if you want to continue doing this, you need to change this to a different
3319 key."
3320 :group 'org-agenda
3321 :type 'sexp)
3323 (defcustom org-agenda-diary-file 'diary-file
3324 "File to which to add new entries with the `i' key in agenda and calendar.
3325 When this is the symbol `diary-file', the functionality in the Emacs
3326 calendar will be used to add entries to the `diary-file'. But when this
3327 points to a file, `org-agenda-diary-entry' will be used instead."
3328 :group 'org-agenda
3329 :type '(choice
3330 (const :tag "The standard Emacs diary file" diary-file)
3331 (file :tag "Special Org file diary entries")))
3333 (eval-after-load "calendar"
3334 '(progn
3335 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3336 'org-calendar-goto-agenda)
3337 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3338 'org-agenda-action)
3339 (add-hook 'calendar-mode-hook
3340 (lambda ()
3341 (unless (eq org-agenda-diary-file 'diary-file)
3342 (define-key calendar-mode-map
3343 org-calendar-insert-diary-entry-key
3344 'org-agenda-diary-entry))))))
3346 (defgroup org-latex nil
3347 "Options for embedding LaTeX code into Org-mode."
3348 :tag "Org LaTeX"
3349 :group 'org)
3351 (defcustom org-format-latex-options
3352 '(:foreground default :background default :scale 1.0
3353 :html-foreground "Black" :html-background "Transparent"
3354 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3355 "Options for creating images from LaTeX fragments.
3356 This is a property list with the following properties:
3357 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3358 `default' means use the foreground of the default face.
3359 :background the background color, or \"Transparent\".
3360 `default' means use the background of the default face.
3361 :scale a scaling factor for the size of the images, to get more pixels
3362 :html-foreground, :html-background, :html-scale
3363 the same numbers for HTML export.
3364 :matchers a list indicating which matchers should be used to
3365 find LaTeX fragments. Valid members of this list are:
3366 \"begin\" find environments
3367 \"$1\" find single characters surrounded by $.$
3368 \"$\" find math expressions surrounded by $...$
3369 \"$$\" find math expressions surrounded by $$....$$
3370 \"\\(\" find math expressions surrounded by \\(...\\)
3371 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3372 :group 'org-latex
3373 :type 'plist)
3375 (defcustom org-format-latex-signal-error t
3376 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3377 When nil, just push out a message."
3378 :group 'org-latex
3379 :version "24.1"
3380 :type 'boolean)
3382 (defcustom org-latex-to-mathml-jar-file nil
3383 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3384 Use this to specify additional executable file say a jar file.
3386 When using MathToWeb as the converter, specify the full-path to
3387 your mathtoweb.jar file."
3388 :group 'org-latex
3389 :version "24.1"
3390 :type '(choice
3391 (const :tag "None" nil)
3392 (file :tag "JAR file" :must-match t)))
3394 (defcustom org-latex-to-mathml-convert-command nil
3395 "Command to convert LaTeX fragments to MathML.
3396 Replace format-specifiers in the command as noted below and use
3397 `shell-command' to convert LaTeX to MathML.
3398 %j: Executable file in fully expanded form as specified by
3399 `org-latex-to-mathml-jar-file'.
3400 %I: Input LaTeX file in fully expanded form
3401 %o: Output MathML file
3402 This command is used by `org-create-math-formula'.
3404 When using MathToWeb as the converter, set this to
3405 \"java -jar %j -unicode -force -df %o %I\"."
3406 :group 'org-latex
3407 :version "24.1"
3408 :type '(choice
3409 (const :tag "None" nil)
3410 (string :tag "\nShell command")))
3412 (defcustom org-latex-create-formula-image-program 'dvipng
3413 "Program to convert LaTeX fragments with.
3415 dvipng Process the LaTeX fragments to dvi file, then convert
3416 dvi files to png files using dvipng.
3417 This will also include processing of non-math environments.
3418 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3419 to convert pdf files to png files"
3420 :group 'org-latex
3421 :version "24.1"
3422 :type '(choice
3423 (const :tag "dvipng" dvipng)
3424 (const :tag "imagemagick" imagemagick)))
3426 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3427 "Path to store latex preview images. A relative path here creates many
3428 directories relative to the processed org files paths. An absolute path
3429 puts all preview images at the same place."
3430 :group 'org-latex
3431 ;; :version "24.3"
3432 :type 'string)
3434 (defun org-format-latex-mathml-available-p ()
3435 "Return t if `org-latex-to-mathml-convert-command' is usable."
3436 (save-match-data
3437 (when (and (boundp 'org-latex-to-mathml-convert-command)
3438 org-latex-to-mathml-convert-command)
3439 (let ((executable (car (split-string
3440 org-latex-to-mathml-convert-command))))
3441 (when (executable-find executable)
3442 (if (string-match
3443 "%j" org-latex-to-mathml-convert-command)
3444 (file-readable-p org-latex-to-mathml-jar-file)
3445 t))))))
3447 (defcustom org-format-latex-header "\\documentclass{article}
3448 \\usepackage[usenames]{color}
3449 \\usepackage{amsmath}
3450 \\usepackage[mathscr]{eucal}
3451 \\pagestyle{empty} % do not remove
3452 \[PACKAGES]
3453 \[DEFAULT-PACKAGES]
3454 % The settings below are copied from fullpage.sty
3455 \\setlength{\\textwidth}{\\paperwidth}
3456 \\addtolength{\\textwidth}{-3cm}
3457 \\setlength{\\oddsidemargin}{1.5cm}
3458 \\addtolength{\\oddsidemargin}{-2.54cm}
3459 \\setlength{\\evensidemargin}{\\oddsidemargin}
3460 \\setlength{\\textheight}{\\paperheight}
3461 \\addtolength{\\textheight}{-\\headheight}
3462 \\addtolength{\\textheight}{-\\headsep}
3463 \\addtolength{\\textheight}{-\\footskip}
3464 \\addtolength{\\textheight}{-3cm}
3465 \\setlength{\\topmargin}{1.5cm}
3466 \\addtolength{\\topmargin}{-2.54cm}"
3467 "The document header used for processing LaTeX fragments.
3468 It is imperative that this header make sure that no page number
3469 appears on the page. The package defined in the variables
3470 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3471 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3472 will be appended."
3473 :group 'org-latex
3474 :type 'string)
3476 (defvar org-format-latex-header-extra nil)
3478 (defun org-set-packages-alist (var val)
3479 "Set the packages alist and make sure it has 3 elements per entry."
3480 (set var (mapcar (lambda (x)
3481 (if (and (consp x) (= (length x) 2))
3482 (list (car x) (nth 1 x) t)
3484 val)))
3486 (defun org-get-packages-alist (var)
3488 "Get the packages alist and make sure it has 3 elements per entry."
3489 (mapcar (lambda (x)
3490 (if (and (consp x) (= (length x) 2))
3491 (list (car x) (nth 1 x) t)
3493 (default-value var)))
3495 ;; The following variables are defined here because is it also used
3496 ;; when formatting latex fragments. Originally it was part of the
3497 ;; LaTeX exporter, which is why the name includes "export".
3498 (defcustom org-export-latex-default-packages-alist
3499 '(("AUTO" "inputenc" t)
3500 ("T1" "fontenc" t)
3501 ("" "fixltx2e" nil)
3502 ("" "graphicx" t)
3503 ("" "longtable" nil)
3504 ("" "float" nil)
3505 ("" "wrapfig" nil)
3506 ("" "soul" t)
3507 ("" "textcomp" t)
3508 ("" "marvosym" t)
3509 ("" "wasysym" t)
3510 ("" "latexsym" t)
3511 ("" "amssymb" t)
3512 ("" "hyperref" nil)
3513 "\\tolerance=1000"
3515 "Alist of default packages to be inserted in the header.
3516 Change this only if one of the packages here causes an incompatibility
3517 with another package you are using.
3518 The packages in this list are needed by one part or another of Org-mode
3519 to function properly.
3521 - inputenc, fontenc: for basic font and character selection
3522 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3523 for interpreting the entities in `org-entities'. You can skip some of these
3524 packages if you don't use any of the symbols in it.
3525 - graphicx: for including images
3526 - float, wrapfig: for figure placement
3527 - longtable: for long tables
3528 - hyperref: for cross references
3530 Therefore you should not modify this variable unless you know what you
3531 are doing. The one reason to change it anyway is that you might be loading
3532 some other package that conflicts with one of the default packages.
3533 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3534 If SNIPPET-FLAG is t, the package also needs to be included when
3535 compiling LaTeX snippets into images for inclusion into HTML."
3536 :group 'org-export-latex
3537 :set 'org-set-packages-alist
3538 :get 'org-get-packages-alist
3539 :version "24.1"
3540 :type '(repeat
3541 (choice
3542 (list :tag "options/package pair"
3543 (string :tag "options")
3544 (string :tag "package")
3545 (boolean :tag "Snippet"))
3546 (string :tag "A line of LaTeX"))))
3548 (defcustom org-export-latex-packages-alist nil
3549 "Alist of packages to be inserted in every LaTeX header.
3550 These will be inserted after `org-export-latex-default-packages-alist'.
3551 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3552 SNIPPET-FLAG, when t, indicates that this package is also needed when
3553 turning LaTeX snippets into images for inclusion into HTML.
3554 Make sure that you only list packages here which:
3555 - you want in every file
3556 - do not conflict with the default packages in
3557 `org-export-latex-default-packages-alist'
3558 - do not conflict with the setup in `org-format-latex-header'."
3559 :group 'org-export-latex
3560 :set 'org-set-packages-alist
3561 :get 'org-get-packages-alist
3562 :type '(repeat
3563 (choice
3564 (list :tag "options/package pair"
3565 (string :tag "options")
3566 (string :tag "package")
3567 (boolean :tag "Snippet"))
3568 (string :tag "A line of LaTeX"))))
3571 (defgroup org-appearance nil
3572 "Settings for Org-mode appearance."
3573 :tag "Org Appearance"
3574 :group 'org)
3576 (defcustom org-level-color-stars-only nil
3577 "Non-nil means fontify only the stars in each headline.
3578 When nil, the entire headline is fontified.
3579 Changing it requires restart of `font-lock-mode' to become effective
3580 also in regions already fontified."
3581 :group 'org-appearance
3582 :type 'boolean)
3584 (defcustom org-hide-leading-stars nil
3585 "Non-nil means hide the first N-1 stars in a headline.
3586 This works by using the face `org-hide' for these stars. This
3587 face is white for a light background, and black for a dark
3588 background. You may have to customize the face `org-hide' to
3589 make this work.
3590 Changing it requires restart of `font-lock-mode' to become effective
3591 also in regions already fontified.
3592 You may also set this on a per-file basis by adding one of the following
3593 lines to the buffer:
3595 #+STARTUP: hidestars
3596 #+STARTUP: showstars"
3597 :group 'org-appearance
3598 :type 'boolean)
3600 (defcustom org-hidden-keywords nil
3601 "List of symbols corresponding to keywords to be hidden the org buffer.
3602 For example, a value '(title) for this list will make the document's title
3603 appear in the buffer without the initial #+TITLE: keyword."
3604 :group 'org-appearance
3605 :version "24.1"
3606 :type '(set (const :tag "#+AUTHOR" author)
3607 (const :tag "#+DATE" date)
3608 (const :tag "#+EMAIL" email)
3609 (const :tag "#+TITLE" title)))
3611 (defcustom org-custom-properties nil
3612 "List of properties (as strings) with a special meaning.
3613 The default use of these custom properties is to let the user
3614 hide them with `org-toggle-custom-properties-visibility'."
3615 :group 'org-properties
3616 :group 'org-appearance
3617 ;; :version "24.3"
3618 :type '(repeat (string :tag "Property Name")))
3620 (defcustom org-fontify-done-headline nil
3621 "Non-nil means change the face of a headline if it is marked DONE.
3622 Normally, only the TODO/DONE keyword indicates the state of a headline.
3623 When this is non-nil, the headline after the keyword is set to the
3624 `org-headline-done' as an additional indication."
3625 :group 'org-appearance
3626 :type 'boolean)
3628 (defcustom org-fontify-emphasized-text t
3629 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3630 Changing this variable requires a restart of Emacs to take effect."
3631 :group 'org-appearance
3632 :type 'boolean)
3634 (defcustom org-fontify-whole-heading-line nil
3635 "Non-nil means fontify the whole line for headings.
3636 This is useful when setting a background color for the
3637 org-level-* faces."
3638 :group 'org-appearance
3639 :type 'boolean)
3641 (defcustom org-highlight-latex-fragments-and-specials nil
3642 "Non-nil means fontify what is treated specially by the exporters."
3643 :group 'org-appearance
3644 :type 'boolean)
3646 (defcustom org-hide-emphasis-markers nil
3647 "Non-nil mean font-lock should hide the emphasis marker characters."
3648 :group 'org-appearance
3649 :type 'boolean)
3651 (defcustom org-pretty-entities nil
3652 "Non-nil means show entities as UTF8 characters.
3653 When nil, the \\name form remains in the buffer."
3654 :group 'org-appearance
3655 :version "24.1"
3656 :type 'boolean)
3658 (defcustom org-pretty-entities-include-sub-superscripts t
3659 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3660 :group 'org-appearance
3661 :version "24.1"
3662 :type 'boolean)
3664 (defvar org-emph-re nil
3665 "Regular expression for matching emphasis.
3666 After a match, the match groups contain these elements:
3667 0 The match of the full regular expression, including the characters
3668 before and after the proper match
3669 1 The character before the proper match, or empty at beginning of line
3670 2 The proper match, including the leading and trailing markers
3671 3 The leading marker like * or /, indicating the type of highlighting
3672 4 The text between the emphasis markers, not including the markers
3673 5 The character after the match, empty at the end of a line")
3674 (defvar org-verbatim-re nil
3675 "Regular expression for matching verbatim text.")
3676 (defvar org-emphasis-regexp-components) ; defined just below
3677 (defvar org-emphasis-alist) ; defined just below
3678 (defun org-set-emph-re (var val)
3679 "Set variable and compute the emphasis regular expression."
3680 (set var val)
3681 (when (and (boundp 'org-emphasis-alist)
3682 (boundp 'org-emphasis-regexp-components)
3683 org-emphasis-alist org-emphasis-regexp-components)
3684 (let* ((e org-emphasis-regexp-components)
3685 (pre (car e))
3686 (post (nth 1 e))
3687 (border (nth 2 e))
3688 (body (nth 3 e))
3689 (nl (nth 4 e))
3690 (body1 (concat body "*?"))
3691 (markers (mapconcat 'car org-emphasis-alist ""))
3692 (vmarkers (mapconcat
3693 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3694 org-emphasis-alist "")))
3695 ;; make sure special characters appear at the right position in the class
3696 (if (string-match "\\^" markers)
3697 (setq markers (concat (replace-match "" t t markers) "^")))
3698 (if (string-match "-" markers)
3699 (setq markers (concat (replace-match "" t t markers) "-")))
3700 (if (string-match "\\^" vmarkers)
3701 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3702 (if (string-match "-" vmarkers)
3703 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3704 (if (> nl 0)
3705 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3706 (int-to-string nl) "\\}")))
3707 ;; Make the regexp
3708 (setq org-emph-re
3709 (concat "\\([" pre "]\\|^\\)"
3710 "\\("
3711 "\\([" markers "]\\)"
3712 "\\("
3713 "[^" border "]\\|"
3714 "[^" border "]"
3715 body1
3716 "[^" border "]"
3717 "\\)"
3718 "\\3\\)"
3719 "\\([" post "]\\|$\\)"))
3720 (setq org-verbatim-re
3721 (concat "\\([" pre "]\\|^\\)"
3722 "\\("
3723 "\\([" vmarkers "]\\)"
3724 "\\("
3725 "[^" border "]\\|"
3726 "[^" border "]"
3727 body1
3728 "[^" border "]"
3729 "\\)"
3730 "\\3\\)"
3731 "\\([" post "]\\|$\\)")))))
3733 (defcustom org-emphasis-regexp-components
3734 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3735 "Components used to build the regular expression for emphasis.
3736 This is a list with five entries. Terminology: In an emphasis string
3737 like \" *strong word* \", we call the initial space PREMATCH, the final
3738 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3739 and \"trong wor\" is the body. The different components in this variable
3740 specify what is allowed/forbidden in each part:
3742 pre Chars allowed as prematch. Beginning of line will be allowed too.
3743 post Chars allowed as postmatch. End of line will be allowed too.
3744 border The chars *forbidden* as border characters.
3745 body-regexp A regexp like \".\" to match a body character. Don't use
3746 non-shy groups here, and don't allow newline here.
3747 newline The maximum number of newlines allowed in an emphasis exp.
3749 Use customize to modify this, or restart Emacs after changing it."
3750 :group 'org-appearance
3751 :set 'org-set-emph-re
3752 :type '(list
3753 (sexp :tag "Allowed chars in pre ")
3754 (sexp :tag "Allowed chars in post ")
3755 (sexp :tag "Forbidden chars in border ")
3756 (sexp :tag "Regexp for body ")
3757 (integer :tag "number of newlines allowed")
3758 (option (boolean :tag "Please ignore this button"))))
3760 (defcustom org-emphasis-alist
3761 `(("*" bold "<b>" "</b>")
3762 ("/" italic "<i>" "</i>")
3763 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3764 ("=" org-code "<code>" "</code>" verbatim)
3765 ("~" org-verbatim "<code>" "</code>" verbatim)
3766 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3767 "<del>" "</del>")
3769 "Special syntax for emphasized text.
3770 Text starting and ending with a special character will be emphasized, for
3771 example *bold*, _underlined_ and /italic/. This variable sets the marker
3772 characters, the face to be used by font-lock for highlighting in Org-mode
3773 Emacs buffers, and the HTML tags to be used for this.
3774 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3775 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3776 Use customize to modify this, or restart Emacs after changing it."
3777 :group 'org-appearance
3778 :set 'org-set-emph-re
3779 :type '(repeat
3780 (list
3781 (string :tag "Marker character")
3782 (choice
3783 (face :tag "Font-lock-face")
3784 (plist :tag "Face property list"))
3785 (string :tag "HTML start tag")
3786 (string :tag "HTML end tag")
3787 (option (const verbatim)))))
3789 (defvar org-protecting-blocks
3790 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3791 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3792 This is needed for font-lock setup.")
3794 ;;; Miscellaneous options
3796 (defgroup org-completion nil
3797 "Completion in Org-mode."
3798 :tag "Org Completion"
3799 :group 'org)
3801 (defcustom org-completion-use-ido nil
3802 "Non-nil means use ido completion wherever possible.
3803 Note that `ido-mode' must be active for this variable to be relevant.
3804 If you decide to turn this variable on, you might well want to turn off
3805 `org-outline-path-complete-in-steps'.
3806 See also `org-completion-use-iswitchb'."
3807 :group 'org-completion
3808 :type 'boolean)
3810 (defcustom org-completion-use-iswitchb nil
3811 "Non-nil means use iswitchb completion wherever possible.
3812 Note that `iswitchb-mode' must be active for this variable to be relevant.
3813 If you decide to turn this variable on, you might well want to turn off
3814 `org-outline-path-complete-in-steps'.
3815 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3816 :group 'org-completion
3817 :type 'boolean)
3819 (defcustom org-completion-fallback-command 'hippie-expand
3820 "The expansion command called by \\[pcomplete] in normal context.
3821 Normal means, no org-mode-specific context."
3822 :group 'org-completion
3823 :type 'function)
3825 ;;; Functions and variables from their packages
3826 ;; Declared here to avoid compiler warnings
3828 ;; XEmacs only
3829 (defvar outline-mode-menu-heading)
3830 (defvar outline-mode-menu-show)
3831 (defvar outline-mode-menu-hide)
3832 (defvar zmacs-regions) ; XEmacs regions
3834 ;; Emacs only
3835 (defvar mark-active)
3837 ;; Various packages
3838 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3839 (declare-function calendar-forward-day "cal-move" (arg))
3840 (declare-function calendar-goto-date "cal-move" (date))
3841 (declare-function calendar-goto-today "cal-move" ())
3842 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3843 (defvar calc-embedded-close-formula)
3844 (defvar calc-embedded-open-formula)
3845 (declare-function cdlatex-tab "ext:cdlatex" ())
3846 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3847 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3848 (defvar font-lock-unfontify-region-function)
3849 (declare-function iswitchb-read-buffer "iswitchb"
3850 (prompt &optional default require-match start matches-set))
3851 (defvar iswitchb-temp-buflist)
3852 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3853 (defvar org-agenda-tags-todo-honor-ignore-options)
3854 (declare-function org-agenda-skip "org-agenda" ())
3855 (declare-function
3856 org-agenda-format-item "org-agenda"
3857 (extra txt &optional category tags dotime noprefix remove-re habitp))
3858 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3859 (declare-function org-agenda-change-all-lines "org-agenda"
3860 (newhead hdmarker &optional fixface just-this))
3861 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3862 (declare-function org-agenda-maybe-redo "org-agenda" ())
3863 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3864 (beg end))
3865 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3866 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3867 "org-agenda" (&optional end))
3868 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3869 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3870 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3871 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3872 (declare-function org-indent-mode "org-indent" (&optional arg))
3873 (declare-function parse-time-string "parse-time" (string))
3874 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3875 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3876 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3877 (defvar remember-data-file)
3878 (defvar texmathp-why)
3879 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3880 (declare-function table--at-cell-p "table" (position &optional object at-column))
3882 (defvar w3m-current-url)
3883 (defvar w3m-current-title)
3885 (defvar org-latex-regexps)
3887 ;;; Autoload and prepare some org modules
3889 ;; Some table stuff that needs to be defined here, because it is used
3890 ;; by the functions setting up org-mode or checking for table context.
3892 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3893 "Detect an org-type or table-type table.")
3894 (defconst org-table-line-regexp "^[ \t]*|"
3895 "Detect an org-type table line.")
3896 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3897 "Detect an org-type table line.")
3898 (defconst org-table-hline-regexp "^[ \t]*|-"
3899 "Detect an org-type table hline.")
3900 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3901 "Detect a table-type table hline.")
3902 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3903 "Detect the first line outside a table when searching from within it.
3904 This works for both table types.")
3906 ;; Autoload the functions in org-table.el that are needed by functions here.
3908 (eval-and-compile
3909 (org-autoload "org-table"
3910 '(org-table-align org-table-begin org-table-blank-field
3911 org-table-convert org-table-convert-region org-table-copy-down
3912 org-table-copy-region org-table-create
3913 org-table-create-or-convert-from-region
3914 org-table-create-with-table.el org-table-current-dline
3915 org-table-cut-region org-table-delete-column org-table-edit-field
3916 org-table-edit-formulas org-table-end org-table-eval-formula
3917 org-table-export org-table-field-info
3918 org-table-get-stored-formulas org-table-goto-column
3919 org-table-hline-and-move org-table-import org-table-insert-column
3920 org-table-insert-hline org-table-insert-row org-table-iterate
3921 org-table-justify-field-maybe org-table-kill-row
3922 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3923 org-table-move-column org-table-move-column-left
3924 org-table-move-column-right org-table-move-row
3925 org-table-move-row-down org-table-move-row-up
3926 org-table-next-field org-table-next-row org-table-paste-rectangle
3927 org-table-previous-field org-table-recalculate
3928 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3929 org-table-toggle-coordinate-overlays
3930 org-table-toggle-formula-debugger org-table-wrap-region
3931 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3932 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3933 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3935 (defun org-at-table-p (&optional table-type)
3936 "Return t if the cursor is inside an org-type table.
3937 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3938 (if org-enable-table-editor
3939 (save-excursion
3940 (beginning-of-line 1)
3941 (looking-at (if table-type org-table-any-line-regexp
3942 org-table-line-regexp)))
3943 nil))
3944 (defsubst org-table-p () (org-at-table-p))
3946 (defun org-at-table.el-p ()
3947 "Return t if and only if we are at a table.el table."
3948 (and (org-at-table-p 'any)
3949 (save-excursion
3950 (goto-char (org-table-begin 'any))
3951 (looking-at org-table1-hline-regexp))))
3952 (defun org-table-recognize-table.el ()
3953 "If there is a table.el table nearby, recognize it and move into it."
3954 (if org-table-tab-recognizes-table.el
3955 (if (org-at-table.el-p)
3956 (progn
3957 (beginning-of-line 1)
3958 (if (looking-at org-table-dataline-regexp)
3960 (if (looking-at org-table1-hline-regexp)
3961 (progn
3962 (beginning-of-line 2)
3963 (if (looking-at org-table-any-border-regexp)
3964 (beginning-of-line -1)))))
3965 (if (re-search-forward "|" (org-table-end t) t)
3966 (progn
3967 (require 'table)
3968 (if (table--at-cell-p (point))
3970 (message "recognizing table.el table...")
3971 (table-recognize-table)
3972 (message "recognizing table.el table...done")))
3973 (error "This should not happen"))
3975 nil)
3976 nil))
3978 (defun org-at-table-hline-p ()
3979 "Return t if the cursor is inside a hline in a table."
3980 (if org-enable-table-editor
3981 (save-excursion
3982 (beginning-of-line 1)
3983 (looking-at org-table-hline-regexp))
3984 nil))
3986 (defvar org-table-clean-did-remove-column nil)
3988 (defun org-table-map-tables (function &optional quietly)
3989 "Apply FUNCTION to the start of all tables in the buffer."
3990 (save-excursion
3991 (save-restriction
3992 (widen)
3993 (goto-char (point-min))
3994 (while (re-search-forward org-table-any-line-regexp nil t)
3995 (unless quietly
3996 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3997 (beginning-of-line 1)
3998 (when (and (looking-at org-table-line-regexp)
3999 ;; Exclude tables in src/example/verbatim/clocktable blocks
4000 (not (org-in-block-p '("src" "example"))))
4001 (save-excursion (funcall function))
4002 (or (looking-at org-table-line-regexp)
4003 (forward-char 1)))
4004 (re-search-forward org-table-any-border-regexp nil 1))))
4005 (unless quietly (message "Mapping tables: done")))
4007 ;; Declare and autoload functions from org-exp.el & Co
4009 (declare-function org-default-export-plist "org-exp")
4010 (declare-function org-infile-export-plist "org-exp")
4011 (declare-function org-get-current-options "org-exp")
4012 (eval-and-compile
4013 (org-autoload "org-exp"
4014 '(org-export org-export-visible
4015 org-insert-export-options-template
4016 org-table-clean-before-export))
4017 (org-autoload "org-ascii"
4018 '(org-export-as-ascii org-export-ascii-preprocess
4019 org-export-as-ascii-to-buffer org-replace-region-by-ascii
4020 org-export-region-as-ascii))
4021 (org-autoload "org-latex"
4022 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4023 org-replace-region-by-latex org-export-region-as-latex
4024 org-export-as-latex org-export-as-pdf
4025 org-export-as-pdf-and-open))
4026 (org-autoload "org-html"
4027 '(org-export-as-html-and-open
4028 org-export-as-html-batch org-export-as-html-to-buffer
4029 org-replace-region-by-html org-export-region-as-html
4030 org-export-as-html))
4031 (org-autoload "org-docbook"
4032 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4033 org-replace-region-by-docbook org-export-region-as-docbook
4034 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4035 org-export-as-docbook))
4036 (org-autoload "org-icalendar"
4037 '(org-export-icalendar-this-file
4038 org-export-icalendar-all-agenda-files
4039 org-export-icalendar-combine-agenda-files))
4040 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4041 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4043 ;; Declare and autoload functions from org-agenda.el
4045 (eval-and-compile
4046 (org-autoload "org-agenda"
4047 '(org-agenda org-agenda-list org-search-view
4048 org-todo-list org-tags-view org-agenda-list-stuck-projects
4049 org-diary org-agenda-to-appt
4050 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4052 ;; Autoload org-remember
4054 (eval-and-compile
4055 (org-autoload "org-remember"
4056 '(org-remember-insinuate org-remember-annotation
4057 org-remember-apply-template org-remember org-remember-handler)))
4059 (eval-and-compile
4060 (org-autoload "org-capture"
4061 '(org-capture org-capture-insert-template-here
4062 org-capture-import-remember-templates)))
4064 ;; Autoload org-clock.el
4066 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4067 (beg end))
4068 (declare-function org-clock-update-mode-line "org-clock" ())
4069 (declare-function org-resolve-clocks "org-clock"
4070 (&optional also-non-dangling-p prompt last-valid))
4071 (defvar org-clock-start-time)
4072 (defvar org-clock-marker (make-marker)
4073 "Marker recording the last clock-in.")
4074 (defvar org-clock-hd-marker (make-marker)
4075 "Marker recording the last clock-in, but the headline position.")
4076 (defvar org-clock-heading ""
4077 "The heading of the current clock entry.")
4078 (defun org-clock-is-active ()
4079 "Return non-nil if clock is currently running.
4080 The return value is actually the clock marker."
4081 (marker-buffer org-clock-marker))
4083 (eval-and-compile
4084 (org-autoload
4085 "org-clock"
4086 '(org-clock-in org-clock-out org-clock-cancel
4087 org-clock-goto org-clock-sum org-clock-display
4088 org-clock-remove-overlays org-clock-report
4089 org-clocktable-shift org-dblock-write:clocktable
4090 org-get-clocktable org-resolve-clocks)))
4092 (defun org-clock-update-time-maybe ()
4093 "If this is a CLOCK line, update it and return t.
4094 Otherwise, return nil."
4095 (interactive)
4096 (save-excursion
4097 (beginning-of-line 1)
4098 (skip-chars-forward " \t")
4099 (when (looking-at org-clock-string)
4100 (let ((re (concat "[ \t]*" org-clock-string
4101 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4102 "\\([ \t]*=>.*\\)?\\)?"))
4103 ts te h m s neg)
4104 (cond
4105 ((not (looking-at re))
4106 nil)
4107 ((not (match-end 2))
4108 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4109 (> org-clock-marker (point))
4110 (<= org-clock-marker (point-at-eol)))
4111 ;; The clock is running here
4112 (setq org-clock-start-time
4113 (apply 'encode-time
4114 (org-parse-time-string (match-string 1))))
4115 (org-clock-update-mode-line)))
4117 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4118 (end-of-line 1)
4119 (setq ts (match-string 1)
4120 te (match-string 3))
4121 (setq s (- (org-float-time
4122 (apply 'encode-time (org-parse-time-string te)))
4123 (org-float-time
4124 (apply 'encode-time (org-parse-time-string ts))))
4125 neg (< s 0)
4126 s (abs s)
4127 h (floor (/ s 3600))
4128 s (- s (* 3600 h))
4129 m (floor (/ s 60))
4130 s (- s (* 60 s)))
4131 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4132 t))))))
4134 (defun org-check-running-clock ()
4135 "Check if the current buffer contains the running clock.
4136 If yes, offer to stop it and to save the buffer with the changes."
4137 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4138 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4139 (buffer-name))))
4140 (org-clock-out)
4141 (when (y-or-n-p "Save changed buffer?")
4142 (save-buffer))))
4144 (defun org-clocktable-try-shift (dir n)
4145 "Check if this line starts a clock table, if yes, shift the time block."
4146 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4147 (org-clocktable-shift dir n)))
4149 ;; Autoload org-timer.el
4151 (eval-and-compile
4152 (org-autoload
4153 "org-timer"
4154 '(org-timer-start org-timer org-timer-item
4155 org-timer-change-times-in-region
4156 org-timer-set-timer
4157 org-timer-reset-timers
4158 org-timer-show-remaining-time)))
4160 ;; Autoload org-feed.el
4162 (eval-and-compile
4163 (org-autoload
4164 "org-feed"
4165 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4168 ;; Autoload org-indent.el
4170 ;; Define the variable already here, to make sure we have it.
4171 (defvar org-indent-mode nil
4172 "Non-nil if Org-Indent mode is enabled.
4173 Use the command `org-indent-mode' to change this variable.")
4175 (eval-and-compile
4176 (org-autoload
4177 "org-indent"
4178 '(org-indent-mode)))
4180 ;; Autoload org-mobile.el
4182 (eval-and-compile
4183 (org-autoload
4184 "org-mobile"
4185 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4187 ;; Autoload archiving code
4188 ;; The stuff that is needed for cycling and tags has to be defined here.
4190 (defgroup org-archive nil
4191 "Options concerning archiving in Org-mode."
4192 :tag "Org Archive"
4193 :group 'org-structure)
4195 (defcustom org-archive-location "%s_archive::"
4196 "The location where subtrees should be archived.
4198 The value of this variable is a string, consisting of two parts,
4199 separated by a double-colon. The first part is a filename and
4200 the second part is a headline.
4202 When the filename is omitted, archiving happens in the same file.
4203 %s in the filename will be replaced by the current file
4204 name (without the directory part). Archiving to a different file
4205 is useful to keep archived entries from contributing to the
4206 Org-mode Agenda.
4208 The archived entries will be filed as subtrees of the specified
4209 headline. When the headline is omitted, the subtrees are simply
4210 filed away at the end of the file, as top-level entries. Also in
4211 the heading you can use %s to represent the file name, this can be
4212 useful when using the same archive for a number of different files.
4214 Here are a few examples:
4215 \"%s_archive::\"
4216 If the current file is Projects.org, archive in file
4217 Projects.org_archive, as top-level trees. This is the default.
4219 \"::* Archived Tasks\"
4220 Archive in the current file, under the top-level headline
4221 \"* Archived Tasks\".
4223 \"~/org/archive.org::\"
4224 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4226 \"~/org/archive.org::* From %s\"
4227 Archive in file ~/org/archive.org (absolute path), under headlines
4228 \"From FILENAME\" where file name is the current file name.
4230 \"~/org/datetree.org::datetree/* Finished Tasks\"
4231 The \"datetree/\" string is special, signifying to archive
4232 items to the datetree. Items are placed in either the CLOSED
4233 date of the item, or the current date if there is no CLOSED date.
4234 The heading will be a subentry to the current date. There doesn't
4235 need to be a heading, but there always needs to be a slash after
4236 datetree. For example, to store archived items directly in the
4237 datetree, use \"~/org/datetree.org::datetree/\".
4239 \"basement::** Finished Tasks\"
4240 Archive in file ./basement (relative path), as level 3 trees
4241 below the level 2 heading \"** Finished Tasks\".
4243 You may set this option on a per-file basis by adding to the buffer a
4244 line like
4246 #+ARCHIVE: basement::** Finished Tasks
4248 You may also define it locally for a subtree by setting an ARCHIVE property
4249 in the entry. If such a property is found in an entry, or anywhere up
4250 the hierarchy, it will be used."
4251 :group 'org-archive
4252 :type 'string)
4254 (defcustom org-archive-tag "ARCHIVE"
4255 "The tag that marks a subtree as archived.
4256 An archived subtree does not open during visibility cycling, and does
4257 not contribute to the agenda listings.
4258 After changing this, font-lock must be restarted in the relevant buffers to
4259 get the proper fontification."
4260 :group 'org-archive
4261 :group 'org-keywords
4262 :type 'string)
4264 (defcustom org-agenda-skip-archived-trees t
4265 "Non-nil means the agenda will skip any items located in archived trees.
4266 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4267 variable is no longer recommended, you should leave it at the value t.
4268 Instead, use the key `v' to cycle the archives-mode in the agenda."
4269 :group 'org-archive
4270 :group 'org-agenda-skip
4271 :type 'boolean)
4273 (defcustom org-columns-skip-archived-trees t
4274 "Non-nil means ignore archived trees when creating column view."
4275 :group 'org-archive
4276 :group 'org-properties
4277 :type 'boolean)
4279 (defcustom org-cycle-open-archived-trees nil
4280 "Non-nil means `org-cycle' will open archived trees.
4281 An archived tree is a tree marked with the tag ARCHIVE.
4282 When nil, archived trees will stay folded. You can still open them with
4283 normal outline commands like `show-all', but not with the cycling commands."
4284 :group 'org-archive
4285 :group 'org-cycle
4286 :type 'boolean)
4288 (defcustom org-sparse-tree-open-archived-trees nil
4289 "Non-nil means sparse tree construction shows matches in archived trees.
4290 When nil, matches in these trees are highlighted, but the trees are kept in
4291 collapsed state."
4292 :group 'org-archive
4293 :group 'org-sparse-trees
4294 :type 'boolean)
4296 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4297 "The default date type when building a sparse tree.
4298 When this is nil, a date is a scheduled or a deadline timestamp.
4299 Otherwise, these types are allowed:
4301 all: all timestamps
4302 active: only active timestamps (<...>)
4303 inactive: only inactive timestamps (<...)
4304 scheduled: only scheduled timestamps
4305 deadline: only deadline timestamps"
4306 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4307 (const :tag "All timestamps" all)
4308 (const :tag "Only active timestamps" active)
4309 (const :tag "Only inactive timestamps" inactive)
4310 (const :tag "Only scheduled timestamps" scheduled)
4311 (const :tag "Only deadline timestamps" deadline))
4312 ;; :version "24.3"
4313 :group 'org-sparse-trees)
4315 (defun org-cycle-hide-archived-subtrees (state)
4316 "Re-hide all archived subtrees after a visibility state change."
4317 (when (and (not org-cycle-open-archived-trees)
4318 (not (memq state '(overview folded))))
4319 (save-excursion
4320 (let* ((globalp (memq state '(contents all)))
4321 (beg (if globalp (point-min) (point)))
4322 (end (if globalp (point-max) (org-end-of-subtree t))))
4323 (org-hide-archived-subtrees beg end)
4324 (goto-char beg)
4325 (if (looking-at (concat ".*:" org-archive-tag ":"))
4326 (message "%s" (substitute-command-keys
4327 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4329 (defun org-force-cycle-archived ()
4330 "Cycle subtree even if it is archived."
4331 (interactive)
4332 (setq this-command 'org-cycle)
4333 (let ((org-cycle-open-archived-trees t))
4334 (call-interactively 'org-cycle)))
4336 (defun org-hide-archived-subtrees (beg end)
4337 "Re-hide all archived subtrees after a visibility state change."
4338 (save-excursion
4339 (let* ((re (concat ":" org-archive-tag ":")))
4340 (goto-char beg)
4341 (while (re-search-forward re end t)
4342 (when (org-at-heading-p)
4343 (org-flag-subtree t)
4344 (org-end-of-subtree t))))))
4346 (declare-function outline-end-of-heading "outline" ())
4347 (declare-function outline-flag-region "outline" (from to flag))
4348 (defun org-flag-subtree (flag)
4349 (save-excursion
4350 (org-back-to-heading t)
4351 (outline-end-of-heading)
4352 (outline-flag-region (point)
4353 (progn (org-end-of-subtree t) (point))
4354 flag)))
4356 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4358 (eval-and-compile
4359 (org-autoload "org-archive"
4360 '(org-add-archive-files org-archive-subtree
4361 org-archive-to-archive-sibling org-toggle-archive-tag
4362 org-archive-subtree-default
4363 org-archive-subtree-default-with-confirmation)))
4365 ;; Autoload Column View Code
4367 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4368 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4369 (declare-function org-columns-compute "org-colview" (property))
4371 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4372 '(org-columns-number-to-string org-columns-get-format-and-top-level
4373 org-columns-compute org-agenda-columns org-columns-remove-overlays
4374 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4376 ;; Autoload ID code
4378 (declare-function org-id-store-link "org-id")
4379 (declare-function org-id-locations-load "org-id")
4380 (declare-function org-id-locations-save "org-id")
4381 (defvar org-id-track-globally)
4382 (org-autoload "org-id"
4383 '(org-id-get-create org-id-new org-id-copy org-id-get
4384 org-id-get-with-outline-path-completion
4385 org-id-get-with-outline-drilling org-id-store-link
4386 org-id-goto org-id-find org-id-store-link))
4388 ;; Autoload Plotting Code
4390 (org-autoload "org-plot"
4391 '(org-plot/gnuplot))
4393 ;;; Variables for pre-computed regular expressions, all buffer local
4395 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4396 "Matches first line of a hidden block.")
4397 (make-variable-buffer-local 'org-drawer-regexp)
4398 (defvar org-todo-regexp nil
4399 "Matches any of the TODO state keywords.")
4400 (make-variable-buffer-local 'org-todo-regexp)
4401 (defvar org-not-done-regexp nil
4402 "Matches any of the TODO state keywords except the last one.")
4403 (make-variable-buffer-local 'org-not-done-regexp)
4404 (defvar org-not-done-heading-regexp nil
4405 "Matches a TODO headline that is not done.")
4406 (make-variable-buffer-local 'org-not-done-regexp)
4407 (defvar org-todo-line-regexp nil
4408 "Matches a headline and puts TODO state into group 2 if present.")
4409 (make-variable-buffer-local 'org-todo-line-regexp)
4410 (defvar org-complex-heading-regexp nil
4411 "Matches a headline and puts everything into groups:
4412 group 1: the stars
4413 group 2: The todo keyword, maybe
4414 group 3: Priority cookie
4415 group 4: True headline
4416 group 5: Tags")
4417 (make-variable-buffer-local 'org-complex-heading-regexp)
4418 (defvar org-complex-heading-regexp-format nil
4419 "Printf format to make regexp to match an exact headline.
4420 This regexp will match the headline of any node which has the
4421 exact headline text that is put into the format, but may have any
4422 TODO state, priority and tags.")
4423 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4424 (defvar org-todo-line-tags-regexp nil
4425 "Matches a headline and puts TODO state into group 2 if present.
4426 Also put tags into group 4 if tags are present.")
4427 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4428 (defvar org-ds-keyword-length 12
4429 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4430 (make-variable-buffer-local 'org-ds-keyword-length)
4431 (defvar org-deadline-regexp nil
4432 "Matches the DEADLINE keyword.")
4433 (make-variable-buffer-local 'org-deadline-regexp)
4434 (defvar org-deadline-time-regexp nil
4435 "Matches the DEADLINE keyword together with a time stamp.")
4436 (make-variable-buffer-local 'org-deadline-time-regexp)
4437 (defvar org-deadline-line-regexp nil
4438 "Matches the DEADLINE keyword and the rest of the line.")
4439 (make-variable-buffer-local 'org-deadline-line-regexp)
4440 (defvar org-scheduled-regexp nil
4441 "Matches the SCHEDULED keyword.")
4442 (make-variable-buffer-local 'org-scheduled-regexp)
4443 (defvar org-scheduled-time-regexp nil
4444 "Matches the SCHEDULED keyword together with a time stamp.")
4445 (make-variable-buffer-local 'org-scheduled-time-regexp)
4446 (defvar org-closed-time-regexp nil
4447 "Matches the CLOSED keyword together with a time stamp.")
4448 (make-variable-buffer-local 'org-closed-time-regexp)
4450 (defvar org-keyword-time-regexp nil
4451 "Matches any of the 4 keywords, together with the time stamp.")
4452 (make-variable-buffer-local 'org-keyword-time-regexp)
4453 (defvar org-keyword-time-not-clock-regexp nil
4454 "Matches any of the 3 keywords, together with the time stamp.")
4455 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4456 (defvar org-maybe-keyword-time-regexp nil
4457 "Matches a timestamp, possibly preceded by a keyword.")
4458 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4459 (defvar org-all-time-keywords nil
4460 "List of time keywords.")
4461 (make-variable-buffer-local 'org-all-time-keywords)
4463 (defconst org-plain-time-of-day-regexp
4464 (concat
4465 "\\(\\<[012]?[0-9]"
4466 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4467 "\\(--?"
4468 "\\(\\<[012]?[0-9]"
4469 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4470 "\\)?")
4471 "Regular expression to match a plain time or time range.
4472 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4473 groups carry important information:
4474 0 the full match
4475 1 the first time, range or not
4476 8 the second time, if it is a range.")
4478 (defconst org-plain-time-extension-regexp
4479 (concat
4480 "\\(\\<[012]?[0-9]"
4481 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4482 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4483 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4484 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4485 groups carry important information:
4486 0 the full match
4487 7 hours of duration
4488 9 minutes of duration")
4490 (defconst org-stamp-time-of-day-regexp
4491 (concat
4492 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4493 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4494 "\\(--?"
4495 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4496 "Regular expression to match a timestamp time or time range.
4497 After a match, the following groups carry important information:
4498 0 the full match
4499 1 date plus weekday, for back referencing to make sure both times are on the same day
4500 2 the first time, range or not
4501 4 the second time, if it is a range.")
4503 (defconst org-startup-options
4504 '(("fold" org-startup-folded t)
4505 ("overview" org-startup-folded t)
4506 ("nofold" org-startup-folded nil)
4507 ("showall" org-startup-folded nil)
4508 ("showeverything" org-startup-folded showeverything)
4509 ("content" org-startup-folded content)
4510 ("indent" org-startup-indented t)
4511 ("noindent" org-startup-indented nil)
4512 ("hidestars" org-hide-leading-stars t)
4513 ("showstars" org-hide-leading-stars nil)
4514 ("odd" org-odd-levels-only t)
4515 ("oddeven" org-odd-levels-only nil)
4516 ("align" org-startup-align-all-tables t)
4517 ("noalign" org-startup-align-all-tables nil)
4518 ("inlineimages" org-startup-with-inline-images t)
4519 ("noinlineimages" org-startup-with-inline-images nil)
4520 ("customtime" org-display-custom-times t)
4521 ("logdone" org-log-done time)
4522 ("lognotedone" org-log-done note)
4523 ("nologdone" org-log-done nil)
4524 ("lognoteclock-out" org-log-note-clock-out t)
4525 ("nolognoteclock-out" org-log-note-clock-out nil)
4526 ("logrepeat" org-log-repeat state)
4527 ("lognoterepeat" org-log-repeat note)
4528 ("nologrepeat" org-log-repeat nil)
4529 ("logreschedule" org-log-reschedule time)
4530 ("lognotereschedule" org-log-reschedule note)
4531 ("nologreschedule" org-log-reschedule nil)
4532 ("logredeadline" org-log-redeadline time)
4533 ("lognoteredeadline" org-log-redeadline note)
4534 ("nologredeadline" org-log-redeadline nil)
4535 ("logrefile" org-log-refile time)
4536 ("lognoterefile" org-log-refile note)
4537 ("nologrefile" org-log-refile nil)
4538 ("fninline" org-footnote-define-inline t)
4539 ("nofninline" org-footnote-define-inline nil)
4540 ("fnlocal" org-footnote-section nil)
4541 ("fnauto" org-footnote-auto-label t)
4542 ("fnprompt" org-footnote-auto-label nil)
4543 ("fnconfirm" org-footnote-auto-label confirm)
4544 ("fnplain" org-footnote-auto-label plain)
4545 ("fnadjust" org-footnote-auto-adjust t)
4546 ("nofnadjust" org-footnote-auto-adjust nil)
4547 ("constcgs" constants-unit-system cgs)
4548 ("constSI" constants-unit-system SI)
4549 ("noptag" org-tag-persistent-alist nil)
4550 ("hideblocks" org-hide-block-startup t)
4551 ("nohideblocks" org-hide-block-startup nil)
4552 ("beamer" org-startup-with-beamer-mode t)
4553 ("entitiespretty" org-pretty-entities t)
4554 ("entitiesplain" org-pretty-entities nil))
4555 "Variable associated with STARTUP options for org-mode.
4556 Each element is a list of three items: the startup options (as written
4557 in the #+STARTUP line), the corresponding variable, and the value to set
4558 this variable to if the option is found. An optional forth element PUSH
4559 means to push this value onto the list in the variable.")
4561 (defun org-update-property-plist (key val props)
4562 "Update PROPS with KEY and VAL."
4563 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4564 (key (if appending (substring key 0 (- (length key) 1)) key))
4565 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4566 (previous (cdr (assoc key props))))
4567 (if appending
4568 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4569 (cons (cons key val) remainder))))
4571 (defconst org-block-regexp
4572 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4573 "Regular expression for hiding blocks.")
4574 (defconst org-heading-keyword-regexp-format
4575 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4576 "Printf format for a regexp matching an headline with some keyword.
4577 This regexp will match the headline of any node which has the
4578 exact keyword that is put into the format. The keyword isn't in
4579 any group by default, but the stars and the body are.")
4580 (defconst org-heading-keyword-maybe-regexp-format
4581 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4582 "Printf format for a regexp matching an headline, possibly with some keyword.
4583 This regexp can match any headline with the specified keyword, or
4584 without a keyword. The keyword isn't in any group by default,
4585 but the stars and the body are.")
4587 (defun org-set-regexps-and-options ()
4588 "Precompute regular expressions for current buffer."
4589 (when (derived-mode-p 'org-mode)
4590 (org-set-local 'org-todo-kwd-alist nil)
4591 (org-set-local 'org-todo-key-alist nil)
4592 (org-set-local 'org-todo-key-trigger nil)
4593 (org-set-local 'org-todo-keywords-1 nil)
4594 (org-set-local 'org-done-keywords nil)
4595 (org-set-local 'org-todo-heads nil)
4596 (org-set-local 'org-todo-sets nil)
4597 (org-set-local 'org-todo-log-states nil)
4598 (org-set-local 'org-file-properties nil)
4599 (org-set-local 'org-file-tags nil)
4600 (let ((re (org-make-options-regexp
4601 '("CATEGORY" "TODO" "COLUMNS"
4602 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4603 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4604 "OPTIONS")
4605 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4606 (splitre "[ \t]+")
4607 (scripts org-use-sub-superscripts)
4608 kwds kws0 kwsa key log value cat arch tags const links hw dws
4609 tail sep kws1 prio props ftags drawers beamer-p
4610 ext-setup-or-nil setup-contents (start 0))
4611 (save-excursion
4612 (save-restriction
4613 (widen)
4614 (goto-char (point-min))
4615 (while (or (and ext-setup-or-nil
4616 (string-match re ext-setup-or-nil start)
4617 (setq start (match-end 0)))
4618 (and (setq ext-setup-or-nil nil start 0)
4619 (re-search-forward re nil t)))
4620 (setq key (upcase (match-string 1 ext-setup-or-nil))
4621 value (org-match-string-no-properties 2 ext-setup-or-nil))
4622 (if (stringp value) (setq value (org-trim value)))
4623 (cond
4624 ((equal key "CATEGORY")
4625 (setq cat value))
4626 ((member key '("SEQ_TODO" "TODO"))
4627 (push (cons 'sequence (org-split-string value splitre)) kwds))
4628 ((equal key "TYP_TODO")
4629 (push (cons 'type (org-split-string value splitre)) kwds))
4630 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4631 ;; general TODO-like setup
4632 (push (cons (intern (downcase (match-string 1 key)))
4633 (org-split-string value splitre)) kwds))
4634 ((equal key "TAGS")
4635 (setq tags (append tags (if tags '("\\n") nil)
4636 (org-split-string value splitre))))
4637 ((equal key "COLUMNS")
4638 (org-set-local 'org-columns-default-format value))
4639 ((equal key "LINK")
4640 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4641 (push (cons (match-string 1 value)
4642 (org-trim (match-string 2 value)))
4643 links)))
4644 ((equal key "PRIORITIES")
4645 (setq prio (org-split-string value " +")))
4646 ((equal key "PROPERTY")
4647 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4648 (setq props (org-update-property-plist (match-string 1 value)
4649 (match-string 2 value)
4650 props))))
4651 ((equal key "FILETAGS")
4652 (when (string-match "\\S-" value)
4653 (setq ftags
4654 (append
4655 ftags
4656 (apply 'append
4657 (mapcar (lambda (x) (org-split-string x ":"))
4658 (org-split-string value)))))))
4659 ((equal key "DRAWERS")
4660 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4661 ((equal key "CONSTANTS")
4662 (setq const (append const (org-split-string value splitre))))
4663 ((equal key "STARTUP")
4664 (let ((opts (org-split-string value splitre))
4665 l var val)
4666 (while (setq l (pop opts))
4667 (when (setq l (assoc l org-startup-options))
4668 (setq var (nth 1 l) val (nth 2 l))
4669 (if (not (nth 3 l))
4670 (set (make-local-variable var) val)
4671 (if (not (listp (symbol-value var)))
4672 (set (make-local-variable var) nil))
4673 (set (make-local-variable var) (symbol-value var))
4674 (add-to-list var val))))))
4675 ((equal key "ARCHIVE")
4676 (setq arch value)
4677 (remove-text-properties 0 (length arch)
4678 '(face t fontified t) arch))
4679 ((equal key "LATEX_CLASS")
4680 (setq beamer-p (equal value "beamer")))
4681 ((equal key "OPTIONS")
4682 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4683 (setq scripts (read (match-string 2 value)))))
4684 ((equal key "SETUPFILE")
4685 (setq setup-contents (org-file-contents
4686 (expand-file-name
4687 (org-remove-double-quotes value))
4688 'noerror))
4689 (if (not ext-setup-or-nil)
4690 (setq ext-setup-or-nil setup-contents start 0)
4691 (setq ext-setup-or-nil
4692 (concat (substring ext-setup-or-nil 0 start)
4693 "\n" setup-contents "\n"
4694 (substring ext-setup-or-nil start)))))))
4695 ;; search for property blocks
4696 (goto-char (point-min))
4697 (while (re-search-forward org-block-regexp nil t)
4698 (when (equal "PROPERTY" (upcase (match-string 1)))
4699 (setq value (replace-regexp-in-string
4700 "[\n\r]" " " (match-string 4)))
4701 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4702 (setq props (org-update-property-plist (match-string 1 value)
4703 (match-string 2 value)
4704 props)))))))
4705 (org-set-local 'org-use-sub-superscripts scripts)
4706 (when cat
4707 (org-set-local 'org-category (intern cat))
4708 (push (cons "CATEGORY" cat) props))
4709 (when prio
4710 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4711 (setq prio (mapcar 'string-to-char prio))
4712 (org-set-local 'org-highest-priority (nth 0 prio))
4713 (org-set-local 'org-lowest-priority (nth 1 prio))
4714 (org-set-local 'org-default-priority (nth 2 prio)))
4715 (and props (org-set-local 'org-file-properties (nreverse props)))
4716 (and ftags (org-set-local 'org-file-tags
4717 (mapcar 'org-add-prop-inherited ftags)))
4718 (and drawers (org-set-local 'org-drawers drawers))
4719 (and arch (org-set-local 'org-archive-location arch))
4720 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4721 ;; Process the TODO keywords
4722 (unless kwds
4723 ;; Use the global values as if they had been given locally.
4724 (setq kwds (default-value 'org-todo-keywords))
4725 (if (stringp (car kwds))
4726 (setq kwds (list (cons org-todo-interpretation
4727 (default-value 'org-todo-keywords)))))
4728 (setq kwds (reverse kwds)))
4729 (setq kwds (nreverse kwds))
4730 (let (inter kws kw)
4731 (while (setq kws (pop kwds))
4732 (let ((kws (or
4733 (run-hook-with-args-until-success
4734 'org-todo-setup-filter-hook kws)
4735 kws)))
4736 (setq inter (pop kws) sep (member "|" kws)
4737 kws0 (delete "|" (copy-sequence kws))
4738 kwsa nil
4739 kws1 (mapcar
4740 (lambda (x)
4741 ;; 1 2
4742 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4743 (progn
4744 (setq kw (match-string 1 x)
4745 key (and (match-end 2) (match-string 2 x))
4746 log (org-extract-log-state-settings x))
4747 (push (cons kw (and key (string-to-char key))) kwsa)
4748 (and log (push log org-todo-log-states))
4750 (error "Invalid TODO keyword %s" x)))
4751 kws0)
4752 kwsa (if kwsa (append '((:startgroup))
4753 (nreverse kwsa)
4754 '((:endgroup))))
4755 hw (car kws1)
4756 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4757 tail (list inter hw (car dws) (org-last dws))))
4758 (add-to-list 'org-todo-heads hw 'append)
4759 (push kws1 org-todo-sets)
4760 (setq org-done-keywords (append org-done-keywords dws nil))
4761 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4762 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4763 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4764 (setq org-todo-sets (nreverse org-todo-sets)
4765 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4766 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4767 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4768 ;; Process the constants
4769 (when const
4770 (let (e cst)
4771 (while (setq e (pop const))
4772 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4773 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4774 (setq org-table-formula-constants-local cst)))
4776 ;; Process the tags.
4777 (when tags
4778 (let (e tgs)
4779 (while (setq e (pop tags))
4780 (cond
4781 ((equal e "{") (push '(:startgroup) tgs))
4782 ((equal e "}") (push '(:endgroup) tgs))
4783 ((equal e "\\n") (push '(:newline) tgs))
4784 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4785 (push (cons (match-string 1 e)
4786 (string-to-char (match-string 2 e)))
4787 tgs))
4788 (t (push (list e) tgs))))
4789 (org-set-local 'org-tag-alist nil)
4790 (while (setq e (pop tgs))
4791 (or (and (stringp (car e))
4792 (assoc (car e) org-tag-alist))
4793 (push e org-tag-alist)))))
4795 ;; Compute the regular expressions and other local variables.
4796 ;; Using `org-outline-regexp-bol' would complicate them much,
4797 ;; because of the fixed white space at the end of that string.
4798 (if (not org-done-keywords)
4799 (setq org-done-keywords (and org-todo-keywords-1
4800 (list (org-last org-todo-keywords-1)))))
4801 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4802 (length org-scheduled-string)
4803 (length org-clock-string)
4804 (length org-closed-string)))
4805 org-drawer-regexp
4806 (concat "^[ \t]*:\\("
4807 (mapconcat 'regexp-quote org-drawers "\\|")
4808 "\\):[ \t]*$")
4809 org-not-done-keywords
4810 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4811 org-todo-regexp
4812 (concat "\\("
4813 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4814 "\\)")
4815 org-not-done-regexp
4816 (concat "\\("
4817 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4818 "\\)")
4819 org-not-done-heading-regexp
4820 (format org-heading-keyword-regexp-format org-not-done-regexp)
4821 org-todo-line-regexp
4822 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4823 org-complex-heading-regexp
4824 (concat "^\\(\\*+\\)"
4825 "\\(?: +" org-todo-regexp "\\)?"
4826 "\\(?: +\\(\\[#.\\]\\)\\)?"
4827 "\\(?: +\\(.*?\\)\\)?"
4828 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4829 "[ \t]*$")
4830 org-complex-heading-regexp-format
4831 (concat "^\\(\\*+\\)"
4832 "\\(?: +" org-todo-regexp "\\)?"
4833 "\\(?: +\\(\\[#.\\]\\)\\)?"
4834 "\\(?: +"
4835 ;; Stats cookies can be stuck to body.
4836 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4837 "\\(%s\\)"
4838 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4839 "\\)"
4840 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4841 "[ \t]*$")
4842 org-todo-line-tags-regexp
4843 (concat "^\\(\\*+\\)"
4844 "\\(?: +" org-todo-regexp "\\)?"
4845 "\\(?: +\\(.*?\\)\\)?"
4846 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4847 "[ \t]*$")
4848 org-deadline-regexp (concat "\\<" org-deadline-string)
4849 org-deadline-time-regexp
4850 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4851 org-deadline-line-regexp
4852 (concat "\\<\\(" org-deadline-string "\\).*")
4853 org-scheduled-regexp
4854 (concat "\\<" org-scheduled-string)
4855 org-scheduled-time-regexp
4856 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4857 org-closed-time-regexp
4858 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4859 org-keyword-time-regexp
4860 (concat "\\<\\(" org-scheduled-string
4861 "\\|" org-deadline-string
4862 "\\|" org-closed-string
4863 "\\|" org-clock-string "\\)"
4864 " *[[<]\\([^]>]+\\)[]>]")
4865 org-keyword-time-not-clock-regexp
4866 (concat "\\<\\(" org-scheduled-string
4867 "\\|" org-deadline-string
4868 "\\|" org-closed-string
4869 "\\)"
4870 " *[[<]\\([^]>]+\\)[]>]")
4871 org-maybe-keyword-time-regexp
4872 (concat "\\(\\<\\(" org-scheduled-string
4873 "\\|" org-deadline-string
4874 "\\|" org-closed-string
4875 "\\|" org-clock-string "\\)\\)?"
4876 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4877 org-all-time-keywords
4878 (mapcar (lambda (w) (substring w 0 -1))
4879 (list org-scheduled-string org-deadline-string
4880 org-clock-string org-closed-string))
4882 (org-compute-latex-and-specials-regexp)
4883 (org-set-font-lock-defaults))))
4885 (defun org-file-contents (file &optional noerror)
4886 "Return the contents of FILE, as a string."
4887 (if (or (not file)
4888 (not (file-readable-p file)))
4889 (if noerror
4890 (progn
4891 (message "Cannot read file \"%s\"" file)
4892 (ding) (sit-for 2)
4894 (error "Cannot read file \"%s\"" file))
4895 (with-temp-buffer
4896 (insert-file-contents file)
4897 (buffer-string))))
4899 (defun org-extract-log-state-settings (x)
4900 "Extract the log state setting from a TODO keyword string.
4901 This will extract info from a string like \"WAIT(w@/!)\"."
4902 (let (kw key log1 log2)
4903 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4904 (setq kw (match-string 1 x)
4905 key (and (match-end 2) (match-string 2 x))
4906 log1 (and (match-end 3) (match-string 3 x))
4907 log2 (and (match-end 4) (match-string 4 x)))
4908 (and (or log1 log2)
4909 (list kw
4910 (and log1 (if (equal log1 "!") 'time 'note))
4911 (and log2 (if (equal log2 "!") 'time 'note)))))))
4913 (defun org-remove-keyword-keys (list)
4914 "Remove a pair of parenthesis at the end of each string in LIST."
4915 (mapcar (lambda (x)
4916 (if (string-match "(.*)$" x)
4917 (substring x 0 (match-beginning 0))
4919 list))
4921 (defun org-assign-fast-keys (alist)
4922 "Assign fast keys to a keyword-key alist.
4923 Respect keys that are already there."
4924 (let (new e (alt ?0))
4925 (while (setq e (pop alist))
4926 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4927 (cdr e)) ;; Key already assigned.
4928 (push e new)
4929 (let ((clist (string-to-list (downcase (car e))))
4930 (used (append new alist)))
4931 (when (= (car clist) ?@)
4932 (pop clist))
4933 (while (and clist (rassoc (car clist) used))
4934 (pop clist))
4935 (unless clist
4936 (while (rassoc alt used)
4937 (incf alt)))
4938 (push (cons (car e) (or (car clist) alt)) new))))
4939 (nreverse new)))
4941 ;;; Some variables used in various places
4943 (defvar org-window-configuration nil
4944 "Used in various places to store a window configuration.")
4945 (defvar org-selected-window nil
4946 "Used in various places to store a window configuration.")
4947 (defvar org-finish-function nil
4948 "Function to be called when `C-c C-c' is used.
4949 This is for getting out of special buffers like remember.")
4952 ;; FIXME: Occasionally check by commenting these, to make sure
4953 ;; no other functions uses these, forgetting to let-bind them.
4954 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4955 (defvar org-last-state)
4956 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4958 ;; Defined somewhere in this file, but used before definition.
4959 (defvar org-entities) ;; defined in org-entities.el
4960 (defvar org-struct-menu)
4961 (defvar org-org-menu)
4962 (defvar org-tbl-menu)
4964 ;;;; Define the Org-mode
4966 ;; We use a before-change function to check if a table might need
4967 ;; an update.
4968 (defvar org-table-may-need-update t
4969 "Indicates that a table might need an update.
4970 This variable is set by `org-before-change-function'.
4971 `org-table-align' sets it back to nil.")
4972 (defun org-before-change-function (beg end)
4973 "Every change indicates that a table might need an update."
4974 (setq org-table-may-need-update t))
4975 (defvar org-mode-map)
4976 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4977 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4978 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4979 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4980 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4981 (defvar org-table-buffer-is-an nil)
4983 (defvar bidi-paragraph-direction)
4984 (defvar buffer-face-mode-face)
4986 (require 'outline)
4987 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4988 (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"))
4989 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4991 ;; Other stuff we need.
4992 (require 'time-date)
4993 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4994 (require 'easymenu)
4995 (require 'overlay)
4997 (require 'org-macs)
4998 (require 'org-entities)
4999 ;; (require 'org-compat) moved higher up in the file before it is first used
5000 (require 'org-faces)
5001 (require 'org-list)
5002 (require 'org-pcomplete)
5003 (require 'org-src)
5004 (require 'org-footnote)
5006 ;; babel
5007 (require 'ob)
5008 (require 'ob-table)
5009 (require 'ob-lob)
5010 (require 'ob-ref)
5011 (require 'ob-tangle)
5012 (require 'ob-comint)
5013 (require 'ob-keys)
5015 ;;;###autoload
5016 (define-derived-mode org-mode outline-mode "Org"
5017 "Outline-based notes management and organizer, alias
5018 \"Carsten's outline-mode for keeping track of everything.\"
5020 Org-mode develops organizational tasks around a NOTES file which
5021 contains information about projects as plain text. Org-mode is
5022 implemented on top of outline-mode, which is ideal to keep the content
5023 of large files well structured. It supports ToDo items, deadlines and
5024 time stamps, which magically appear in the diary listing of the Emacs
5025 calendar. Tables are easily created with a built-in table editor.
5026 Plain text URL-like links connect to websites, emails (VM), Usenet
5027 messages (Gnus), BBDB entries, and any files related to the project.
5028 For printing and sharing of notes, an Org-mode file (or a part of it)
5029 can be exported as a structured ASCII or HTML file.
5031 The following commands are available:
5033 \\{org-mode-map}"
5035 ;; Get rid of Outline menus, they are not needed
5036 ;; Need to do this here because define-derived-mode sets up
5037 ;; the keymap so late. Still, it is a waste to call this each time
5038 ;; we switch another buffer into org-mode.
5039 (if (featurep 'xemacs)
5040 (when (boundp 'outline-mode-menu-heading)
5041 ;; Assume this is Greg's port, it uses easymenu
5042 (easy-menu-remove outline-mode-menu-heading)
5043 (easy-menu-remove outline-mode-menu-show)
5044 (easy-menu-remove outline-mode-menu-hide))
5045 (define-key org-mode-map [menu-bar headings] 'undefined)
5046 (define-key org-mode-map [menu-bar hide] 'undefined)
5047 (define-key org-mode-map [menu-bar show] 'undefined))
5049 (org-load-modules-maybe)
5050 (easy-menu-add org-org-menu)
5051 (easy-menu-add org-tbl-menu)
5052 (org-install-agenda-files-menu)
5053 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5054 (add-to-invisibility-spec '(org-cwidth))
5055 (add-to-invisibility-spec '(org-hide-block . t))
5056 (when (featurep 'xemacs)
5057 (org-set-local 'line-move-ignore-invisible t))
5058 (org-set-local 'outline-regexp org-outline-regexp)
5059 (org-set-local 'outline-level 'org-outline-level)
5060 (setq bidi-paragraph-direction 'left-to-right)
5061 (when (and org-ellipsis
5062 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5063 (fboundp 'make-glyph-code))
5064 (unless org-display-table
5065 (setq org-display-table (make-display-table)))
5066 (set-display-table-slot
5067 org-display-table 4
5068 (vconcat (mapcar
5069 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5070 org-ellipsis)))
5071 (if (stringp org-ellipsis) org-ellipsis "..."))))
5072 (setq buffer-display-table org-display-table))
5073 (org-set-regexps-and-options)
5074 (when (and org-tag-faces (not org-tags-special-faces-re))
5075 ;; tag faces set outside customize.... force initialization.
5076 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5077 ;; Calc embedded
5078 (org-set-local 'calc-embedded-open-mode "# ")
5079 (modify-syntax-entry ?@ "w")
5080 (modify-syntax-entry ?\" "\"")
5081 (if org-startup-truncated (setq truncate-lines t))
5082 (org-set-local 'font-lock-unfontify-region-function
5083 'org-unfontify-region)
5084 ;; Activate before-change-function
5085 (org-set-local 'org-table-may-need-update t)
5086 (org-add-hook 'before-change-functions 'org-before-change-function nil
5087 'local)
5088 ;; Check for running clock before killing a buffer
5089 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5090 ;; Initialize macros templates.
5091 (org-macro-initialize-templates)
5092 ;; Initialize radio targets.
5093 (org-update-radio-target-regexp)
5094 ;; Indentation.
5095 (org-set-local 'indent-line-function 'org-indent-line)
5096 (org-set-local 'indent-region-function 'org-indent-region)
5097 ;; Filling and auto-filling.
5098 (org-setup-filling)
5099 ;; Comments.
5100 (org-setup-comments-handling)
5101 ;; Beginning/end of defun
5102 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5103 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5104 ;; Next error for sparse trees
5105 (org-set-local 'next-error-function 'org-occur-next-match)
5106 ;; Make sure dependence stuff works reliably, even for users who set it
5107 ;; too late :-(
5108 (if org-enforce-todo-dependencies
5109 (add-hook 'org-blocker-hook
5110 'org-block-todo-from-children-or-siblings-or-parent)
5111 (remove-hook 'org-blocker-hook
5112 'org-block-todo-from-children-or-siblings-or-parent))
5113 (if org-enforce-todo-checkbox-dependencies
5114 (add-hook 'org-blocker-hook
5115 'org-block-todo-from-checkboxes)
5116 (remove-hook 'org-blocker-hook
5117 'org-block-todo-from-checkboxes))
5119 ;; Align options lines
5120 (org-set-local
5121 'align-mode-rules-list
5122 '((org-in-buffer-settings
5123 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5124 (modes . '(org-mode)))))
5126 ;; Imenu
5127 (org-set-local 'imenu-create-index-function
5128 'org-imenu-get-tree)
5130 ;; Make isearch reveal context
5131 (if (or (featurep 'xemacs)
5132 (not (boundp 'outline-isearch-open-invisible-function)))
5133 ;; Emacs 21 and XEmacs make use of the hook
5134 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5135 ;; Emacs 22 deals with this through a special variable
5136 (org-set-local 'outline-isearch-open-invisible-function
5137 (lambda (&rest ignore) (org-show-context 'isearch))))
5139 ;; Turn on org-beamer-mode?
5140 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5142 ;; Setup the pcomplete hooks
5143 (set (make-local-variable 'pcomplete-command-completion-function)
5144 'org-pcomplete-initial)
5145 (set (make-local-variable 'pcomplete-command-name-function)
5146 'org-command-at-point)
5147 (set (make-local-variable 'pcomplete-default-completion-function)
5148 'ignore)
5149 (set (make-local-variable 'pcomplete-parse-arguments-function)
5150 'org-parse-arguments)
5151 (set (make-local-variable 'pcomplete-termination-string) "")
5152 (when (>= emacs-major-version 23)
5153 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5155 ;; If empty file that did not turn on org-mode automatically, make it to.
5156 (if (and org-insert-mode-line-in-empty-file
5157 (org-called-interactively-p 'any)
5158 (= (point-min) (point-max)))
5159 (insert "# -*- mode: org -*-\n\n"))
5160 (unless org-inhibit-startup
5161 (when org-startup-align-all-tables
5162 (let ((bmp (buffer-modified-p)))
5163 (org-table-map-tables 'org-table-align 'quietly)
5164 (set-buffer-modified-p bmp)))
5165 (when org-startup-with-inline-images
5166 (org-display-inline-images))
5167 (when org-startup-indented
5168 (require 'org-indent)
5169 (org-indent-mode 1))
5170 (unless org-inhibit-startup-visibility-stuff
5171 (org-set-startup-visibility))))
5173 (when (fboundp 'abbrev-table-put)
5174 (abbrev-table-put org-mode-abbrev-table
5175 :parents (list text-mode-abbrev-table)))
5177 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5179 (defun org-current-time ()
5180 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5181 (if (> (car org-time-stamp-rounding-minutes) 1)
5182 (let ((r (car org-time-stamp-rounding-minutes))
5183 (time (decode-time)))
5184 (apply 'encode-time
5185 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5186 (nthcdr 2 time))))
5187 (current-time)))
5189 (defun org-today ()
5190 "Return today date, considering `org-extend-today-until'."
5191 (time-to-days
5192 (time-subtract (current-time)
5193 (list 0 (* 3600 org-extend-today-until) 0))))
5195 ;;;; Font-Lock stuff, including the activators
5197 (defvar org-mouse-map (make-sparse-keymap))
5198 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5199 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5200 (when org-mouse-1-follows-link
5201 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5202 (when org-tab-follows-link
5203 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5204 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5206 (require 'font-lock)
5208 (defconst org-non-link-chars "]\t\n\r<>")
5209 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5210 "shell" "elisp" "doi" "message"))
5211 (defvar org-link-types-re nil
5212 "Matches a link that has a url-like prefix like \"http:\"")
5213 (defvar org-link-re-with-space nil
5214 "Matches a link with spaces, optional angular brackets around it.")
5215 (defvar org-link-re-with-space2 nil
5216 "Matches a link with spaces, optional angular brackets around it.")
5217 (defvar org-link-re-with-space3 nil
5218 "Matches a link with spaces, only for internal part in bracket links.")
5219 (defvar org-angle-link-re nil
5220 "Matches link with angular brackets, spaces are allowed.")
5221 (defvar org-plain-link-re nil
5222 "Matches plain link, without spaces.")
5223 (defvar org-bracket-link-regexp nil
5224 "Matches a link in double brackets.")
5225 (defvar org-bracket-link-analytic-regexp nil
5226 "Regular expression used to analyze links.
5227 Here is what the match groups contain after a match:
5228 1: http:
5229 2: http
5230 3: path
5231 4: [desc]
5232 5: desc")
5233 (defvar org-bracket-link-analytic-regexp++ nil
5234 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5235 (defvar org-any-link-re nil
5236 "Regular expression matching any link.")
5238 (defcustom org-match-sexp-depth 3
5239 "Number of stacked braces for sub/superscript matching.
5240 This has to be set before loading org.el to be effective."
5241 :group 'org-export-translation ; ??????????????????????????/
5242 :type 'integer)
5244 (defun org-create-multibrace-regexp (left right n)
5245 "Create a regular expression which will match a balanced sexp.
5246 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5247 as single character strings.
5248 The regexp returned will match the entire expression including the
5249 delimiters. It will also define a single group which contains the
5250 match except for the outermost delimiters. The maximum depth of
5251 stacked delimiters is N. Escaping delimiters is not possible."
5252 (let* ((nothing (concat "[^" left right "]*?"))
5253 (or "\\|")
5254 (re nothing)
5255 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5256 (while (> n 1)
5257 (setq n (1- n)
5258 re (concat re or next)
5259 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5260 (concat left "\\(" re "\\)" right)))
5262 (defvar org-match-substring-regexp
5263 (concat
5264 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5265 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5266 "\\|"
5267 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5268 "\\|"
5269 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5270 "The regular expression matching a sub- or superscript.")
5272 (defvar org-match-substring-with-braces-regexp
5273 (concat
5274 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5275 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5276 "\\)")
5277 "The regular expression matching a sub- or superscript, forcing braces.")
5279 (defun org-make-link-regexps ()
5280 "Update the link regular expressions.
5281 This should be called after the variable `org-link-types' has changed."
5282 (setq org-link-types-re
5283 (concat
5284 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5285 org-link-re-with-space
5286 (concat
5287 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5288 "\\([^" org-non-link-chars " ]"
5289 "[^" org-non-link-chars "]*"
5290 "[^" org-non-link-chars " ]\\)>?")
5291 org-link-re-with-space2
5292 (concat
5293 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5294 "\\([^" org-non-link-chars " ]"
5295 "[^\t\n\r]*"
5296 "[^" org-non-link-chars " ]\\)>?")
5297 org-link-re-with-space3
5298 (concat
5299 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5300 "\\([^" org-non-link-chars " ]"
5301 "[^\t\n\r]*\\)")
5302 org-angle-link-re
5303 (concat
5304 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5305 "\\([^" org-non-link-chars " ]"
5306 "[^" org-non-link-chars "]*"
5307 "\\)>")
5308 org-plain-link-re
5309 (concat
5310 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5311 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5312 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5313 org-bracket-link-regexp
5314 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5315 org-bracket-link-analytic-regexp
5316 (concat
5317 "\\[\\["
5318 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5319 "\\([^]]+\\)"
5320 "\\]"
5321 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5322 "\\]")
5323 org-bracket-link-analytic-regexp++
5324 (concat
5325 "\\[\\["
5326 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5327 "\\([^]]+\\)"
5328 "\\]"
5329 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5330 "\\]")
5331 org-any-link-re
5332 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5333 org-angle-link-re "\\)\\|\\("
5334 org-plain-link-re "\\)")))
5336 (org-make-link-regexps)
5338 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5339 "Regular expression for fast time stamp matching.")
5340 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5341 "Regular expression for fast time stamp matching.")
5342 (defconst org-ts-regexp0
5343 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5344 "Regular expression matching time strings for analysis.
5345 This one does not require the space after the date, so it can be used
5346 on a string that terminates immediately after the date.")
5347 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5348 "Regular expression matching time strings for analysis.")
5349 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5350 "Regular expression matching time stamps, with groups.")
5351 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5352 "Regular expression matching time stamps (also [..]), with groups.")
5353 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5354 "Regular expression matching a time stamp range.")
5355 (defconst org-tr-regexp-both
5356 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5357 "Regular expression matching a time stamp range.")
5358 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5359 org-ts-regexp "\\)?")
5360 "Regular expression matching a time stamp or time stamp range.")
5361 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5362 org-ts-regexp-both "\\)?")
5363 "Regular expression matching a time stamp or time stamp range.
5364 The time stamps may be either active or inactive.")
5366 (defvar org-emph-face nil)
5368 (defun org-do-emphasis-faces (limit)
5369 "Run through the buffer and add overlays to emphasized strings."
5370 (let (rtn a)
5371 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5372 (if (not (= (char-after (match-beginning 3))
5373 (char-after (match-beginning 4))))
5374 (progn
5375 (setq rtn t)
5376 (setq a (assoc (match-string 3) org-emphasis-alist))
5377 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5378 'face
5379 (nth 1 a))
5380 (and (nth 4 a)
5381 (org-remove-flyspell-overlays-in
5382 (match-beginning 0) (match-end 0)))
5383 (add-text-properties (match-beginning 2) (match-end 2)
5384 '(font-lock-multiline t org-emphasis t))
5385 (when org-hide-emphasis-markers
5386 (add-text-properties (match-end 4) (match-beginning 5)
5387 '(invisible org-link))
5388 (add-text-properties (match-beginning 3) (match-end 3)
5389 '(invisible org-link)))))
5390 (backward-char 1))
5391 rtn))
5393 (defun org-emphasize (&optional char)
5394 "Insert or change an emphasis, i.e. a font like bold or italic.
5395 If there is an active region, change that region to a new emphasis.
5396 If there is no region, just insert the marker characters and position
5397 the cursor between them.
5398 CHAR should be either the marker character, or the first character of the
5399 HTML tag associated with that emphasis. If CHAR is a space, the means
5400 to remove the emphasis of the selected region.
5401 If char is not given (for example in an interactive call) it
5402 will be prompted for."
5403 (interactive)
5404 (let ((eal org-emphasis-alist) e det
5405 (erc org-emphasis-regexp-components)
5406 (prompt "")
5407 (string "") beg end move tag c s)
5408 (if (org-region-active-p)
5409 (setq beg (region-beginning) end (region-end)
5410 string (buffer-substring beg end))
5411 (setq move t))
5413 (while (setq e (pop eal))
5414 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5415 c (aref tag 0))
5416 (push (cons c (string-to-char (car e))) det)
5417 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5418 (substring tag 1)))))
5419 (setq det (nreverse det))
5420 (unless char
5421 (message "%s" (concat "Emphasis marker or tag:" prompt))
5422 (setq char (read-char-exclusive)))
5423 (setq char (or (cdr (assoc char det)) char))
5424 (if (equal char ?\ )
5425 (setq s "" move nil)
5426 (unless (assoc (char-to-string char) org-emphasis-alist)
5427 (error "No such emphasis marker: \"%c\"" char))
5428 (setq s (char-to-string char)))
5429 (while (and (> (length string) 1)
5430 (equal (substring string 0 1) (substring string -1))
5431 (assoc (substring string 0 1) org-emphasis-alist))
5432 (setq string (substring string 1 -1)))
5433 (setq string (concat s string s))
5434 (if beg (delete-region beg end))
5435 (unless (or (bolp)
5436 (string-match (concat "[" (nth 0 erc) "\n]")
5437 (char-to-string (char-before (point)))))
5438 (insert " "))
5439 (unless (or (eobp)
5440 (string-match (concat "[" (nth 1 erc) "\n]")
5441 (char-to-string (char-after (point)))))
5442 (insert " ") (backward-char 1))
5443 (insert string)
5444 (and move (backward-char 1))))
5446 (defconst org-nonsticky-props
5447 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5449 (defsubst org-rear-nonsticky-at (pos)
5450 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5452 (defun org-activate-plain-links (limit)
5453 "Run through the buffer and add overlays to links."
5454 (catch 'exit
5455 (let (f)
5456 (if (and (re-search-forward (concat org-plain-link-re) limit t)
5457 (or (not (member 'bracket org-activate-links))
5458 (save-excursion
5459 (save-match-data
5460 (goto-char (match-beginning 0))
5461 (not (looking-back "\\[\\["))))))
5462 (progn
5463 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5464 (setq f (get-text-property (match-beginning 0) 'face))
5465 (if (or (eq f 'org-tag)
5466 (and (listp f) (memq 'org-tag f)))
5468 (add-text-properties (match-beginning 0) (match-end 0)
5469 (list 'mouse-face 'highlight
5470 'face 'org-link
5471 'keymap org-mouse-map))
5472 (org-rear-nonsticky-at (match-end 0)))
5473 t)))))
5475 (defun org-activate-code (limit)
5476 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5477 (progn
5478 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5479 (remove-text-properties (match-beginning 0) (match-end 0)
5480 '(display t invisible t intangible t))
5481 t)))
5483 (defcustom org-src-fontify-natively nil
5484 "When non-nil, fontify code in code blocks."
5485 :type 'boolean
5486 :version "24.1"
5487 :group 'org-appearance
5488 :group 'org-babel)
5490 (defcustom org-allow-promoting-top-level-subtree nil
5491 "When non-nil, allow promoting a top level subtree.
5492 The leading star of the top level headline will be replaced
5493 by a #."
5494 :type 'boolean
5495 :version "24.1"
5496 :group 'org-appearance)
5498 (defun org-fontify-meta-lines-and-blocks (limit)
5499 (condition-case nil
5500 (org-fontify-meta-lines-and-blocks-1 limit)
5501 (error (message "org-mode fontification error"))))
5503 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5504 "Fontify #+ lines and blocks, in the correct ways."
5505 (let ((case-fold-search t))
5506 (if (re-search-forward
5507 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5508 limit t)
5509 (let ((beg (match-beginning 0))
5510 (block-start (match-end 0))
5511 (block-end nil)
5512 (lang (match-string 7))
5513 (beg1 (line-beginning-position 2))
5514 (dc1 (downcase (match-string 2)))
5515 (dc3 (downcase (match-string 3)))
5516 end end1 quoting block-type ovl)
5517 (cond
5518 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5519 ;; a single line of backend-specific content
5520 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5521 (remove-text-properties (match-beginning 0) (match-end 0)
5522 '(display t invisible t intangible t))
5523 (add-text-properties (match-beginning 1) (match-end 3)
5524 '(font-lock-fontified t face org-meta-line))
5525 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5526 '(font-lock-fontified t face org-block))
5527 ; for backend-specific code
5529 ((and (match-end 4) (equal dc3 "+begin"))
5530 ;; Truly a block
5531 (setq block-type (downcase (match-string 5))
5532 quoting (member block-type org-protecting-blocks))
5533 (when (re-search-forward
5534 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5535 nil t) ;; on purpose, we look further than LIMIT
5536 (setq end (min (point-max) (match-end 0))
5537 end1 (min (point-max) (1- (match-beginning 0))))
5538 (setq block-end (match-beginning 0))
5539 (when quoting
5540 (remove-text-properties beg end
5541 '(display t invisible t intangible t)))
5542 (add-text-properties
5543 beg end
5544 '(font-lock-fontified t font-lock-multiline t))
5545 (add-text-properties beg beg1 '(face org-meta-line))
5546 (add-text-properties end1 (min (point-max) (1+ end))
5547 '(face org-meta-line)) ; for end_src
5548 (cond
5549 ((and lang (not (string= lang "")) org-src-fontify-natively)
5550 (org-src-font-lock-fontify-block lang block-start block-end)
5551 ;; remove old background overlays
5552 (mapc (lambda (ov)
5553 (if (eq (overlay-get ov 'face) 'org-block-background)
5554 (delete-overlay ov)))
5555 (overlays-at (/ (+ beg1 block-end) 2)))
5556 ;; add a background overlay
5557 (setq ovl (make-overlay beg1 block-end))
5558 (overlay-put ovl 'face 'org-block-background)
5559 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5560 (quoting
5561 (add-text-properties beg1 (min (point-max) (1+ end1))
5562 '(face org-block))) ; end of source block
5563 ((not org-fontify-quote-and-verse-blocks))
5564 ((string= block-type "quote")
5565 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5566 ((string= block-type "verse")
5567 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5568 (add-text-properties beg beg1 '(face org-block-begin-line))
5569 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5570 '(face org-block-end-line))
5572 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5573 (add-text-properties
5574 beg (match-end 3)
5575 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5576 '(font-lock-fontified t invisible t)
5577 '(font-lock-fontified t face org-document-info-keyword)))
5578 (add-text-properties
5579 (match-beginning 6) (match-end 6)
5580 (if (string-equal dc1 "+title:")
5581 '(font-lock-fontified t face org-document-title)
5582 '(font-lock-fontified t face org-document-info))))
5583 ((or (equal dc1 "+results")
5584 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5585 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5586 "+call:" "+header:" "+headers:" "+name:"))
5587 (and (match-end 4) (equal dc3 "+attr")))
5588 (add-text-properties
5589 beg (match-end 0)
5590 '(font-lock-fontified t face org-meta-line))
5592 ((member dc3 '(" " ""))
5593 (add-text-properties
5594 beg (match-end 0)
5595 '(font-lock-fontified t face font-lock-comment-face)))
5596 ((not (member (char-after beg) '(?\ ?\t)))
5597 ;; just any other in-buffer setting, but not indented
5598 (add-text-properties
5599 beg (match-end 0)
5600 '(font-lock-fontified t face org-meta-line))
5602 (t nil))))))
5604 (defun org-strip-protective-commas (beg end)
5605 "Strip protective commas between BEG and END in the current buffer."
5606 (interactive "r")
5607 (save-excursion
5608 (save-match-data
5609 (goto-char beg)
5610 (let ((front-line (save-excursion
5611 (re-search-forward
5612 "[^[:space:]]" end t)
5613 (goto-char (match-beginning 0))
5614 (current-column))))
5615 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5616 (goto-char (match-beginning 1))
5617 (when (= (current-column) front-line)
5618 (replace-match "" nil nil nil 1)))))))
5620 (defun org-activate-angle-links (limit)
5621 "Run through the buffer and add overlays to links."
5622 (if (re-search-forward org-angle-link-re limit t)
5623 (progn
5624 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5625 (add-text-properties (match-beginning 0) (match-end 0)
5626 (list 'mouse-face 'highlight
5627 'keymap org-mouse-map))
5628 (org-rear-nonsticky-at (match-end 0))
5629 t)))
5631 (defun org-activate-footnote-links (limit)
5632 "Run through the buffer and add overlays to footnotes."
5633 (let ((fn (org-footnote-next-reference-or-definition limit)))
5634 (when fn
5635 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5636 (org-remove-flyspell-overlays-in beg end)
5637 (add-text-properties beg end
5638 (list 'mouse-face 'highlight
5639 'keymap org-mouse-map
5640 'help-echo
5641 (if (= (point-at-bol) beg)
5642 "Footnote definition"
5643 "Footnote reference")
5644 'font-lock-fontified t
5645 'font-lock-multiline t
5646 'face 'org-footnote))))))
5648 (defun org-activate-bracket-links (limit)
5649 "Run through the buffer and add overlays to bracketed links."
5650 (if (re-search-forward org-bracket-link-regexp limit t)
5651 (let* ((help (concat "LINK: "
5652 (org-match-string-no-properties 1)))
5653 ;; FIXME: above we should remove the escapes.
5654 ;; but that requires another match, protecting match data,
5655 ;; a lot of overhead for font-lock.
5656 (ip (org-maybe-intangible
5657 (list 'invisible 'org-link
5658 'keymap org-mouse-map 'mouse-face 'highlight
5659 'font-lock-multiline t 'help-echo help)))
5660 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5661 'font-lock-multiline t 'help-echo help)))
5662 ;; We need to remove the invisible property here. Table narrowing
5663 ;; may have made some of this invisible.
5664 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5665 (remove-text-properties (match-beginning 0) (match-end 0)
5666 '(invisible nil))
5667 (if (match-end 3)
5668 (progn
5669 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5670 (org-rear-nonsticky-at (match-beginning 3))
5671 (add-text-properties (match-beginning 3) (match-end 3) vp)
5672 (org-rear-nonsticky-at (match-end 3))
5673 (add-text-properties (match-end 3) (match-end 0) ip)
5674 (org-rear-nonsticky-at (match-end 0)))
5675 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5676 (org-rear-nonsticky-at (match-beginning 1))
5677 (add-text-properties (match-beginning 1) (match-end 1) vp)
5678 (org-rear-nonsticky-at (match-end 1))
5679 (add-text-properties (match-end 1) (match-end 0) ip)
5680 (org-rear-nonsticky-at (match-end 0)))
5681 t)))
5683 (defun org-activate-dates (limit)
5684 "Run through the buffer and add overlays to dates."
5685 (if (re-search-forward org-tsr-regexp-both limit t)
5686 (progn
5687 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5688 (add-text-properties (match-beginning 0) (match-end 0)
5689 (list 'mouse-face 'highlight
5690 'keymap org-mouse-map))
5691 (org-rear-nonsticky-at (match-end 0))
5692 (when org-display-custom-times
5693 (if (match-end 3)
5694 (org-display-custom-time (match-beginning 3) (match-end 3)))
5695 (org-display-custom-time (match-beginning 1) (match-end 1)))
5696 t)))
5698 (defvar org-target-link-regexp nil
5699 "Regular expression matching radio targets in plain text.")
5700 (make-variable-buffer-local 'org-target-link-regexp)
5701 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5702 "Regular expression matching a link target.")
5703 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5704 "Regular expression matching a radio target.")
5705 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5706 "Regular expression matching any target.")
5708 (defun org-activate-target-links (limit)
5709 "Run through the buffer and add overlays to target matches."
5710 (when org-target-link-regexp
5711 (let ((case-fold-search t))
5712 (if (re-search-forward org-target-link-regexp limit t)
5713 (progn
5714 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5715 (add-text-properties (match-beginning 0) (match-end 0)
5716 (list 'mouse-face 'highlight
5717 'keymap org-mouse-map
5718 'help-echo "Radio target link"
5719 'org-linked-text t))
5720 (org-rear-nonsticky-at (match-end 0))
5721 t)))))
5723 (defun org-update-radio-target-regexp ()
5724 "Find all radio targets in this file and update the regular expression."
5725 (interactive)
5726 (when (memq 'radio org-activate-links)
5727 (setq org-target-link-regexp
5728 (org-make-target-link-regexp (org-all-targets 'radio)))
5729 (org-restart-font-lock)))
5731 (defun org-hide-wide-columns (limit)
5732 (let (s e)
5733 (setq s (text-property-any (point) (or limit (point-max))
5734 'org-cwidth t))
5735 (when s
5736 (setq e (next-single-property-change s 'org-cwidth))
5737 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5738 (goto-char e)
5739 t)))
5741 (defvar org-latex-and-specials-regexp nil
5742 "Regular expression for highlighting export special stuff.")
5743 (defvar org-match-substring-regexp)
5744 (defvar org-match-substring-with-braces-regexp)
5746 ;; This should be with the exporter code, but we also use if for font-locking
5747 (defconst org-export-html-special-string-regexps
5748 '(("\\\\-" . "&shy;")
5749 ("---\\([^-]\\)" . "&mdash;\\1")
5750 ("--\\([^-]\\)" . "&ndash;\\1")
5751 ("\\.\\.\\." . "&hellip;"))
5752 "Regular expressions for special string conversion.")
5755 (defun org-compute-latex-and-specials-regexp ()
5756 "Compute regular expression for stuff treated specially by exporters."
5757 (if (not org-highlight-latex-fragments-and-specials)
5758 (org-set-local 'org-latex-and-specials-regexp nil)
5759 (require 'org-exp)
5760 (let*
5761 ((matchers (plist-get org-format-latex-options :matchers))
5762 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5763 org-latex-regexps)))
5764 (org-export-allow-BIND nil)
5765 (options (org-combine-plists (org-default-export-plist)
5766 (org-infile-export-plist)))
5767 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5768 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5769 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5770 (org-export-html-expand (plist-get options :expand-quoted-html))
5771 (org-export-with-special-strings (plist-get options :special-strings))
5772 (re-sub
5773 (cond
5774 ((equal org-export-with-sub-superscripts '{})
5775 (list org-match-substring-with-braces-regexp))
5776 (org-export-with-sub-superscripts
5777 (list org-match-substring-regexp))))
5778 (re-latex
5779 (if org-export-with-LaTeX-fragments
5780 (mapcar (lambda (x) (nth 1 x)) latexs)))
5781 (re-macros
5782 (if org-export-with-TeX-macros
5783 (list (concat "\\\\"
5784 (regexp-opt
5785 (append
5787 (delq nil
5788 (mapcar 'car-safe
5789 (append org-entities-user
5790 org-entities)))
5791 (if (boundp 'org-latex-entities)
5792 (mapcar (lambda (x)
5793 (or (car-safe x) x))
5794 org-latex-entities)
5795 nil))
5796 'words))) ; FIXME
5798 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5799 (re-special (if org-export-with-special-strings
5800 (mapcar (lambda (x) (car x))
5801 org-export-html-special-string-regexps)))
5802 (re-rest
5803 (delq nil
5804 (list
5805 (if org-export-html-expand "@<[^>\n]+>")
5806 ))))
5807 (org-set-local
5808 'org-latex-and-specials-regexp
5809 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5810 re-rest) "\\|")))))
5812 (defun org-do-latex-and-special-faces (limit)
5813 "Run through the buffer and add overlays to links."
5814 (when org-latex-and-specials-regexp
5815 (let (rtn d)
5816 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5817 limit t))
5818 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5819 'face))
5820 '(org-code org-verbatim underline)))
5821 (progn
5822 (setq rtn t
5823 d (cond ((member (char-after (1+ (match-beginning 0)))
5824 '(?_ ?^)) 1)
5825 (t 0)))
5826 (font-lock-prepend-text-property
5827 (+ d (match-beginning 0)) (match-end 0)
5828 'face 'org-latex-and-export-specials)
5829 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5830 '(font-lock-multiline t)))))
5831 rtn)))
5833 (defun org-restart-font-lock ()
5834 "Restart `font-lock-mode', to force refontification."
5835 (when (and (boundp 'font-lock-mode) font-lock-mode)
5836 (font-lock-mode -1)
5837 (font-lock-mode 1)))
5839 (defun org-all-targets (&optional radio)
5840 "Return a list of all targets in this file.
5841 With optional argument RADIO, only find radio targets."
5842 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5843 rtn)
5844 (save-excursion
5845 (goto-char (point-min))
5846 (while (re-search-forward re nil t)
5847 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5848 rtn)))
5850 (defun org-make-target-link-regexp (targets)
5851 "Make regular expression matching all strings in TARGETS.
5852 The regular expression finds the targets also if there is a line break
5853 between words."
5854 (and targets
5855 (concat
5856 "\\<\\("
5857 (mapconcat
5858 (lambda (x)
5859 (setq x (regexp-quote x))
5860 (while (string-match " +" x)
5861 (setq x (replace-match "\\s-+" t t x)))
5863 targets
5864 "\\|")
5865 "\\)\\>")))
5867 (defun org-activate-tags (limit)
5868 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5869 (progn
5870 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5871 (add-text-properties (match-beginning 1) (match-end 1)
5872 (list 'mouse-face 'highlight
5873 'keymap org-mouse-map))
5874 (org-rear-nonsticky-at (match-end 1))
5875 t)))
5877 (defun org-outline-level ()
5878 "Compute the outline level of the heading at point.
5879 This function assumes that the cursor is at the beginning of a line matched
5880 by `outline-regexp'. Otherwise it returns garbage.
5881 If this is called at a normal headline, the level is the number of stars.
5882 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5883 (save-excursion
5884 (looking-at org-outline-regexp)
5885 (1- (- (match-end 0) (match-beginning 0)))))
5887 (defvar org-font-lock-keywords nil)
5889 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5890 "Regular expression matching a property line.")
5892 (defvar org-font-lock-hook nil
5893 "Functions to be called for special font lock stuff.")
5895 (defvar org-font-lock-set-keywords-hook nil
5896 "Functions that can manipulate `org-font-lock-extra-keywords'.
5897 This is called after `org-font-lock-extra-keywords' is defined, but before
5898 it is installed to be used by font lock. This can be useful if something
5899 needs to be inserted at a specific position in the font-lock sequence.")
5901 (defun org-font-lock-hook (limit)
5902 (run-hook-with-args 'org-font-lock-hook limit))
5904 (defun org-set-font-lock-defaults ()
5905 (let* ((em org-fontify-emphasized-text)
5906 (lk org-activate-links)
5907 (org-font-lock-extra-keywords
5908 (list
5909 ;; Call the hook
5910 '(org-font-lock-hook)
5911 ;; Headlines
5912 `(,(if org-fontify-whole-heading-line
5913 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5914 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5915 (1 (org-get-level-face 1))
5916 (2 (org-get-level-face 2))
5917 (3 (org-get-level-face 3)))
5918 ;; Table lines
5919 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5920 (1 'org-table t))
5921 ;; Table internals
5922 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5923 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5924 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5925 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5926 ;; Drawers
5927 (list org-drawer-regexp '(0 'org-special-keyword t))
5928 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5929 ;; Properties
5930 (list org-property-re
5931 '(1 'org-special-keyword t)
5932 '(3 'org-property-value t))
5933 ;; Links
5934 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5935 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5936 (if (memq 'plain lk) '(org-activate-plain-links))
5937 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5938 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5939 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5940 (if (memq 'footnote lk) '(org-activate-footnote-links))
5941 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5942 '(org-hide-wide-columns (0 nil append))
5943 ;; TODO keyword
5944 (list (format org-heading-keyword-regexp-format
5945 org-todo-regexp)
5946 '(2 (org-get-todo-face 2) t))
5947 ;; DONE
5948 (if org-fontify-done-headline
5949 (list (format org-heading-keyword-regexp-format
5950 (concat
5951 "\\(?:"
5952 (mapconcat 'regexp-quote org-done-keywords "\\|")
5953 "\\)"))
5954 '(2 'org-headline-done t))
5955 nil)
5956 ;; Priorities
5957 '(org-font-lock-add-priority-faces)
5958 ;; Tags
5959 '(org-font-lock-add-tag-faces)
5960 ;; Special keywords
5961 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5962 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5963 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5964 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5965 ;; Emphasis
5966 (if em
5967 (if (featurep 'xemacs)
5968 '(org-do-emphasis-faces (0 nil append))
5969 '(org-do-emphasis-faces)))
5970 ;; Checkboxes
5971 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5972 1 'org-checkbox prepend)
5973 (if (cdr (assq 'checkbox org-list-automatic-rules))
5974 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5975 (0 (org-get-checkbox-statistics-face) t)))
5976 ;; Description list items
5977 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5978 1 'org-list-dt prepend)
5979 ;; ARCHIVEd headings
5980 (list (concat
5981 org-outline-regexp-bol
5982 "\\(.*:" org-archive-tag ":.*\\)")
5983 '(1 'org-archived prepend))
5984 ;; Specials
5985 '(org-do-latex-and-special-faces)
5986 '(org-fontify-entities)
5987 '(org-raise-scripts)
5988 ;; Code
5989 '(org-activate-code (1 'org-code t))
5990 ;; COMMENT
5991 (list (format org-heading-keyword-regexp-format
5992 (concat "\\("
5993 org-comment-string "\\|" org-quote-string
5994 "\\)"))
5995 '(2 'org-special-keyword t))
5996 ;; Blocks and meta lines
5997 '(org-fontify-meta-lines-and-blocks)
5999 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6000 (run-hooks 'org-font-lock-set-keywords-hook)
6001 ;; Now set the full font-lock-keywords
6002 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6003 (org-set-local 'font-lock-defaults
6004 '(org-font-lock-keywords t nil nil backward-paragraph))
6005 (kill-local-variable 'font-lock-keywords) nil))
6007 (defun org-toggle-pretty-entities ()
6008 "Toggle the composition display of entities as UTF8 characters."
6009 (interactive)
6010 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6011 (org-restart-font-lock)
6012 (if org-pretty-entities
6013 (message "Entities are displayed as UTF8 characters")
6014 (save-restriction
6015 (widen)
6016 (org-decompose-region (point-min) (point-max))
6017 (message "Entities are displayed plain"))))
6019 (defvar org-custom-properties-overlays nil
6020 "List of overlays used for custom properties.")
6021 (make-variable-buffer-local 'org-custom-properties-overlays)
6023 (defun org-toggle-custom-properties-visibility ()
6024 "Display or hide properties in `org-custom-properties'."
6025 (interactive)
6026 (if org-custom-properties-overlays
6027 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6028 (setq org-custom-properties-overlays nil))
6029 (unless (not org-custom-properties)
6030 (save-excursion
6031 (save-restriction
6032 (widen)
6033 (goto-char (point-min))
6034 (while (re-search-forward org-property-re nil t)
6035 (mapc (lambda(p)
6036 (when (equal p (substring (match-string 1) 1 -1))
6037 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6038 (overlay-put o 'invisible t)
6039 (overlay-put o 'org-custom-property t)
6040 (push o org-custom-properties-overlays))))
6041 org-custom-properties)))))))
6043 (defun org-fontify-entities (limit)
6044 "Find an entity to fontify."
6045 (let (ee)
6046 (when org-pretty-entities
6047 (catch 'match
6048 (while (re-search-forward
6049 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6050 limit t)
6051 (if (and (not (org-in-indented-comment-line))
6052 (setq ee (org-entity-get (match-string 1)))
6053 (= (length (nth 6 ee)) 1))
6054 (let*
6055 ((end (if (equal (match-string 2) "{}")
6056 (match-end 2)
6057 (match-end 1))))
6058 (add-text-properties
6059 (match-beginning 0) end
6060 (list 'font-lock-fontified t))
6061 (compose-region (match-beginning 0) end
6062 (nth 6 ee) nil)
6063 (backward-char 1)
6064 (throw 'match t))))
6065 nil))))
6067 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6068 "Fontify string S like in Org-mode."
6069 (with-temp-buffer
6070 (insert s)
6071 (let ((org-odd-levels-only odd-levels))
6072 (org-mode)
6073 (font-lock-fontify-buffer)
6074 (buffer-string))))
6076 (defvar org-m nil)
6077 (defvar org-l nil)
6078 (defvar org-f nil)
6079 (defun org-get-level-face (n)
6080 "Get the right face for match N in font-lock matching of headlines."
6081 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6082 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6083 (if org-cycle-level-faces
6084 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6085 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6086 (cond
6087 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6088 ((eq n 2) org-f)
6089 (t (if org-level-color-stars-only nil org-f))))
6092 (defun org-get-todo-face (kwd)
6093 "Get the right face for a TODO keyword KWD.
6094 If KWD is a number, get the corresponding match group."
6095 (if (numberp kwd) (setq kwd (match-string kwd)))
6096 (or (org-face-from-face-or-color
6097 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6098 (and (member kwd org-done-keywords) 'org-done)
6099 'org-todo))
6101 (defun org-face-from-face-or-color (context inherit face-or-color)
6102 "Create a face list that inherits INHERIT, but sets the foreground color.
6103 When FACE-OR-COLOR is not a string, just return it."
6104 (if (stringp face-or-color)
6105 (list :inherit inherit
6106 (cdr (assoc context org-faces-easy-properties))
6107 face-or-color)
6108 face-or-color))
6110 (defun org-font-lock-add-tag-faces (limit)
6111 "Add the special tag faces."
6112 (when (and org-tag-faces org-tags-special-faces-re)
6113 (while (re-search-forward org-tags-special-faces-re limit t)
6114 (add-text-properties (match-beginning 1) (match-end 1)
6115 (list 'face (org-get-tag-face 1)
6116 'font-lock-fontified t))
6117 (backward-char 1))))
6119 (defun org-font-lock-add-priority-faces (limit)
6120 "Add the special priority faces."
6121 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6122 (when (save-match-data (org-at-heading-p))
6123 (add-text-properties
6124 (match-beginning 0) (match-end 0)
6125 (list 'face (or (org-face-from-face-or-color
6126 'priority 'org-special-keyword
6127 (cdr (assoc (char-after (match-beginning 1))
6128 org-priority-faces)))
6129 'org-special-keyword)
6130 'font-lock-fontified t)))))
6132 (defun org-get-tag-face (kwd)
6133 "Get the right face for a TODO keyword KWD.
6134 If KWD is a number, get the corresponding match group."
6135 (if (numberp kwd) (setq kwd (match-string kwd)))
6136 (or (org-face-from-face-or-color
6137 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6138 'org-tag))
6140 (defun org-unfontify-region (beg end &optional maybe_loudly)
6141 "Remove fontification and activation overlays from links."
6142 (font-lock-default-unfontify-region beg end)
6143 (let* ((buffer-undo-list t)
6144 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6145 (inhibit-modification-hooks t)
6146 deactivate-mark buffer-file-name buffer-file-truename)
6147 (org-decompose-region beg end)
6148 (remove-text-properties beg end
6149 '(mouse-face t keymap t org-linked-text t
6150 invisible t intangible t
6151 org-no-flyspell t org-emphasis t))
6152 (org-remove-font-lock-display-properties beg end)))
6154 (defconst org-script-display '(((raise -0.3) (height 0.7))
6155 ((raise 0.3) (height 0.7))
6156 ((raise -0.5))
6157 ((raise 0.5)))
6158 "Display properties for showing superscripts and subscripts.")
6160 (defun org-remove-font-lock-display-properties (beg end)
6161 "Remove specific display properties that have been added by font lock.
6162 The will remove the raise properties that are used to show superscripts
6163 and subscripts."
6164 (let (next prop)
6165 (while (< beg end)
6166 (setq next (next-single-property-change beg 'display nil end)
6167 prop (get-text-property beg 'display))
6168 (if (member prop org-script-display)
6169 (put-text-property beg next 'display nil))
6170 (setq beg next))))
6172 (defun org-raise-scripts (limit)
6173 "Add raise properties to sub/superscripts."
6174 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6175 (if (re-search-forward
6176 (if (eq org-use-sub-superscripts t)
6177 org-match-substring-regexp
6178 org-match-substring-with-braces-regexp)
6179 limit t)
6180 (let* ((pos (point)) table-p comment-p
6181 (mpos (match-beginning 3))
6182 (emph-p (get-text-property mpos 'org-emphasis))
6183 (link-p (get-text-property mpos 'mouse-face))
6184 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6185 (goto-char (point-at-bol))
6186 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6187 comment-p (org-looking-at-p "[ \t]*#"))
6188 (goto-char pos)
6189 ;; FIXME: Should we go back one character here, for a_b^c
6190 ;; (goto-char (1- pos)) ;????????????????????
6191 (if (or comment-p emph-p link-p keyw-p)
6193 (put-text-property (match-beginning 3) (match-end 0)
6194 'display
6195 (if (equal (char-after (match-beginning 2)) ?^)
6196 (nth (if table-p 3 1) org-script-display)
6197 (nth (if table-p 2 0) org-script-display)))
6198 (add-text-properties (match-beginning 2) (match-end 2)
6199 (list 'invisible t
6200 'org-dwidth t 'org-dwidth-n 1))
6201 (if (and (eq (char-after (match-beginning 3)) ?{)
6202 (eq (char-before (match-end 3)) ?}))
6203 (progn
6204 (add-text-properties
6205 (match-beginning 3) (1+ (match-beginning 3))
6206 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6207 (add-text-properties
6208 (1- (match-end 3)) (match-end 3)
6209 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6210 t)))))
6212 ;;;; Visibility cycling, including org-goto and indirect buffer
6214 ;;; Cycling
6216 (defvar org-cycle-global-status nil)
6217 (make-variable-buffer-local 'org-cycle-global-status)
6218 (defvar org-cycle-subtree-status nil)
6219 (make-variable-buffer-local 'org-cycle-subtree-status)
6221 ;;;###autoload
6223 (defvar org-inlinetask-min-level)
6225 (defun org-cycle (&optional arg)
6226 "TAB-action and visibility cycling for Org-mode.
6228 This is the command invoked in Org-mode by the TAB key. Its main purpose
6229 is outline visibility cycling, but it also invokes other actions
6230 in special contexts.
6232 - When this function is called with a prefix argument, rotate the entire
6233 buffer through 3 states (global cycling)
6234 1. OVERVIEW: Show only top-level headlines.
6235 2. CONTENTS: Show all headlines of all levels, but no body text.
6236 3. SHOW ALL: Show everything.
6237 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6238 determined by the variable `org-startup-folded', and by any VISIBILITY
6239 properties in the buffer.
6240 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6241 including any drawers.
6243 - When inside a table, re-align the table and move to the next field.
6245 - When point is at the beginning of a headline, rotate the subtree started
6246 by this line through 3 different states (local cycling)
6247 1. FOLDED: Only the main headline is shown.
6248 2. CHILDREN: The main headline and the direct children are shown.
6249 From this state, you can move to one of the children
6250 and zoom in further.
6251 3. SUBTREE: Show the entire subtree, including body text.
6252 If there is no subtree, switch directly from CHILDREN to FOLDED.
6254 - When point is at the beginning of an empty headline and the variable
6255 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6256 of the headline by demoting and promoting it to likely levels. This
6257 speeds up creation document structure by pressing TAB once or several
6258 times right after creating a new headline.
6260 - When there is a numeric prefix, go up to a heading with level ARG, do
6261 a `show-subtree' and return to the previous cursor position. If ARG
6262 is negative, go up that many levels.
6264 - When point is not at the beginning of a headline, execute the global
6265 binding for TAB, which is re-indenting the line. See the option
6266 `org-cycle-emulate-tab' for details.
6268 - Special case: if point is at the beginning of the buffer and there is
6269 no headline in line 1, this function will act as if called with prefix arg
6270 (C-u TAB, same as S-TAB) also when called without prefix arg.
6271 But only if also the variable `org-cycle-global-at-bob' is t."
6272 (interactive "P")
6273 (org-load-modules-maybe)
6274 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6275 (and org-cycle-level-after-item/entry-creation
6276 (or (org-cycle-level)
6277 (org-cycle-item-indentation))))
6278 (let* ((limit-level
6279 (or org-cycle-max-level
6280 (and (boundp 'org-inlinetask-min-level)
6281 org-inlinetask-min-level
6282 (1- org-inlinetask-min-level))))
6283 (nstars (and limit-level
6284 (if org-odd-levels-only
6285 (and limit-level (1- (* limit-level 2)))
6286 limit-level)))
6287 (org-outline-regexp
6288 (if (not (derived-mode-p 'org-mode))
6289 outline-regexp
6290 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6291 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6292 (not (looking-at org-outline-regexp))))
6293 (org-cycle-hook
6294 (if bob-special
6295 (delq 'org-optimize-window-after-visibility-change
6296 (copy-sequence org-cycle-hook))
6297 org-cycle-hook))
6298 (pos (point)))
6300 (if (or bob-special (equal arg '(4)))
6301 ;; special case: use global cycling
6302 (setq arg t))
6304 (cond
6306 ((equal arg '(16))
6307 (setq last-command 'dummy)
6308 (org-set-startup-visibility)
6309 (message "Startup visibility, plus VISIBILITY properties"))
6311 ((equal arg '(64))
6312 (show-all)
6313 (message "Entire buffer visible, including drawers"))
6315 ;; Table: enter it or move to the next field.
6316 ((org-at-table-p 'any)
6317 (if (org-at-table.el-p)
6318 (message "Use C-c ' to edit table.el tables")
6319 (if arg (org-table-edit-field t)
6320 (org-table-justify-field-maybe)
6321 (call-interactively 'org-table-next-field))))
6323 ((run-hook-with-args-until-success
6324 'org-tab-after-check-for-table-hook))
6326 ;; Global cycling: delegate to `org-cycle-internal-global'.
6327 ((eq arg t) (org-cycle-internal-global))
6329 ;; Drawers: delegate to `org-flag-drawer'.
6330 ((and org-drawers org-drawer-regexp
6331 (save-excursion
6332 (beginning-of-line 1)
6333 (looking-at org-drawer-regexp)))
6334 (org-flag-drawer ; toggle block visibility
6335 (not (get-char-property (match-end 0) 'invisible))))
6337 ;; Show-subtree, ARG levels up from here.
6338 ((integerp arg)
6339 (save-excursion
6340 (org-back-to-heading)
6341 (outline-up-heading (if (< arg 0) (- arg)
6342 (- (funcall outline-level) arg)))
6343 (org-show-subtree)))
6345 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6346 ((and (featurep 'org-inlinetask)
6347 (org-inlinetask-at-task-p)
6348 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6349 (org-inlinetask-toggle-visibility))
6351 ((org-try-cdlatex-tab))
6353 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6354 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6355 (save-excursion (beginning-of-line 1)
6356 (looking-at org-outline-regexp)))
6357 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6358 (org-cycle-internal-local))
6360 ;; From there: TAB emulation and template completion.
6361 (buffer-read-only (org-back-to-heading))
6363 ((run-hook-with-args-until-success
6364 'org-tab-after-check-for-cycling-hook))
6366 ((org-try-structure-completion))
6368 ((run-hook-with-args-until-success
6369 'org-tab-before-tab-emulation-hook))
6371 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6372 (or (not (bolp))
6373 (not (looking-at org-outline-regexp))))
6374 (call-interactively (global-key-binding "\t")))
6376 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6377 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6378 (or (and (eq org-cycle-emulate-tab 'white)
6379 (= (match-end 0) (point-at-eol)))
6380 (and (eq org-cycle-emulate-tab 'whitestart)
6381 (>= (match-end 0) pos))))
6383 (eq org-cycle-emulate-tab t))
6384 (call-interactively (global-key-binding "\t")))
6386 (t (save-excursion
6387 (org-back-to-heading)
6388 (org-cycle)))))))
6390 (defun org-cycle-internal-global ()
6391 "Do the global cycling action."
6392 ;; Hack to avoid display of messages for .org attachments in Gnus
6393 (let ((ga (string-match "\\*fontification" (buffer-name))))
6394 (cond
6395 ((and (eq last-command this-command)
6396 (eq org-cycle-global-status 'overview))
6397 ;; We just created the overview - now do table of contents
6398 ;; This can be slow in very large buffers, so indicate action
6399 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6400 (unless ga (message "CONTENTS..."))
6401 (org-content)
6402 (unless ga (message "CONTENTS...done"))
6403 (setq org-cycle-global-status 'contents)
6404 (run-hook-with-args 'org-cycle-hook 'contents))
6406 ((and (eq last-command this-command)
6407 (eq org-cycle-global-status 'contents))
6408 ;; We just showed the table of contents - now show everything
6409 (run-hook-with-args 'org-pre-cycle-hook 'all)
6410 (show-all)
6411 (unless ga (message "SHOW ALL"))
6412 (setq org-cycle-global-status 'all)
6413 (run-hook-with-args 'org-cycle-hook 'all))
6416 ;; Default action: go to overview
6417 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6418 (org-overview)
6419 (unless ga (message "OVERVIEW"))
6420 (setq org-cycle-global-status 'overview)
6421 (run-hook-with-args 'org-cycle-hook 'overview)))))
6423 (defun org-cycle-internal-local ()
6424 "Do the local cycling action."
6425 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6426 ;; First, determine end of headline (EOH), end of subtree or item
6427 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6428 (save-excursion
6429 (if (org-at-item-p)
6430 (progn
6431 (beginning-of-line)
6432 (setq struct (org-list-struct))
6433 (setq eoh (point-at-eol))
6434 (setq eos (org-list-get-item-end-before-blank (point) struct))
6435 (setq has-children (org-list-has-child-p (point) struct)))
6436 (org-back-to-heading)
6437 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6438 (setq eos (save-excursion
6439 (org-end-of-subtree t)
6440 (unless (eobp)
6441 (skip-chars-forward " \t\n"))
6442 (if (eobp) (point) (1- (point)))))
6443 (setq has-children
6444 (or (save-excursion
6445 (let ((level (funcall outline-level)))
6446 (outline-next-heading)
6447 (and (org-at-heading-p t)
6448 (> (funcall outline-level) level))))
6449 (save-excursion
6450 (org-list-search-forward (org-item-beginning-re) eos t)))))
6451 ;; Determine end invisible part of buffer (EOL)
6452 (beginning-of-line 2)
6453 ;; XEmacs doesn't have `next-single-char-property-change'
6454 (if (featurep 'xemacs)
6455 (while (and (not (eobp)) ;; this is like `next-line'
6456 (get-char-property (1- (point)) 'invisible))
6457 (beginning-of-line 2))
6458 (while (and (not (eobp)) ;; this is like `next-line'
6459 (get-char-property (1- (point)) 'invisible))
6460 (goto-char (next-single-char-property-change (point) 'invisible))
6461 (and (eolp) (beginning-of-line 2))))
6462 (setq eol (point)))
6463 ;; Find out what to do next and set `this-command'
6464 (cond
6465 ((= eos eoh)
6466 ;; Nothing is hidden behind this heading
6467 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6468 (message "EMPTY ENTRY")
6469 (setq org-cycle-subtree-status nil)
6470 (save-excursion
6471 (goto-char eos)
6472 (outline-next-heading)
6473 (if (outline-invisible-p) (org-flag-heading nil))))
6474 ((and (or (>= eol eos)
6475 (not (string-match "\\S-" (buffer-substring eol eos))))
6476 (or has-children
6477 (not (setq children-skipped
6478 org-cycle-skip-children-state-if-no-children))))
6479 ;; Entire subtree is hidden in one line: children view
6480 (run-hook-with-args 'org-pre-cycle-hook 'children)
6481 (if (org-at-item-p)
6482 (org-list-set-item-visibility (point-at-bol) struct 'children)
6483 (org-show-entry)
6484 (org-with-limited-levels (show-children))
6485 ;; FIXME: This slows down the func way too much.
6486 ;; How keep drawers hidden in subtree anyway?
6487 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6488 ;; (org-cycle-hide-drawers 'subtree))
6490 ;; Fold every list in subtree to top-level items.
6491 (when (eq org-cycle-include-plain-lists 'integrate)
6492 (save-excursion
6493 (org-back-to-heading)
6494 (while (org-list-search-forward (org-item-beginning-re) eos t)
6495 (beginning-of-line 1)
6496 (let* ((struct (org-list-struct))
6497 (prevs (org-list-prevs-alist struct))
6498 (end (org-list-get-bottom-point struct)))
6499 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6500 (org-list-get-all-items (point) struct prevs))
6501 (goto-char end))))))
6502 (message "CHILDREN")
6503 (save-excursion
6504 (goto-char eos)
6505 (outline-next-heading)
6506 (if (outline-invisible-p) (org-flag-heading nil)))
6507 (setq org-cycle-subtree-status 'children)
6508 (run-hook-with-args 'org-cycle-hook 'children))
6509 ((or children-skipped
6510 (and (eq last-command this-command)
6511 (eq org-cycle-subtree-status 'children)))
6512 ;; We just showed the children, or no children are there,
6513 ;; now show everything.
6514 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6515 (outline-flag-region eoh eos nil)
6516 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6517 (setq org-cycle-subtree-status 'subtree)
6518 (run-hook-with-args 'org-cycle-hook 'subtree))
6520 ;; Default action: hide the subtree.
6521 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6522 (outline-flag-region eoh eos t)
6523 (message "FOLDED")
6524 (setq org-cycle-subtree-status 'folded)
6525 (run-hook-with-args 'org-cycle-hook 'folded)))))
6527 ;;;###autoload
6528 (defun org-global-cycle (&optional arg)
6529 "Cycle the global visibility. For details see `org-cycle'.
6530 With \\[universal-argument] prefix arg, switch to startup visibility.
6531 With a numeric prefix, show all headlines up to that level."
6532 (interactive "P")
6533 (let ((org-cycle-include-plain-lists
6534 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6535 (cond
6536 ((integerp arg)
6537 (show-all)
6538 (hide-sublevels arg)
6539 (setq org-cycle-global-status 'contents))
6540 ((equal arg '(4))
6541 (org-set-startup-visibility)
6542 (message "Startup visibility, plus VISIBILITY properties."))
6544 (org-cycle '(4))))))
6546 (defun org-set-startup-visibility ()
6547 "Set the visibility required by startup options and properties."
6548 (cond
6549 ((eq org-startup-folded t)
6550 (org-cycle '(4)))
6551 ((eq org-startup-folded 'content)
6552 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6553 (org-cycle '(4)) (org-cycle '(4)))))
6554 (unless (eq org-startup-folded 'showeverything)
6555 (if org-hide-block-startup (org-hide-block-all))
6556 (org-set-visibility-according-to-property 'no-cleanup)
6557 (org-cycle-hide-archived-subtrees 'all)
6558 (org-cycle-hide-drawers 'all)
6559 (org-cycle-show-empty-lines t)))
6561 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6562 "Switch subtree visibilities according to :VISIBILITY: property."
6563 (interactive)
6564 (let (org-show-entry-below state)
6565 (save-excursion
6566 (goto-char (point-min))
6567 (while (re-search-forward
6568 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6569 nil t)
6570 (setq state (match-string 1))
6571 (save-excursion
6572 (org-back-to-heading t)
6573 (hide-subtree)
6574 (org-reveal)
6575 (cond
6576 ((equal state '("fold" "folded"))
6577 (hide-subtree))
6578 ((equal state "children")
6579 (org-show-hidden-entry)
6580 (show-children))
6581 ((equal state "content")
6582 (save-excursion
6583 (save-restriction
6584 (org-narrow-to-subtree)
6585 (org-content))))
6586 ((member state '("all" "showall"))
6587 (show-subtree)))))
6588 (unless no-cleanup
6589 (org-cycle-hide-archived-subtrees 'all)
6590 (org-cycle-hide-drawers 'all)
6591 (org-cycle-show-empty-lines 'all)))))
6593 ;; This function uses outline-regexp instead of the more fundamental
6594 ;; org-outline-regexp so that org-cycle-global works outside of Org
6595 ;; buffers, where outline-regexp is needed.
6596 (defun org-overview ()
6597 "Switch to overview mode, showing only top-level headlines.
6598 Really, this shows all headlines with level equal or greater than the level
6599 of the first headline in the buffer. This is important, because if the
6600 first headline is not level one, then (hide-sublevels 1) gives confusing
6601 results."
6602 (interactive)
6603 (let ((level (save-excursion
6604 (goto-char (point-min))
6605 (if (re-search-forward (concat "^" outline-regexp) nil t)
6606 (progn
6607 (goto-char (match-beginning 0))
6608 (funcall outline-level))))))
6609 (and level (hide-sublevels level))))
6611 (defun org-content (&optional arg)
6612 "Show all headlines in the buffer, like a table of contents.
6613 With numerical argument N, show content up to level N."
6614 (interactive "P")
6615 (save-excursion
6616 ;; Visit all headings and show their offspring
6617 (and (integerp arg) (org-overview))
6618 (goto-char (point-max))
6619 (catch 'exit
6620 (while (and (progn (condition-case nil
6621 (outline-previous-visible-heading 1)
6622 (error (goto-char (point-min))))
6624 (looking-at org-outline-regexp))
6625 (if (integerp arg)
6626 (show-children (1- arg))
6627 (show-branches))
6628 (if (bobp) (throw 'exit nil))))))
6631 (defun org-optimize-window-after-visibility-change (state)
6632 "Adjust the window after a change in outline visibility.
6633 This function is the default value of the hook `org-cycle-hook'."
6634 (when (get-buffer-window (current-buffer))
6635 (cond
6636 ((eq state 'content) nil)
6637 ((eq state 'all) nil)
6638 ((eq state 'folded) nil)
6639 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6640 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6642 (defun org-remove-empty-overlays-at (pos)
6643 "Remove outline overlays that do not contain non-white stuff."
6644 (mapc
6645 (lambda (o)
6646 (and (eq 'outline (overlay-get o 'invisible))
6647 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6648 (overlay-end o))))
6649 (delete-overlay o)))
6650 (overlays-at pos)))
6652 (defun org-clean-visibility-after-subtree-move ()
6653 "Fix visibility issues after moving a subtree."
6654 ;; First, find a reasonable region to look at:
6655 ;; Start two siblings above, end three below
6656 (let* ((beg (save-excursion
6657 (and (org-get-last-sibling)
6658 (org-get-last-sibling))
6659 (point)))
6660 (end (save-excursion
6661 (and (org-get-next-sibling)
6662 (org-get-next-sibling)
6663 (org-get-next-sibling))
6664 (if (org-at-heading-p)
6665 (point-at-eol)
6666 (point))))
6667 (level (looking-at "\\*+"))
6668 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6669 (save-excursion
6670 (save-restriction
6671 (narrow-to-region beg end)
6672 (when re
6673 ;; Properly fold already folded siblings
6674 (goto-char (point-min))
6675 (while (re-search-forward re nil t)
6676 (if (and (not (outline-invisible-p))
6677 (save-excursion
6678 (goto-char (point-at-eol)) (outline-invisible-p)))
6679 (hide-entry))))
6680 (org-cycle-show-empty-lines 'overview)
6681 (org-cycle-hide-drawers 'overview)))))
6683 (defun org-cycle-show-empty-lines (state)
6684 "Show empty lines above all visible headlines.
6685 The region to be covered depends on STATE when called through
6686 `org-cycle-hook'. Lisp program can use t for STATE to get the
6687 entire buffer covered. Note that an empty line is only shown if there
6688 are at least `org-cycle-separator-lines' empty lines before the headline."
6689 (when (not (= org-cycle-separator-lines 0))
6690 (save-excursion
6691 (let* ((n (abs org-cycle-separator-lines))
6692 (re (cond
6693 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6694 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6695 (t (let ((ns (number-to-string (- n 2))))
6696 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6697 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6698 beg end b e)
6699 (cond
6700 ((memq state '(overview contents t))
6701 (setq beg (point-min) end (point-max)))
6702 ((memq state '(children folded))
6703 (setq beg (point) end (progn (org-end-of-subtree t t)
6704 (beginning-of-line 2)
6705 (point)))))
6706 (when beg
6707 (goto-char beg)
6708 (while (re-search-forward re end t)
6709 (unless (get-char-property (match-end 1) 'invisible)
6710 (setq e (match-end 1))
6711 (if (< org-cycle-separator-lines 0)
6712 (setq b (save-excursion
6713 (goto-char (match-beginning 0))
6714 (org-back-over-empty-lines)
6715 (if (save-excursion
6716 (goto-char (max (point-min) (1- (point))))
6717 (org-at-heading-p))
6718 (1- (point))
6719 (point))))
6720 (setq b (match-beginning 1)))
6721 (outline-flag-region b e nil)))))))
6722 ;; Never hide empty lines at the end of the file.
6723 (save-excursion
6724 (goto-char (point-max))
6725 (outline-previous-heading)
6726 (outline-end-of-heading)
6727 (if (and (looking-at "[ \t\n]+")
6728 (= (match-end 0) (point-max)))
6729 (outline-flag-region (point) (match-end 0) nil))))
6731 (defun org-show-empty-lines-in-parent ()
6732 "Move to the parent and re-show empty lines before visible headlines."
6733 (save-excursion
6734 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6735 (org-cycle-show-empty-lines context))))
6737 (defun org-files-list ()
6738 "Return `org-agenda-files' list, plus all open org-mode files.
6739 This is useful for operations that need to scan all of a user's
6740 open and agenda-wise Org files."
6741 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6742 (dolist (buf (buffer-list))
6743 (with-current-buffer buf
6744 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6745 (let ((file (expand-file-name (buffer-file-name))))
6746 (unless (member file files)
6747 (push file files))))))
6748 files))
6750 (defsubst org-entry-beginning-position ()
6751 "Return the beginning position of the current entry."
6752 (save-excursion (outline-back-to-heading t) (point)))
6754 (defsubst org-entry-end-position ()
6755 "Return the end position of the current entry."
6756 (save-excursion (outline-next-heading) (point)))
6758 (defun org-cycle-hide-drawers (state)
6759 "Re-hide all drawers after a visibility state change."
6760 (when (and (derived-mode-p 'org-mode)
6761 (not (memq state '(overview folded contents))))
6762 (save-excursion
6763 (let* ((globalp (memq state '(contents all)))
6764 (beg (if globalp (point-min) (point)))
6765 (end (if globalp (point-max)
6766 (if (eq state 'children)
6767 (save-excursion (outline-next-heading) (point))
6768 (org-end-of-subtree t)))))
6769 (goto-char beg)
6770 (while (re-search-forward org-drawer-regexp end t)
6771 (org-flag-drawer t))))))
6773 (defun org-flag-drawer (flag)
6774 "When FLAG is non-nil, hide the drawer we are within.
6775 Otherwise make it visible."
6776 (save-excursion
6777 (beginning-of-line 1)
6778 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6779 (let ((b (match-end 0)))
6780 (if (re-search-forward
6781 "^[ \t]*:END:"
6782 (save-excursion (outline-next-heading) (point)) t)
6783 (outline-flag-region b (point-at-eol) flag)
6784 (error ":END: line missing at position %s" b))))))
6786 (defun org-subtree-end-visible-p ()
6787 "Is the end of the current subtree visible?"
6788 (pos-visible-in-window-p
6789 (save-excursion (org-end-of-subtree t) (point))))
6791 (defun org-first-headline-recenter (&optional N)
6792 "Move cursor to the first headline and recenter the headline.
6793 Optional argument N means put the headline into the Nth line of the window."
6794 (goto-char (point-min))
6795 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6796 (beginning-of-line)
6797 (recenter (prefix-numeric-value N))))
6799 ;;; Saving and restoring visibility
6801 (defun org-outline-overlay-data (&optional use-markers)
6802 "Return a list of the locations of all outline overlays.
6803 These are overlays with the `invisible' property value `outline'.
6804 The return value is a list of cons cells, with start and stop
6805 positions for each overlay.
6806 If USE-MARKERS is set, return the positions as markers."
6807 (let (beg end)
6808 (save-excursion
6809 (save-restriction
6810 (widen)
6811 (delq nil
6812 (mapcar (lambda (o)
6813 (when (eq (overlay-get o 'invisible) 'outline)
6814 (setq beg (overlay-start o)
6815 end (overlay-end o))
6816 (and beg end (> end beg)
6817 (if use-markers
6818 (cons (move-marker (make-marker) beg)
6819 (move-marker (make-marker) end))
6820 (cons beg end)))))
6821 (overlays-in (point-min) (point-max))))))))
6823 (defun org-set-outline-overlay-data (data)
6824 "Create visibility overlays for all positions in DATA.
6825 DATA should have been made by `org-outline-overlay-data'."
6826 (let (o)
6827 (save-excursion
6828 (save-restriction
6829 (widen)
6830 (show-all)
6831 (mapc (lambda (c)
6832 (outline-flag-region (car c) (cdr c) t))
6833 data)))))
6835 ;;; Folding of blocks
6837 (defvar org-hide-block-overlays nil
6838 "Overlays hiding blocks.")
6839 (make-variable-buffer-local 'org-hide-block-overlays)
6841 (defun org-block-map (function &optional start end)
6842 "Call FUNCTION at the head of all source blocks in the current buffer.
6843 Optional arguments START and END can be used to limit the range."
6844 (let ((start (or start (point-min)))
6845 (end (or end (point-max))))
6846 (save-excursion
6847 (goto-char start)
6848 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6849 (save-excursion
6850 (save-match-data
6851 (goto-char (match-beginning 0))
6852 (funcall function)))))))
6854 (defun org-hide-block-toggle-all ()
6855 "Toggle the visibility of all blocks in the current buffer."
6856 (org-block-map #'org-hide-block-toggle))
6858 (defun org-hide-block-all ()
6859 "Fold all blocks in the current buffer."
6860 (interactive)
6861 (org-show-block-all)
6862 (org-block-map #'org-hide-block-toggle-maybe))
6864 (defun org-show-block-all ()
6865 "Unfold all blocks in the current buffer."
6866 (interactive)
6867 (mapc 'delete-overlay org-hide-block-overlays)
6868 (setq org-hide-block-overlays nil))
6870 (defun org-hide-block-toggle-maybe ()
6871 "Toggle visibility of block at point."
6872 (interactive)
6873 (let ((case-fold-search t))
6874 (if (save-excursion
6875 (beginning-of-line 1)
6876 (looking-at org-block-regexp))
6877 (progn (org-hide-block-toggle)
6878 t) ;; to signal that we took action
6879 nil))) ;; to signal that we did not
6881 (defun org-hide-block-toggle (&optional force)
6882 "Toggle the visibility of the current block."
6883 (interactive)
6884 (save-excursion
6885 (beginning-of-line)
6886 (if (re-search-forward org-block-regexp nil t)
6887 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6888 (end (match-end 0)) ;; end of entire body
6890 (if (memq t (mapcar (lambda (overlay)
6891 (eq (overlay-get overlay 'invisible)
6892 'org-hide-block))
6893 (overlays-at start)))
6894 (if (or (not force) (eq force 'off))
6895 (mapc (lambda (ov)
6896 (when (member ov org-hide-block-overlays)
6897 (setq org-hide-block-overlays
6898 (delq ov org-hide-block-overlays)))
6899 (when (eq (overlay-get ov 'invisible)
6900 'org-hide-block)
6901 (delete-overlay ov)))
6902 (overlays-at start)))
6903 (setq ov (make-overlay start end))
6904 (overlay-put ov 'invisible 'org-hide-block)
6905 ;; make the block accessible to isearch
6906 (overlay-put
6907 ov 'isearch-open-invisible
6908 (lambda (ov)
6909 (when (member ov org-hide-block-overlays)
6910 (setq org-hide-block-overlays
6911 (delq ov org-hide-block-overlays)))
6912 (when (eq (overlay-get ov 'invisible)
6913 'org-hide-block)
6914 (delete-overlay ov))))
6915 (push ov org-hide-block-overlays)))
6916 (error "Not looking at a source block"))))
6918 ;; org-tab-after-check-for-cycling-hook
6919 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6920 ;; Remove overlays when changing major mode
6921 (add-hook 'org-mode-hook
6922 (lambda () (org-add-hook 'change-major-mode-hook
6923 'org-show-block-all 'append 'local)))
6925 ;;; Org-goto
6927 (defvar org-goto-window-configuration nil)
6928 (defvar org-goto-marker nil)
6929 (defvar org-goto-map
6930 (let ((map (make-sparse-keymap)))
6931 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6932 (while (setq cmd (pop cmds))
6933 (substitute-key-definition cmd cmd map global-map)))
6934 (suppress-keymap map)
6935 (org-defkey map "\C-m" 'org-goto-ret)
6936 (org-defkey map [(return)] 'org-goto-ret)
6937 (org-defkey map [(left)] 'org-goto-left)
6938 (org-defkey map [(right)] 'org-goto-right)
6939 (org-defkey map [(control ?g)] 'org-goto-quit)
6940 (org-defkey map "\C-i" 'org-cycle)
6941 (org-defkey map [(tab)] 'org-cycle)
6942 (org-defkey map [(down)] 'outline-next-visible-heading)
6943 (org-defkey map [(up)] 'outline-previous-visible-heading)
6944 (if org-goto-auto-isearch
6945 (if (fboundp 'define-key-after)
6946 (define-key-after map [t] 'org-goto-local-auto-isearch)
6947 nil)
6948 (org-defkey map "q" 'org-goto-quit)
6949 (org-defkey map "n" 'outline-next-visible-heading)
6950 (org-defkey map "p" 'outline-previous-visible-heading)
6951 (org-defkey map "f" 'outline-forward-same-level)
6952 (org-defkey map "b" 'outline-backward-same-level)
6953 (org-defkey map "u" 'outline-up-heading))
6954 (org-defkey map "/" 'org-occur)
6955 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6956 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6957 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6958 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6959 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6960 map))
6962 (defconst org-goto-help
6963 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6964 RET=jump to location [Q]uit and return to previous location
6965 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6967 (defvar org-goto-start-pos) ; dynamically scoped parameter
6969 ;; FIXME: Docstring does not mention both interfaces
6970 (defun org-goto (&optional alternative-interface)
6971 "Look up a different location in the current file, keeping current visibility.
6973 When you want look-up or go to a different location in a
6974 document, the fastest way is often to fold the entire buffer and
6975 then dive into the tree. This method has the disadvantage, that
6976 the previous location will be folded, which may not be what you
6977 want.
6979 This command works around this by showing a copy of the current
6980 buffer in an indirect buffer, in overview mode. You can dive
6981 into the tree in that copy, use org-occur and incremental search
6982 to find a location. When pressing RET or `Q', the command
6983 returns to the original buffer in which the visibility is still
6984 unchanged. After RET it will also jump to the location selected
6985 in the indirect buffer and expose the headline hierarchy above.
6987 With a prefix argument, use the alternative interface: e.g. if
6988 `org-goto-interface' is 'outline use 'outline-path-completion."
6989 (interactive "P")
6990 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6991 (org-refile-use-outline-path t)
6992 (org-refile-target-verify-function nil)
6993 (interface
6994 (if (not alternative-interface)
6995 org-goto-interface
6996 (if (eq org-goto-interface 'outline)
6997 'outline-path-completion
6998 'outline)))
6999 (org-goto-start-pos (point))
7000 (selected-point
7001 (if (eq interface 'outline)
7002 (car (org-get-location (current-buffer) org-goto-help))
7003 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7004 (org-refile-check-position pa)
7005 (nth 3 pa)))))
7006 (if selected-point
7007 (progn
7008 (org-mark-ring-push org-goto-start-pos)
7009 (goto-char selected-point)
7010 (if (or (outline-invisible-p) (org-invisible-p2))
7011 (org-show-context 'org-goto)))
7012 (message "Quit"))))
7014 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7015 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7016 (defvar org-goto-local-auto-isearch-map) ; defined below
7018 (defun org-get-location (buf help)
7019 "Let the user select a location in the Org-mode buffer BUF.
7020 This function uses a recursive edit. It returns the selected position
7021 or nil."
7022 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7023 (isearch-hide-immediately nil)
7024 (isearch-search-fun-function
7025 (lambda () 'org-goto-local-search-headings))
7026 (org-goto-selected-point org-goto-exit-command)
7027 (pop-up-frames nil)
7028 (special-display-buffer-names nil)
7029 (special-display-regexps nil)
7030 (special-display-function nil))
7031 (save-excursion
7032 (save-window-excursion
7033 (delete-other-windows)
7034 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7035 (org-pop-to-buffer-same-window
7036 (condition-case nil
7037 (make-indirect-buffer (current-buffer) "*org-goto*")
7038 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7039 (with-output-to-temp-buffer "*Help*"
7040 (princ help))
7041 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7042 (setq buffer-read-only nil)
7043 (let ((org-startup-truncated t)
7044 (org-startup-folded nil)
7045 (org-startup-align-all-tables nil))
7046 (org-mode)
7047 (org-overview))
7048 (setq buffer-read-only t)
7049 (if (and (boundp 'org-goto-start-pos)
7050 (integer-or-marker-p org-goto-start-pos))
7051 (let ((org-show-hierarchy-above t)
7052 (org-show-siblings t)
7053 (org-show-following-heading t))
7054 (goto-char org-goto-start-pos)
7055 (and (outline-invisible-p) (org-show-context)))
7056 (goto-char (point-min)))
7057 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7058 (message "Select location and press RET")
7059 (use-local-map org-goto-map)
7060 (recursive-edit)
7062 (kill-buffer "*org-goto*")
7063 (cons org-goto-selected-point org-goto-exit-command)))
7065 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7066 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7067 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7068 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7070 (defun org-goto-local-search-headings (string bound noerror)
7071 "Search and make sure that any matches are in headlines."
7072 (catch 'return
7073 (while (if isearch-forward
7074 (search-forward string bound noerror)
7075 (search-backward string bound noerror))
7076 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7077 (and (member :headline context)
7078 (not (member :tags context))))
7079 (throw 'return (point))))))
7081 (defun org-goto-local-auto-isearch ()
7082 "Start isearch."
7083 (interactive)
7084 (goto-char (point-min))
7085 (let ((keys (this-command-keys)))
7086 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7087 (isearch-mode t)
7088 (isearch-process-search-char (string-to-char keys)))))
7090 (defun org-goto-ret (&optional arg)
7091 "Finish `org-goto' by going to the new location."
7092 (interactive "P")
7093 (setq org-goto-selected-point (point)
7094 org-goto-exit-command 'return)
7095 (throw 'exit nil))
7097 (defun org-goto-left ()
7098 "Finish `org-goto' by going to the new location."
7099 (interactive)
7100 (if (org-at-heading-p)
7101 (progn
7102 (beginning-of-line 1)
7103 (setq org-goto-selected-point (point)
7104 org-goto-exit-command 'left)
7105 (throw 'exit nil))
7106 (error "Not on a heading")))
7108 (defun org-goto-right ()
7109 "Finish `org-goto' by going to the new location."
7110 (interactive)
7111 (if (org-at-heading-p)
7112 (progn
7113 (setq org-goto-selected-point (point)
7114 org-goto-exit-command 'right)
7115 (throw 'exit nil))
7116 (error "Not on a heading")))
7118 (defun org-goto-quit ()
7119 "Finish `org-goto' without cursor motion."
7120 (interactive)
7121 (setq org-goto-selected-point nil)
7122 (setq org-goto-exit-command 'quit)
7123 (throw 'exit nil))
7125 ;;; Indirect buffer display of subtrees
7127 (defvar org-indirect-dedicated-frame nil
7128 "This is the frame being used for indirect tree display.")
7129 (defvar org-last-indirect-buffer nil)
7131 (defun org-tree-to-indirect-buffer (&optional arg)
7132 "Create indirect buffer and narrow it to current subtree.
7133 With numerical prefix ARG, go up to this level and then take that tree.
7134 If ARG is negative, go up that many levels.
7135 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7136 indirect buffer previously made with this command, to avoid proliferation of
7137 indirect buffers. However, when you call the command with a \
7138 \\[universal-argument] prefix, or
7139 when `org-indirect-buffer-display' is `new-frame', the last buffer
7140 is kept so that you can work with several indirect buffers at the same time.
7141 If `org-indirect-buffer-display' is `dedicated-frame', the \
7142 \\[universal-argument] prefix also
7143 requests that a new frame be made for the new buffer, so that the dedicated
7144 frame is not changed."
7145 (interactive "P")
7146 (let ((cbuf (current-buffer))
7147 (cwin (selected-window))
7148 (pos (point))
7149 beg end level heading ibuf)
7150 (save-excursion
7151 (org-back-to-heading t)
7152 (when (numberp arg)
7153 (setq level (org-outline-level))
7154 (if (< arg 0) (setq arg (+ level arg)))
7155 (while (> (setq level (org-outline-level)) arg)
7156 (outline-up-heading 1 t)))
7157 (setq beg (point)
7158 heading (org-get-heading))
7159 (org-end-of-subtree t t)
7160 (if (org-at-heading-p) (backward-char 1))
7161 (setq end (point)))
7162 (if (and (buffer-live-p org-last-indirect-buffer)
7163 (not (eq org-indirect-buffer-display 'new-frame))
7164 (not arg))
7165 (kill-buffer org-last-indirect-buffer))
7166 (setq ibuf (org-get-indirect-buffer cbuf)
7167 org-last-indirect-buffer ibuf)
7168 (cond
7169 ((or (eq org-indirect-buffer-display 'new-frame)
7170 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7171 (select-frame (make-frame))
7172 (delete-other-windows)
7173 (org-pop-to-buffer-same-window ibuf)
7174 (org-set-frame-title heading))
7175 ((eq org-indirect-buffer-display 'dedicated-frame)
7176 (raise-frame
7177 (select-frame (or (and org-indirect-dedicated-frame
7178 (frame-live-p org-indirect-dedicated-frame)
7179 org-indirect-dedicated-frame)
7180 (setq org-indirect-dedicated-frame (make-frame)))))
7181 (delete-other-windows)
7182 (org-pop-to-buffer-same-window ibuf)
7183 (org-set-frame-title (concat "Indirect: " heading)))
7184 ((eq org-indirect-buffer-display 'current-window)
7185 (org-pop-to-buffer-same-window ibuf))
7186 ((eq org-indirect-buffer-display 'other-window)
7187 (pop-to-buffer ibuf))
7188 (t (error "Invalid value")))
7189 (if (featurep 'xemacs)
7190 (save-excursion (org-mode) (turn-on-font-lock)))
7191 (narrow-to-region beg end)
7192 (show-all)
7193 (goto-char pos)
7194 (run-hook-with-args 'org-cycle-hook 'all)
7195 (and (window-live-p cwin) (select-window cwin))))
7197 (defun org-get-indirect-buffer (&optional buffer)
7198 (setq buffer (or buffer (current-buffer)))
7199 (let ((n 1) (base (buffer-name buffer)) bname)
7200 (while (buffer-live-p
7201 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7202 (setq n (1+ n)))
7203 (condition-case nil
7204 (make-indirect-buffer buffer bname 'clone)
7205 (error (make-indirect-buffer buffer bname)))))
7207 (defun org-set-frame-title (title)
7208 "Set the title of the current frame to the string TITLE."
7209 ;; FIXME: how to name a single frame in XEmacs???
7210 (unless (featurep 'xemacs)
7211 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7213 ;;;; Structure editing
7215 ;;; Inserting headlines
7217 (defun org-previous-line-empty-p ()
7218 (save-excursion
7219 (and (not (bobp))
7220 (or (beginning-of-line 0) t)
7221 (save-match-data
7222 (looking-at "[ \t]*$")))))
7224 (defun org-insert-heading (&optional force-heading invisible-ok)
7225 "Insert a new heading or item with same depth at point.
7226 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7227 If point is at the beginning of a headline, insert a sibling before the
7228 current headline. If point is not at the beginning, split the line,
7229 create the new headline with the text in the current line after point
7230 \(but see also the variable `org-M-RET-may-split-line').
7232 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7233 This is important for non-interactive uses of the command."
7234 (interactive "P")
7235 (if (or (= (buffer-size) 0)
7236 (and (not (save-excursion
7237 (and (ignore-errors (org-back-to-heading invisible-ok))
7238 (org-at-heading-p))))
7239 (or force-heading (not (org-in-item-p)))))
7240 (progn
7241 (insert "\n* ")
7242 (run-hooks 'org-insert-heading-hook))
7243 (when (or force-heading (not (org-insert-item)))
7244 (let* ((empty-line-p nil)
7245 (level nil)
7246 (on-heading (org-at-heading-p))
7247 (head (save-excursion
7248 (condition-case nil
7249 (progn
7250 (org-back-to-heading invisible-ok)
7251 (when (and (not on-heading)
7252 (featurep 'org-inlinetask)
7253 (integerp org-inlinetask-min-level)
7254 (>= (length (match-string 0))
7255 org-inlinetask-min-level))
7256 ;; Find a heading level before the inline task
7257 (while (and (setq level (org-up-heading-safe))
7258 (>= level org-inlinetask-min-level)))
7259 (if (org-at-heading-p)
7260 (org-back-to-heading invisible-ok)
7261 (error "This should not happen")))
7262 (setq empty-line-p (org-previous-line-empty-p))
7263 (match-string 0))
7264 (error "*"))))
7265 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7266 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7267 pos hide-previous previous-pos)
7268 (cond
7269 ((and (org-at-heading-p) (bolp)
7270 (or (bobp)
7271 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7272 ;; insert before the current line
7273 (open-line (if blank 2 1)))
7274 ((and (bolp)
7275 (not org-insert-heading-respect-content)
7276 (or (bobp)
7277 (save-excursion
7278 (backward-char 1) (not (outline-invisible-p)))))
7279 ;; insert right here
7280 nil)
7282 ;; somewhere in the line
7283 (save-excursion
7284 (setq previous-pos (point-at-bol))
7285 (end-of-line)
7286 (setq hide-previous (outline-invisible-p)))
7287 (and org-insert-heading-respect-content (org-show-subtree))
7288 (let ((split
7289 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7290 (save-excursion
7291 (let ((p (point)))
7292 (goto-char (point-at-bol))
7293 (and (looking-at org-complex-heading-regexp)
7294 (match-beginning 4)
7295 (> p (match-beginning 4)))))))
7296 tags pos)
7297 (cond
7298 (org-insert-heading-respect-content
7299 (org-end-of-subtree nil t)
7300 (when (featurep 'org-inlinetask)
7301 (while (and (not (eobp))
7302 (looking-at "\\(\\*+\\)[ \t]+")
7303 (>= (length (match-string 1))
7304 org-inlinetask-min-level))
7305 (org-end-of-subtree nil t)))
7306 (or (bolp) (newline))
7307 (or (org-previous-line-empty-p)
7308 (and blank (newline)))
7309 (open-line 1))
7310 ((org-at-heading-p)
7311 (when hide-previous
7312 (show-children)
7313 (org-show-entry))
7314 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7315 (setq tags (and (match-end 2) (match-string 2)))
7316 (and (match-end 1)
7317 (delete-region (match-beginning 1) (match-end 1)))
7318 (setq pos (point-at-bol))
7319 (or split (end-of-line 1))
7320 (delete-horizontal-space)
7321 (if (string-match "\\`\\*+\\'"
7322 (buffer-substring (point-at-bol) (point)))
7323 (insert " "))
7324 (newline (if blank 2 1))
7325 (when tags
7326 (save-excursion
7327 (goto-char pos)
7328 (end-of-line 1)
7329 (insert " " tags)
7330 (org-set-tags nil 'align))))
7332 (or split (end-of-line 1))
7333 (newline (if blank 2 1)))))))
7334 (insert head) (just-one-space)
7335 (setq pos (point))
7336 (end-of-line 1)
7337 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7338 (when (and org-insert-heading-respect-content hide-previous)
7339 (save-excursion
7340 (goto-char previous-pos)
7341 (hide-subtree)))
7342 (run-hooks 'org-insert-heading-hook)))))
7344 (defun org-get-heading (&optional no-tags no-todo)
7345 "Return the heading of the current entry, without the stars.
7346 When NO-TAGS is non-nil, don't include tags.
7347 When NO-TODO is non-nil, don't include TODO keywords."
7348 (save-excursion
7349 (org-back-to-heading t)
7350 (cond
7351 ((and no-tags no-todo)
7352 (looking-at org-complex-heading-regexp)
7353 (match-string 4))
7354 (no-tags
7355 (looking-at (concat org-outline-regexp
7356 "\\(.*?\\)"
7357 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7358 (match-string 1))
7359 (no-todo
7360 (looking-at org-todo-line-regexp)
7361 (match-string 3))
7362 (t (looking-at org-heading-regexp)
7363 (match-string 2)))))
7365 (defun org-heading-components ()
7366 "Return the components of the current heading.
7367 This is a list with the following elements:
7368 - the level as an integer
7369 - the reduced level, different if `org-odd-levels-only' is set.
7370 - the TODO keyword, or nil
7371 - the priority character, like ?A, or nil if no priority is given
7372 - the headline text itself, or the tags string if no headline text
7373 - the tags string, or nil."
7374 (save-excursion
7375 (org-back-to-heading t)
7376 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7377 (list (length (match-string 1))
7378 (org-reduced-level (length (match-string 1)))
7379 (org-match-string-no-properties 2)
7380 (and (match-end 3) (aref (match-string 3) 2))
7381 (org-match-string-no-properties 4)
7382 (org-match-string-no-properties 5)))))
7384 (defun org-get-entry ()
7385 "Get the entry text, after heading, entire subtree."
7386 (save-excursion
7387 (org-back-to-heading t)
7388 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7390 (defun org-insert-heading-after-current ()
7391 "Insert a new heading with same level as current, after current subtree."
7392 (interactive)
7393 (org-back-to-heading)
7394 (org-insert-heading)
7395 (org-move-subtree-down)
7396 (end-of-line 1))
7398 (defun org-insert-heading-respect-content ()
7399 (interactive)
7400 (let ((org-insert-heading-respect-content t))
7401 (org-insert-heading t)))
7403 (defun org-insert-todo-heading-respect-content (&optional force-state)
7404 (interactive "P")
7405 (let ((org-insert-heading-respect-content t))
7406 (org-insert-todo-heading force-state t)))
7408 (defun org-insert-todo-heading (arg &optional force-heading)
7409 "Insert a new heading with the same level and TODO state as current heading.
7410 If the heading has no TODO state, or if the state is DONE, use the first
7411 state (TODO by default). Also with prefix arg, force first state."
7412 (interactive "P")
7413 (when (or force-heading (not (org-insert-item 'checkbox)))
7414 (org-insert-heading force-heading)
7415 (save-excursion
7416 (org-back-to-heading)
7417 (outline-previous-heading)
7418 (looking-at org-todo-line-regexp))
7419 (let*
7420 ((new-mark-x
7421 (if (or arg
7422 (not (match-beginning 2))
7423 (member (match-string 2) org-done-keywords))
7424 (car org-todo-keywords-1)
7425 (match-string 2)))
7426 (new-mark
7428 (run-hook-with-args-until-success
7429 'org-todo-get-default-hook new-mark-x nil)
7430 new-mark-x)))
7431 (beginning-of-line 1)
7432 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7433 (if org-treat-insert-todo-heading-as-state-change
7434 (org-todo new-mark)
7435 (insert new-mark " "))))
7436 (when org-provide-todo-statistics
7437 (org-update-parent-todo-statistics))))
7439 (defun org-insert-subheading (arg)
7440 "Insert a new subheading and demote it.
7441 Works for outline headings and for plain lists alike."
7442 (interactive "P")
7443 (org-insert-heading arg)
7444 (cond
7445 ((org-at-heading-p) (org-do-demote))
7446 ((org-at-item-p) (org-indent-item))))
7448 (defun org-insert-todo-subheading (arg)
7449 "Insert a new subheading with TODO keyword or checkbox and demote it.
7450 Works for outline headings and for plain lists alike."
7451 (interactive "P")
7452 (org-insert-todo-heading arg)
7453 (cond
7454 ((org-at-heading-p) (org-do-demote))
7455 ((org-at-item-p) (org-indent-item))))
7457 ;;; Promotion and Demotion
7459 (defvar org-after-demote-entry-hook nil
7460 "Hook run after an entry has been demoted.
7461 The cursor will be at the beginning of the entry.
7462 When a subtree is being demoted, the hook will be called for each node.")
7464 (defvar org-after-promote-entry-hook nil
7465 "Hook run after an entry has been promoted.
7466 The cursor will be at the beginning of the entry.
7467 When a subtree is being promoted, the hook will be called for each node.")
7469 (defun org-promote-subtree ()
7470 "Promote the entire subtree.
7471 See also `org-promote'."
7472 (interactive)
7473 (save-excursion
7474 (org-with-limited-levels (org-map-tree 'org-promote)))
7475 (org-fix-position-after-promote))
7477 (defun org-demote-subtree ()
7478 "Demote the entire subtree. See `org-demote'.
7479 See also `org-promote'."
7480 (interactive)
7481 (save-excursion
7482 (org-with-limited-levels (org-map-tree 'org-demote)))
7483 (org-fix-position-after-promote))
7486 (defun org-do-promote ()
7487 "Promote the current heading higher up the tree.
7488 If the region is active in `transient-mark-mode', promote all headings
7489 in the region."
7490 (interactive)
7491 (save-excursion
7492 (if (org-region-active-p)
7493 (org-map-region 'org-promote (region-beginning) (region-end))
7494 (org-promote)))
7495 (org-fix-position-after-promote))
7497 (defun org-do-demote ()
7498 "Demote the current heading lower down the tree.
7499 If the region is active in `transient-mark-mode', demote all headings
7500 in the region."
7501 (interactive)
7502 (save-excursion
7503 (if (org-region-active-p)
7504 (org-map-region 'org-demote (region-beginning) (region-end))
7505 (org-demote)))
7506 (org-fix-position-after-promote))
7508 (defun org-fix-position-after-promote ()
7509 "Make sure that after pro/demotion cursor position is right."
7510 (let ((pos (point)))
7511 (when (save-excursion
7512 (beginning-of-line 1)
7513 (looking-at org-todo-line-regexp)
7514 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7515 (cond ((eobp) (insert " "))
7516 ((eolp) (insert " "))
7517 ((equal (char-after) ?\ ) (forward-char 1))))))
7519 (defun org-current-level ()
7520 "Return the level of the current entry, or nil if before the first headline.
7521 The level is the number of stars at the beginning of the headline."
7522 (save-excursion
7523 (org-with-limited-levels
7524 (if (ignore-errors (org-back-to-heading t))
7525 (funcall outline-level)))))
7527 (defun org-get-previous-line-level ()
7528 "Return the outline depth of the last headline before the current line.
7529 Returns 0 for the first headline in the buffer, and nil if before the
7530 first headline."
7531 (let ((current-level (org-current-level))
7532 (prev-level (when (> (line-number-at-pos) 1)
7533 (save-excursion
7534 (beginning-of-line 0)
7535 (org-current-level)))))
7536 (cond ((null current-level) nil) ; Before first headline
7537 ((null prev-level) 0) ; At first headline
7538 (prev-level))))
7540 (defun org-reduced-level (l)
7541 "Compute the effective level of a heading.
7542 This takes into account the setting of `org-odd-levels-only'."
7543 (cond
7544 ((zerop l) 0)
7545 (org-odd-levels-only (1+ (floor (/ l 2))))
7546 (t l)))
7548 (defun org-level-increment ()
7549 "Return the number of stars that will be added or removed at a
7550 time to headlines when structure editing, based on the value of
7551 `org-odd-levels-only'."
7552 (if org-odd-levels-only 2 1))
7554 (defun org-get-valid-level (level &optional change)
7555 "Rectify a level change under the influence of `org-odd-levels-only'
7556 LEVEL is a current level, CHANGE is by how much the level should be
7557 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7558 even level numbers will become the next higher odd number."
7559 (if org-odd-levels-only
7560 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7561 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7562 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7563 (max 1 (+ level (or change 0)))))
7565 (if (boundp 'define-obsolete-function-alias)
7566 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7567 (define-obsolete-function-alias 'org-get-legal-level
7568 'org-get-valid-level)
7569 (define-obsolete-function-alias 'org-get-legal-level
7570 'org-get-valid-level "23.1")))
7572 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7573 ;; ̀org-with-limited-levels'
7574 (defun org-promote ()
7575 "Promote the current heading higher up the tree.
7576 If the region is active in `transient-mark-mode', promote all headings
7577 in the region."
7578 (org-back-to-heading t)
7579 (let* ((level (save-match-data (funcall outline-level)))
7580 (after-change-functions (remove 'flyspell-after-change-function
7581 after-change-functions))
7582 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7583 (diff (abs (- level (length up-head) -1))))
7584 (cond ((and (= level 1) org-called-with-limited-levels
7585 org-allow-promoting-top-level-subtree)
7586 (replace-match "# " nil t))
7587 ((= level 1)
7588 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7589 (t (replace-match up-head nil t)))
7590 ;; Fixup tag positioning
7591 (unless (= level 1)
7592 (and org-auto-align-tags (org-set-tags nil t))
7593 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7594 (run-hooks 'org-after-promote-entry-hook)))
7596 (defun org-demote ()
7597 "Demote the current heading lower down the tree.
7598 If the region is active in `transient-mark-mode', demote all headings
7599 in the region."
7600 (org-back-to-heading t)
7601 (let* ((level (save-match-data (funcall outline-level)))
7602 (after-change-functions (remove 'flyspell-after-change-function
7603 after-change-functions))
7604 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7605 (diff (abs (- level (length down-head) -1))))
7606 (replace-match down-head nil t)
7607 ;; Fixup tag positioning
7608 (and org-auto-align-tags (org-set-tags nil t))
7609 (if org-adapt-indentation (org-fixup-indentation diff))
7610 (run-hooks 'org-after-demote-entry-hook)))
7612 (defun org-cycle-level ()
7613 "Cycle the level of an empty headline through possible states.
7614 This goes first to child, then to parent, level, then up the hierarchy.
7615 After top level, it switches back to sibling level."
7616 (interactive)
7617 (let ((org-adapt-indentation nil))
7618 (when (org-point-at-end-of-empty-headline)
7619 (setq this-command 'org-cycle-level) ; Only needed for caching
7620 (let ((cur-level (org-current-level))
7621 (prev-level (org-get-previous-line-level)))
7622 (cond
7623 ;; If first headline in file, promote to top-level.
7624 ((= prev-level 0)
7625 (loop repeat (/ (- cur-level 1) (org-level-increment))
7626 do (org-do-promote)))
7627 ;; If same level as prev, demote one.
7628 ((= prev-level cur-level)
7629 (org-do-demote))
7630 ;; If parent is top-level, promote to top level if not already.
7631 ((= prev-level 1)
7632 (loop repeat (/ (- cur-level 1) (org-level-increment))
7633 do (org-do-promote)))
7634 ;; If top-level, return to prev-level.
7635 ((= cur-level 1)
7636 (loop repeat (/ (- prev-level 1) (org-level-increment))
7637 do (org-do-demote)))
7638 ;; If less than prev-level, promote one.
7639 ((< cur-level prev-level)
7640 (org-do-promote))
7641 ;; If deeper than prev-level, promote until higher than
7642 ;; prev-level.
7643 ((> cur-level prev-level)
7644 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7645 do (org-do-promote))))
7646 t))))
7648 (defun org-map-tree (fun)
7649 "Call FUN for every heading underneath the current one."
7650 (org-back-to-heading)
7651 (let ((level (funcall outline-level)))
7652 (save-excursion
7653 (funcall fun)
7654 (while (and (progn
7655 (outline-next-heading)
7656 (> (funcall outline-level) level))
7657 (not (eobp)))
7658 (funcall fun)))))
7660 (defun org-map-region (fun beg end)
7661 "Call FUN for every heading between BEG and END."
7662 (let ((org-ignore-region t))
7663 (save-excursion
7664 (setq end (copy-marker end))
7665 (goto-char beg)
7666 (if (and (re-search-forward org-outline-regexp-bol nil t)
7667 (< (point) end))
7668 (funcall fun))
7669 (while (and (progn
7670 (outline-next-heading)
7671 (< (point) end))
7672 (not (eobp)))
7673 (funcall fun)))))
7675 (defvar org-property-end-re) ; silence byte-compiler
7676 (defun org-fixup-indentation (diff)
7677 "Change the indentation in the current entry by DIFF.
7678 However, if any line in the current entry has no indentation, or if it
7679 would end up with no indentation after the change, nothing at all is done."
7680 (save-excursion
7681 (let ((end (save-excursion (outline-next-heading)
7682 (point-marker)))
7683 (prohibit (if (> diff 0)
7684 "^\\S-"
7685 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7686 col)
7687 (unless (save-excursion (end-of-line 1)
7688 (re-search-forward prohibit end t))
7689 (while (and (< (point) end)
7690 (re-search-forward "^[ \t]+" end t))
7691 (goto-char (match-end 0))
7692 (setq col (current-column))
7693 (if (< diff 0) (replace-match ""))
7694 (org-indent-to-column (+ diff col))))
7695 (move-marker end nil))))
7697 (defun org-convert-to-odd-levels ()
7698 "Convert an org-mode file with all levels allowed to one with odd levels.
7699 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7700 level 5 etc."
7701 (interactive)
7702 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7703 (let ((outline-level 'org-outline-level)
7704 (org-odd-levels-only nil) n)
7705 (save-excursion
7706 (goto-char (point-min))
7707 (while (re-search-forward "^\\*\\*+ " nil t)
7708 (setq n (- (length (match-string 0)) 2))
7709 (while (>= (setq n (1- n)) 0)
7710 (org-demote))
7711 (end-of-line 1))))))
7713 (defun org-convert-to-oddeven-levels ()
7714 "Convert an org-mode file with only odd levels to one with odd/even levels.
7715 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7716 file contains a section with an even level, conversion would
7717 destroy the structure of the file. An error is signaled in this
7718 case."
7719 (interactive)
7720 (goto-char (point-min))
7721 ;; First check if there are no even levels
7722 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7723 (org-show-context t)
7724 (error "Not all levels are odd in this file. Conversion not possible"))
7725 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7726 (let ((outline-regexp org-outline-regexp)
7727 (outline-level 'org-outline-level)
7728 (org-odd-levels-only nil) n)
7729 (save-excursion
7730 (goto-char (point-min))
7731 (while (re-search-forward "^\\*\\*+ " nil t)
7732 (setq n (/ (1- (length (match-string 0))) 2))
7733 (while (>= (setq n (1- n)) 0)
7734 (org-promote))
7735 (end-of-line 1))))))
7737 (defun org-tr-level (n)
7738 "Make N odd if required."
7739 (if org-odd-levels-only (1+ (/ n 2)) n))
7741 ;;; Vertical tree motion, cutting and pasting of subtrees
7743 (defun org-move-subtree-up (&optional arg)
7744 "Move the current subtree up past ARG headlines of the same level."
7745 (interactive "p")
7746 (org-move-subtree-down (- (prefix-numeric-value arg))))
7748 (defun org-move-subtree-down (&optional arg)
7749 "Move the current subtree down past ARG headlines of the same level."
7750 (interactive "p")
7751 (setq arg (prefix-numeric-value arg))
7752 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7753 'org-get-last-sibling))
7754 (ins-point (make-marker))
7755 (cnt (abs arg))
7756 (col (current-column))
7757 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7758 ;; Select the tree
7759 (org-back-to-heading)
7760 (setq beg0 (point))
7761 (save-excursion
7762 (setq ne-beg (org-back-over-empty-lines))
7763 (setq beg (point)))
7764 (save-match-data
7765 (save-excursion (outline-end-of-heading)
7766 (setq folded (outline-invisible-p)))
7767 (outline-end-of-subtree))
7768 (outline-next-heading)
7769 (setq ne-end (org-back-over-empty-lines))
7770 (setq end (point))
7771 (goto-char beg0)
7772 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7773 ;; include less whitespace
7774 (save-excursion
7775 (goto-char beg)
7776 (forward-line (- ne-beg ne-end))
7777 (setq beg (point))))
7778 ;; Find insertion point, with error handling
7779 (while (> cnt 0)
7780 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7781 (progn (goto-char beg0)
7782 (error "Cannot move past superior level or buffer limit")))
7783 (setq cnt (1- cnt)))
7784 (if (> arg 0)
7785 ;; Moving forward - still need to move over subtree
7786 (progn (org-end-of-subtree t t)
7787 (save-excursion
7788 (org-back-over-empty-lines)
7789 (or (bolp) (newline)))))
7790 (setq ne-ins (org-back-over-empty-lines))
7791 (move-marker ins-point (point))
7792 (setq txt (buffer-substring beg end))
7793 (org-save-markers-in-region beg end)
7794 (delete-region beg end)
7795 (org-remove-empty-overlays-at beg)
7796 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7797 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7798 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7799 (let ((bbb (point)))
7800 (insert-before-markers txt)
7801 (org-reinstall-markers-in-region bbb)
7802 (move-marker ins-point bbb))
7803 (or (bolp) (insert "\n"))
7804 (setq ins-end (point))
7805 (goto-char ins-point)
7806 (org-skip-whitespace)
7807 (when (and (< arg 0)
7808 (org-first-sibling-p)
7809 (> ne-ins ne-beg))
7810 ;; Move whitespace back to beginning
7811 (save-excursion
7812 (goto-char ins-end)
7813 (let ((kill-whole-line t))
7814 (kill-line (- ne-ins ne-beg)) (point)))
7815 (insert (make-string (- ne-ins ne-beg) ?\n)))
7816 (move-marker ins-point nil)
7817 (if folded
7818 (hide-subtree)
7819 (org-show-entry)
7820 (show-children)
7821 (org-cycle-hide-drawers 'children))
7822 (org-clean-visibility-after-subtree-move)
7823 ;; move back to the initial column we were at
7824 (move-to-column col)))
7826 (defvar org-subtree-clip ""
7827 "Clipboard for cut and paste of subtrees.
7828 This is actually only a copy of the kill, because we use the normal kill
7829 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7831 (defvar org-subtree-clip-folded nil
7832 "Was the last copied subtree folded?
7833 This is used to fold the tree back after pasting.")
7835 (defun org-cut-subtree (&optional n)
7836 "Cut the current subtree into the clipboard.
7837 With prefix arg N, cut this many sequential subtrees.
7838 This is a short-hand for marking the subtree and then cutting it."
7839 (interactive "p")
7840 (org-copy-subtree n 'cut))
7842 (defun org-copy-subtree (&optional n cut force-store-markers)
7843 "Cut the current subtree into the clipboard.
7844 With prefix arg N, cut this many sequential subtrees.
7845 This is a short-hand for marking the subtree and then copying it.
7846 If CUT is non-nil, actually cut the subtree.
7847 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7848 of some markers in the region, even if CUT is non-nil. This is
7849 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7850 (interactive "p")
7851 (let (beg end folded (beg0 (point)))
7852 (if (org-called-interactively-p 'any)
7853 (org-back-to-heading nil) ; take what looks like a subtree
7854 (org-back-to-heading t)) ; take what is really there
7855 (org-back-over-empty-lines)
7856 (setq beg (point))
7857 (skip-chars-forward " \t\r\n")
7858 (save-match-data
7859 (save-excursion (outline-end-of-heading)
7860 (setq folded (outline-invisible-p)))
7861 (condition-case nil
7862 (org-forward-heading-same-level (1- n) t)
7863 (error nil))
7864 (org-end-of-subtree t t))
7865 (org-back-over-empty-lines)
7866 (setq end (point))
7867 (goto-char beg0)
7868 (when (> end beg)
7869 (setq org-subtree-clip-folded folded)
7870 (when (or cut force-store-markers)
7871 (org-save-markers-in-region beg end))
7872 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7873 (setq org-subtree-clip (current-kill 0))
7874 (message "%s: Subtree(s) with %d characters"
7875 (if cut "Cut" "Copied")
7876 (length org-subtree-clip)))))
7878 (defun org-paste-subtree (&optional level tree for-yank)
7879 "Paste the clipboard as a subtree, with modification of headline level.
7880 The entire subtree is promoted or demoted in order to match a new headline
7881 level.
7883 If the cursor is at the beginning of a headline, the same level as
7884 that headline is used to paste the tree
7886 If not, the new level is derived from the *visible* headings
7887 before and after the insertion point, and taken to be the inferior headline
7888 level of the two. So if the previous visible heading is level 3 and the
7889 next is level 4 (or vice versa), level 4 will be used for insertion.
7890 This makes sure that the subtree remains an independent subtree and does
7891 not swallow low level entries.
7893 You can also force a different level, either by using a numeric prefix
7894 argument, or by inserting the heading marker by hand. For example, if the
7895 cursor is after \"*****\", then the tree will be shifted to level 5.
7897 If optional TREE is given, use this text instead of the kill ring.
7899 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7900 move back over whitespace before inserting, and move point to the end of
7901 the inserted text when done."
7902 (interactive "P")
7903 (setq tree (or tree (and kill-ring (current-kill 0))))
7904 (unless (org-kill-is-subtree-p tree)
7905 (error "%s"
7906 (substitute-command-keys
7907 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7908 (org-with-limited-levels
7909 (let* ((visp (not (outline-invisible-p)))
7910 (txt tree)
7911 (^re_ "\\(\\*+\\)[ \t]*")
7912 (old-level (if (string-match org-outline-regexp-bol txt)
7913 (- (match-end 0) (match-beginning 0) 1)
7914 -1))
7915 (force-level (cond (level (prefix-numeric-value level))
7916 ((and (looking-at "[ \t]*$")
7917 (string-match
7918 "^\\*+$" (buffer-substring
7919 (point-at-bol) (point))))
7920 (- (match-end 1) (match-beginning 1)))
7921 ((and (bolp)
7922 (looking-at org-outline-regexp))
7923 (- (match-end 0) (point) 1))))
7924 (previous-level (save-excursion
7925 (condition-case nil
7926 (progn
7927 (outline-previous-visible-heading 1)
7928 (if (looking-at ^re_)
7929 (- (match-end 0) (match-beginning 0) 1)
7931 (error 1))))
7932 (next-level (save-excursion
7933 (condition-case nil
7934 (progn
7935 (or (looking-at org-outline-regexp)
7936 (outline-next-visible-heading 1))
7937 (if (looking-at ^re_)
7938 (- (match-end 0) (match-beginning 0) 1)
7940 (error 1))))
7941 (new-level (or force-level (max previous-level next-level)))
7942 (shift (if (or (= old-level -1)
7943 (= new-level -1)
7944 (= old-level new-level))
7946 (- new-level old-level)))
7947 (delta (if (> shift 0) -1 1))
7948 (func (if (> shift 0) 'org-demote 'org-promote))
7949 (org-odd-levels-only nil)
7950 beg end newend)
7951 ;; Remove the forced level indicator
7952 (if force-level
7953 (delete-region (point-at-bol) (point)))
7954 ;; Paste
7955 (beginning-of-line (if (bolp) 1 2))
7956 (unless for-yank (org-back-over-empty-lines))
7957 (setq beg (point))
7958 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7959 (insert-before-markers txt)
7960 (unless (string-match "\n\\'" txt) (insert "\n"))
7961 (setq newend (point))
7962 (org-reinstall-markers-in-region beg)
7963 (setq end (point))
7964 (goto-char beg)
7965 (skip-chars-forward " \t\n\r")
7966 (setq beg (point))
7967 (if (and (outline-invisible-p) visp)
7968 (save-excursion (outline-show-heading)))
7969 ;; Shift if necessary
7970 (unless (= shift 0)
7971 (save-restriction
7972 (narrow-to-region beg end)
7973 (while (not (= shift 0))
7974 (org-map-region func (point-min) (point-max))
7975 (setq shift (+ delta shift)))
7976 (goto-char (point-min))
7977 (setq newend (point-max))))
7978 (when (or (org-called-interactively-p 'interactive) for-yank)
7979 (message "Clipboard pasted as level %d subtree" new-level))
7980 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7981 kill-ring
7982 (eq org-subtree-clip (current-kill 0))
7983 org-subtree-clip-folded)
7984 ;; The tree was folded before it was killed/copied
7985 (hide-subtree))
7986 (and for-yank (goto-char newend)))))
7988 (defun org-kill-is-subtree-p (&optional txt)
7989 "Check if the current kill is an outline subtree, or a set of trees.
7990 Returns nil if kill does not start with a headline, or if the first
7991 headline level is not the largest headline level in the tree.
7992 So this will actually accept several entries of equal levels as well,
7993 which is OK for `org-paste-subtree'.
7994 If optional TXT is given, check this string instead of the current kill."
7995 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7996 (re (org-get-limited-outline-regexp))
7997 (^re (concat "^" re))
7998 (start-level (and kill
7999 (string-match
8000 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8001 kill)
8002 (- (match-end 2) (match-beginning 2) 1)))
8003 (start (1+ (or (match-beginning 2) -1))))
8004 (if (not start-level)
8005 (progn
8006 nil) ;; does not even start with a heading
8007 (catch 'exit
8008 (while (setq start (string-match ^re kill (1+ start)))
8009 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8010 (throw 'exit nil)))
8011 t))))
8013 (defvar org-markers-to-move nil
8014 "Markers that should be moved with a cut-and-paste operation.
8015 Those markers are stored together with their positions relative to
8016 the start of the region.")
8018 (defun org-save-markers-in-region (beg end)
8019 "Check markers in region.
8020 If these markers are between BEG and END, record their position relative
8021 to BEG, so that after moving the block of text, we can put the markers back
8022 into place.
8023 This function gets called just before an entry or tree gets cut from the
8024 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8025 called immediately, to move the markers with the entries."
8026 (setq org-markers-to-move nil)
8027 (when (featurep 'org-clock)
8028 (org-clock-save-markers-for-cut-and-paste beg end))
8029 (when (featurep 'org-agenda)
8030 (org-agenda-save-markers-for-cut-and-paste beg end)))
8032 (defun org-check-and-save-marker (marker beg end)
8033 "Check if MARKER is between BEG and END.
8034 If yes, remember the marker and the distance to BEG."
8035 (when (and (marker-buffer marker)
8036 (equal (marker-buffer marker) (current-buffer)))
8037 (if (and (>= marker beg) (< marker end))
8038 (push (cons marker (- marker beg)) org-markers-to-move))))
8040 (defun org-reinstall-markers-in-region (beg)
8041 "Move all remembered markers to their position relative to BEG."
8042 (mapc (lambda (x)
8043 (move-marker (car x) (+ beg (cdr x))))
8044 org-markers-to-move)
8045 (setq org-markers-to-move nil))
8047 (defun org-narrow-to-subtree ()
8048 "Narrow buffer to the current subtree."
8049 (interactive)
8050 (save-excursion
8051 (save-match-data
8052 (org-with-limited-levels
8053 (narrow-to-region
8054 (progn (org-back-to-heading t) (point))
8055 (progn (org-end-of-subtree t t)
8056 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8057 (point)))))))
8059 (defun org-narrow-to-block ()
8060 "Narrow buffer to the current block."
8061 (interactive)
8062 (let* ((case-fold-search t)
8063 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8064 "^[ \t]*#\\+end_.*")))
8065 (if blockp
8066 (narrow-to-region (car blockp) (cdr blockp))
8067 (error "Not in a block"))))
8069 (eval-when-compile
8070 (defvar org-property-drawer-re))
8072 (defvar org-property-start-re) ;; defined below
8073 (defun org-clone-subtree-with-time-shift (n &optional shift)
8074 "Clone the task (subtree) at point N times.
8075 The clones will be inserted as siblings.
8077 In interactive use, the user will be prompted for the number of
8078 clones to be produced, and for a time SHIFT, which may be a
8079 repeater as used in time stamps, for example `+3d'.
8081 When a valid repeater is given and the entry contains any time
8082 stamps, the clones will become a sequence in time, with time
8083 stamps in the subtree shifted for each clone produced. If SHIFT
8084 is nil or the empty string, time stamps will be left alone. The
8085 ID property of the original subtree is removed.
8087 If the original subtree did contain time stamps with a repeater,
8088 the following will happen:
8089 - the repeater will be removed in each clone
8090 - an additional clone will be produced, with the current, unshifted
8091 date(s) in the entry.
8092 - the original entry will be placed *after* all the clones, with
8093 repeater intact.
8094 - the start days in the repeater in the original entry will be shifted
8095 to past the last clone.
8096 In this way you can spell out a number of instances of a repeating task,
8097 and still retain the repeater to cover future instances of the task."
8098 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8099 (let (beg end template task idprop
8100 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8101 (drawer-re org-drawer-regexp))
8102 (if (not (and (integerp n) (> n 0)))
8103 (error "Invalid number of replications %s" n))
8104 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8105 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8106 shift)))
8107 (error "Invalid shift specification %s" shift))
8108 (when doshift
8109 (setq shift-n (string-to-number (match-string 1 shift))
8110 shift-what (cdr (assoc (match-string 2 shift)
8111 '(("d" . day) ("w" . week)
8112 ("m" . month) ("y" . year))))))
8113 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8114 (setq nmin 1 nmax n)
8115 (org-back-to-heading t)
8116 (setq beg (point))
8117 (setq idprop (org-entry-get nil "ID"))
8118 (org-end-of-subtree t t)
8119 (or (bolp) (insert "\n"))
8120 (setq end (point))
8121 (setq template (buffer-substring beg end))
8122 (when (and doshift
8123 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8124 (delete-region beg end)
8125 (setq end beg)
8126 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8127 (goto-char end)
8128 (loop for n from nmin to nmax do
8129 ;; prepare clone
8130 (with-temp-buffer
8131 (insert template)
8132 (org-mode)
8133 (goto-char (point-min))
8134 (org-show-subtree)
8135 (and idprop (if org-clone-delete-id
8136 (org-entry-delete nil "ID")
8137 (org-id-get-create t)))
8138 (unless (= n 0)
8139 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8140 (kill-whole-line))
8141 (goto-char (point-min))
8142 (while (re-search-forward drawer-re nil t)
8143 (mapc (lambda (d)
8144 (org-remove-empty-drawer-at d (point))) org-drawers)))
8145 (goto-char (point-min))
8146 (when doshift
8147 (while (re-search-forward org-ts-regexp-both nil t)
8148 (org-timestamp-change (* n shift-n) shift-what))
8149 (unless (= n n-no-remove)
8150 (goto-char (point-min))
8151 (while (re-search-forward org-ts-regexp nil t)
8152 (save-excursion
8153 (goto-char (match-beginning 0))
8154 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8155 (delete-region (match-beginning 1) (match-end 1)))))))
8156 (setq task (buffer-string)))
8157 (insert task))
8158 (goto-char beg)))
8160 ;;; Outline Sorting
8162 (defun org-sort (with-case)
8163 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8164 Optional argument WITH-CASE means sort case-sensitively."
8165 (interactive "P")
8166 (cond
8167 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8168 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8170 (org-call-with-arg 'org-sort-entries with-case))))
8172 (defun org-sort-remove-invisible (s)
8173 (remove-text-properties 0 (length s) org-rm-props s)
8174 (while (string-match org-bracket-link-regexp s)
8175 (setq s (replace-match (if (match-end 2)
8176 (match-string 3 s)
8177 (match-string 1 s)) t t s)))
8180 (defvar org-priority-regexp) ; defined later in the file
8182 (defvar org-after-sorting-entries-or-items-hook nil
8183 "Hook that is run after a bunch of entries or items have been sorted.
8184 When children are sorted, the cursor is in the parent line when this
8185 hook gets called. When a region or a plain list is sorted, the cursor
8186 will be in the first entry of the sorted region/list.")
8188 (defun org-sort-entries
8189 (&optional with-case sorting-type getkey-func compare-func property)
8190 "Sort entries on a certain level of an outline tree.
8191 If there is an active region, the entries in the region are sorted.
8192 Else, if the cursor is before the first entry, sort the top-level items.
8193 Else, the children of the entry at point are sorted.
8195 Sorting can be alphabetically, numerically, by date/time as given by
8196 a time stamp, by a property or by priority.
8198 The command prompts for the sorting type unless it has been given to the
8199 function through the SORTING-TYPE argument, which needs to be a character,
8200 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8201 precise meaning of each character:
8203 n Numerically, by converting the beginning of the entry/item to a number.
8204 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8205 t By date/time, either the first active time stamp in the entry, or, if
8206 none exist, by the first inactive one.
8207 s By the scheduled date/time.
8208 d By deadline date/time.
8209 c By creation time, which is assumed to be the first inactive time stamp
8210 at the beginning of a line.
8211 p By priority according to the cookie.
8212 r By the value of a property.
8214 Capital letters will reverse the sort order.
8216 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8217 called with point at the beginning of the record. It must return either
8218 a string or a number that should serve as the sorting key for that record.
8220 Comparing entries ignores case by default. However, with an optional argument
8221 WITH-CASE, the sorting considers case as well."
8222 (interactive "P")
8223 (let ((case-func (if with-case 'identity 'downcase))
8224 start beg end stars re re2
8225 txt what tmp)
8226 ;; Find beginning and end of region to sort
8227 (cond
8228 ((org-region-active-p)
8229 ;; we will sort the region
8230 (setq end (region-end)
8231 what "region")
8232 (goto-char (region-beginning))
8233 (if (not (org-at-heading-p)) (outline-next-heading))
8234 (setq start (point)))
8235 ((or (org-at-heading-p)
8236 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8237 ;; we will sort the children of the current headline
8238 (org-back-to-heading)
8239 (setq start (point)
8240 end (progn (org-end-of-subtree t t)
8241 (or (bolp) (insert "\n"))
8242 (org-back-over-empty-lines)
8243 (point))
8244 what "children")
8245 (goto-char start)
8246 (show-subtree)
8247 (outline-next-heading))
8249 ;; we will sort the top-level entries in this file
8250 (goto-char (point-min))
8251 (or (org-at-heading-p) (outline-next-heading))
8252 (setq start (point))
8253 (goto-char (point-max))
8254 (beginning-of-line 1)
8255 (when (looking-at ".*?\\S-")
8256 ;; File ends in a non-white line
8257 (end-of-line 1)
8258 (insert "\n"))
8259 (setq end (point-max))
8260 (setq what "top-level")
8261 (goto-char start)
8262 (show-all)))
8264 (setq beg (point))
8265 (if (>= beg end) (error "Nothing to sort"))
8267 (looking-at "\\(\\*+\\)")
8268 (setq stars (match-string 1)
8269 re (concat "^" (regexp-quote stars) " +")
8270 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8271 txt (buffer-substring beg end))
8272 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8273 (if (and (not (equal stars "*")) (string-match re2 txt))
8274 (error "Region to sort contains a level above the first entry"))
8276 (unless sorting-type
8277 (message
8278 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8279 [t]ime [s]cheduled [d]eadline [c]reated
8280 A/N/T/S/D/C/P/O/F means reversed:"
8281 what)
8282 (setq sorting-type (read-char-exclusive))
8284 (and (= (downcase sorting-type) ?f)
8285 (setq getkey-func
8286 (org-icompleting-read "Sort using function: "
8287 obarray 'fboundp t nil nil))
8288 (setq getkey-func (intern getkey-func)))
8290 (and (= (downcase sorting-type) ?r)
8291 (setq property
8292 (org-icompleting-read "Property: "
8293 (mapcar 'list (org-buffer-property-keys t))
8294 nil t))))
8296 (message "Sorting entries...")
8298 (save-restriction
8299 (narrow-to-region start end)
8300 (let ((dcst (downcase sorting-type))
8301 (case-fold-search nil)
8302 (now (current-time)))
8303 (sort-subr
8304 (/= dcst sorting-type)
8305 ;; This function moves to the beginning character of the "record" to
8306 ;; be sorted.
8307 (lambda nil
8308 (if (re-search-forward re nil t)
8309 (goto-char (match-beginning 0))
8310 (goto-char (point-max))))
8311 ;; This function moves to the last character of the "record" being
8312 ;; sorted.
8313 (lambda nil
8314 (save-match-data
8315 (condition-case nil
8316 (outline-forward-same-level 1)
8317 (error
8318 (goto-char (point-max))))))
8319 ;; This function returns the value that gets sorted against.
8320 (lambda nil
8321 (cond
8322 ((= dcst ?n)
8323 (if (looking-at org-complex-heading-regexp)
8324 (string-to-number (match-string 4))
8325 nil))
8326 ((= dcst ?a)
8327 (if (looking-at org-complex-heading-regexp)
8328 (funcall case-func (match-string 4))
8329 nil))
8330 ((= dcst ?t)
8331 (let ((end (save-excursion (outline-next-heading) (point))))
8332 (if (or (re-search-forward org-ts-regexp end t)
8333 (re-search-forward org-ts-regexp-both end t))
8334 (org-time-string-to-seconds (match-string 0))
8335 (org-float-time now))))
8336 ((= dcst ?c)
8337 (let ((end (save-excursion (outline-next-heading) (point))))
8338 (if (re-search-forward
8339 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8340 end t)
8341 (org-time-string-to-seconds (match-string 0))
8342 (org-float-time now))))
8343 ((= dcst ?s)
8344 (let ((end (save-excursion (outline-next-heading) (point))))
8345 (if (re-search-forward org-scheduled-time-regexp end t)
8346 (org-time-string-to-seconds (match-string 1))
8347 (org-float-time now))))
8348 ((= dcst ?d)
8349 (let ((end (save-excursion (outline-next-heading) (point))))
8350 (if (re-search-forward org-deadline-time-regexp end t)
8351 (org-time-string-to-seconds (match-string 1))
8352 (org-float-time now))))
8353 ((= dcst ?p)
8354 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8355 (string-to-char (match-string 2))
8356 org-default-priority))
8357 ((= dcst ?r)
8358 (or (org-entry-get nil property) ""))
8359 ((= dcst ?o)
8360 (if (looking-at org-complex-heading-regexp)
8361 (- 9999 (length (member (match-string 2)
8362 org-todo-keywords-1)))))
8363 ((= dcst ?f)
8364 (if getkey-func
8365 (progn
8366 (setq tmp (funcall getkey-func))
8367 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8368 tmp)
8369 (error "Invalid key function `%s'" getkey-func)))
8370 (t (error "Invalid sorting type `%c'" sorting-type))))
8372 (cond
8373 ((= dcst ?a) 'string<)
8374 ((= dcst ?f) compare-func)
8375 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8376 (run-hooks 'org-after-sorting-entries-or-items-hook)
8377 (message "Sorting entries...done")))
8379 (defun org-do-sort (table what &optional with-case sorting-type)
8380 "Sort TABLE of WHAT according to SORTING-TYPE.
8381 The user will be prompted for the SORTING-TYPE if the call to this
8382 function does not specify it. WHAT is only for the prompt, to indicate
8383 what is being sorted. The sorting key will be extracted from
8384 the car of the elements of the table.
8385 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8386 (unless sorting-type
8387 (message
8388 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8389 what)
8390 (setq sorting-type (read-char-exclusive)))
8391 (let ((dcst (downcase sorting-type))
8392 extractfun comparefun)
8393 ;; Define the appropriate functions
8394 (cond
8395 ((= dcst ?n)
8396 (setq extractfun 'string-to-number
8397 comparefun (if (= dcst sorting-type) '< '>)))
8398 ((= dcst ?a)
8399 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8400 (lambda(x) (downcase (org-sort-remove-invisible x))))
8401 comparefun (if (= dcst sorting-type)
8402 'string<
8403 (lambda (a b) (and (not (string< a b))
8404 (not (string= a b)))))))
8405 ((= dcst ?t)
8406 (setq extractfun
8407 (lambda (x)
8408 (if (or (string-match org-ts-regexp x)
8409 (string-match org-ts-regexp-both x))
8410 (org-float-time
8411 (org-time-string-to-time (match-string 0 x)))
8413 comparefun (if (= dcst sorting-type) '< '>)))
8414 (t (error "Invalid sorting type `%c'" sorting-type)))
8416 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8417 table)
8418 (lambda (a b) (funcall comparefun (car a) (car b))))))
8421 ;;; The orgstruct minor mode
8423 ;; Define a minor mode which can be used in other modes in order to
8424 ;; integrate the org-mode structure editing commands.
8426 ;; This is really a hack, because the org-mode structure commands use
8427 ;; keys which normally belong to the major mode. Here is how it
8428 ;; works: The minor mode defines all the keys necessary to operate the
8429 ;; structure commands, but wraps the commands into a function which
8430 ;; tests if the cursor is currently at a headline or a plain list
8431 ;; item. If that is the case, the structure command is used,
8432 ;; temporarily setting many Org-mode variables like regular
8433 ;; expressions for filling etc. However, when any of those keys is
8434 ;; used at a different location, function uses `key-binding' to look
8435 ;; up if the key has an associated command in another currently active
8436 ;; keymap (minor modes, major mode, global), and executes that
8437 ;; command. There might be problems if any of the keys is otherwise
8438 ;; used as a prefix key.
8440 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8441 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8442 ;; addresses this by checking explicitly for both bindings.
8444 (defvar orgstruct-mode-map (make-sparse-keymap)
8445 "Keymap for the minor `orgstruct-mode'.")
8447 (defvar org-local-vars nil
8448 "List of local variables, for use by `orgstruct-mode'.")
8450 ;;;###autoload
8451 (define-minor-mode orgstruct-mode
8452 "Toggle the minor mode `orgstruct-mode'.
8453 This mode is for using Org-mode structure commands in other
8454 modes. The following keys behave as if Org-mode were active, if
8455 the cursor is on a headline, or on a plain list item (both as
8456 defined by Org-mode).
8458 M-up Move entry/item up
8459 M-down Move entry/item down
8460 M-left Promote
8461 M-right Demote
8462 M-S-up Move entry/item up
8463 M-S-down Move entry/item down
8464 M-S-left Promote subtree
8465 M-S-right Demote subtree
8466 M-q Fill paragraph and items like in Org-mode
8467 C-c ^ Sort entries
8468 C-c - Cycle list bullet
8469 TAB Cycle item visibility
8470 M-RET Insert new heading/item
8471 S-M-RET Insert new TODO heading / Checkbox item
8472 C-c C-c Set tags / toggle checkbox"
8473 nil " OrgStruct" nil
8474 (org-load-modules-maybe)
8475 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8477 ;;;###autoload
8478 (defun turn-on-orgstruct ()
8479 "Unconditionally turn on `orgstruct-mode'."
8480 (orgstruct-mode 1))
8482 (defvar org-fb-vars nil)
8483 (make-variable-buffer-local 'org-fb-vars)
8484 (defun orgstruct++-mode (&optional arg)
8485 "Toggle `orgstruct-mode', the enhanced version of it.
8486 In addition to setting orgstruct-mode, this also exports all
8487 indentation and autofilling variables from org-mode into the
8488 buffer. It will also recognize item context in multiline items."
8489 (interactive "P")
8490 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8491 (if (< arg 1)
8492 (progn (orgstruct-mode -1)
8493 (mapc (lambda(v)
8494 (org-set-local (car v)
8495 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8496 org-fb-vars))
8497 (orgstruct-mode 1)
8498 (setq org-fb-vars nil)
8499 (let (var val)
8500 (mapc
8501 (lambda (x)
8502 (when (string-match
8503 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8504 (symbol-name (car x)))
8505 (setq var (car x) val (nth 1 x))
8506 (push (list var `(quote ,(eval var))) org-fb-vars)
8507 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8508 org-local-vars)
8509 (org-set-local 'orgstruct-is-++ t))))
8511 (defvar orgstruct-is-++ nil
8512 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8513 (make-variable-buffer-local 'orgstruct-is-++)
8515 ;;;###autoload
8516 (defun turn-on-orgstruct++ ()
8517 "Unconditionally turn on `orgstruct++-mode'."
8518 (orgstruct++-mode 1))
8520 (defun orgstruct-error ()
8521 "Error when there is no default binding for a structure key."
8522 (interactive)
8523 (error "This key has no function outside structure elements"))
8525 (defun orgstruct-setup ()
8526 "Setup orgstruct keymaps."
8527 (let ((nfunc 0)
8528 (bindings
8529 (list
8530 '([(meta up)] org-metaup)
8531 '([(meta down)] org-metadown)
8532 '([(meta left)] org-metaleft)
8533 '([(meta right)] org-metaright)
8534 '([(meta shift up)] org-shiftmetaup)
8535 '([(meta shift down)] org-shiftmetadown)
8536 '([(meta shift left)] org-shiftmetaleft)
8537 '([(meta shift right)] org-shiftmetaright)
8538 '([?\e (up)] org-metaup)
8539 '([?\e (down)] org-metadown)
8540 '([?\e (left)] org-metaleft)
8541 '([?\e (right)] org-metaright)
8542 '([?\e (shift up)] org-shiftmetaup)
8543 '([?\e (shift down)] org-shiftmetadown)
8544 '([?\e (shift left)] org-shiftmetaleft)
8545 '([?\e (shift right)] org-shiftmetaright)
8546 '([(shift up)] org-shiftup)
8547 '([(shift down)] org-shiftdown)
8548 '([(shift left)] org-shiftleft)
8549 '([(shift right)] org-shiftright)
8550 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8551 '("\M-q" fill-paragraph)
8552 '("\C-c^" org-sort)
8553 '("\C-c-" org-cycle-list-bullet)))
8554 elt key fun cmd)
8555 (while (setq elt (pop bindings))
8556 (setq nfunc (1+ nfunc))
8557 (setq key (org-key (car elt))
8558 fun (nth 1 elt)
8559 cmd (orgstruct-make-binding fun nfunc key))
8560 (org-defkey orgstruct-mode-map key cmd))
8562 ;; Prevent an error for users who forgot to make autoloads
8563 (require 'org-element)
8565 ;; Special treatment needed for TAB and RET
8566 (org-defkey orgstruct-mode-map [(tab)]
8567 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8568 (org-defkey orgstruct-mode-map "\C-i"
8569 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8571 (org-defkey orgstruct-mode-map "\M-\C-m"
8572 (orgstruct-make-binding 'org-insert-heading 105
8573 "\M-\C-m" [(meta return)]))
8574 (org-defkey orgstruct-mode-map [(meta return)]
8575 (orgstruct-make-binding 'org-insert-heading 106
8576 [(meta return)] "\M-\C-m"))
8578 (org-defkey orgstruct-mode-map [(shift meta return)]
8579 (orgstruct-make-binding 'org-insert-todo-heading 107
8580 [(meta return)] "\M-\C-m"))
8582 (org-defkey orgstruct-mode-map "\e\C-m"
8583 (orgstruct-make-binding 'org-insert-heading 108
8584 "\e\C-m" [?\e (return)]))
8585 (org-defkey orgstruct-mode-map [?\e (return)]
8586 (orgstruct-make-binding 'org-insert-heading 109
8587 [?\e (return)] "\e\C-m"))
8588 (org-defkey orgstruct-mode-map [?\e (shift return)]
8589 (orgstruct-make-binding 'org-insert-todo-heading 110
8590 [?\e (return)] "\e\C-m"))
8592 (unless org-local-vars
8593 (setq org-local-vars (org-get-local-variables)))
8597 (defun orgstruct-make-binding (fun n &rest keys)
8598 "Create a function for binding in the structure minor mode.
8599 FUN is the command to call inside a table. N is used to create a unique
8600 command name. KEYS are keys that should be checked in for a command
8601 to execute outside of tables."
8602 (eval
8603 (list 'defun
8604 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8605 '(arg)
8606 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8607 "Outside of structure, run the binding of `"
8608 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8609 "'.")
8610 '(interactive "p")
8611 (list 'if
8612 `(org-context-p 'headline 'item
8613 (and orgstruct-is-++
8614 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8615 'item-body))
8616 (list 'org-run-like-in-org-mode (list 'quote fun))
8617 (list 'let '(orgstruct-mode)
8618 (list 'call-interactively
8619 (append '(or)
8620 (mapcar (lambda (k)
8621 (list 'key-binding k))
8622 keys)
8623 '('orgstruct-error))))))))
8625 (defun org-contextualize-keys (alist contexts)
8626 "Return valid elements in ALIST depending on CONTEXTS.
8628 `org-agenda-custom-commands' or `org-capture-templates' are the
8629 values used for ALIST, and `org-agenda-custom-commands-contexts'
8630 or `org-capture-templates-contexts' are the associated contexts
8631 definitions."
8632 (let ((contexts
8633 ;; normalize contexts
8634 (mapcar
8635 (lambda(c) (cond ((listp (cadr c))
8636 (list (car c) (car c) (cadr c)))
8637 ((string= "" (cadr c))
8638 (list (car c) (car c) (caddr c)))
8639 (t c))) contexts))
8640 (a alist) c r s)
8641 ;; loop over all commands or templates
8642 (while (setq c (pop a))
8643 (let (vrules repl)
8644 (cond
8645 ((not (assoc (car c) contexts))
8646 (push c r))
8647 ((and (assoc (car c) contexts)
8648 (setq vrules (org-contextualize-validate-key
8649 (car c) contexts)))
8650 (mapc (lambda (vr)
8651 (when (not (equal (car vr) (cadr vr)))
8652 (setq repl vr))) vrules)
8653 (if (not repl) (push c r)
8654 (push (cadr repl) s)
8655 (push
8656 (cons (car c)
8657 (cdr (or (assoc (cadr repl) alist)
8658 (error "Undefined key `%s' as contextual replacement for `%s'"
8659 (cadr repl) (car c)))))
8660 r))))))
8661 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8662 (delq
8664 (delete-dups
8665 (mapcar (lambda (x)
8666 (let ((tpl (car x)))
8667 (when (not (delq
8669 (mapcar (lambda(y)
8670 (equal y tpl)) s))) x)))
8671 (reverse r))))))
8673 (defun org-contextualize-validate-key (key contexts)
8674 "Check CONTEXTS for agenda or capture KEY."
8675 (let (r rr res)
8676 (while (setq r (pop contexts))
8677 (mapc
8678 (lambda (rr)
8679 (when
8680 (and (equal key (car r))
8681 (if (functionp rr) (funcall rr)
8682 (or (and (eq (car rr) 'in-file)
8683 (buffer-file-name)
8684 (string-match (cdr rr) (buffer-file-name)))
8685 (and (eq (car rr) 'in-mode)
8686 (string-match (cdr rr) (symbol-name major-mode)))
8687 (when (and (eq (car rr) 'not-in-file)
8688 (buffer-file-name))
8689 (not (string-match (cdr rr) (buffer-file-name))))
8690 (when (eq (car rr) 'not-in-mode)
8691 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8692 (push r res)))
8693 (car (last r))))
8694 (delete-dups (delq nil res))))
8696 (defun org-context-p (&rest contexts)
8697 "Check if local context is any of CONTEXTS.
8698 Possible values in the list of contexts are `table', `headline', and `item'."
8699 (let ((pos (point)))
8700 (goto-char (point-at-bol))
8701 (prog1 (or (and (memq 'table contexts)
8702 (looking-at "[ \t]*|"))
8703 (and (memq 'headline contexts)
8704 (looking-at org-outline-regexp))
8705 (and (memq 'item contexts)
8706 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8707 (and (memq 'item-body contexts)
8708 (org-in-item-p)))
8709 (goto-char pos))))
8711 (defun org-get-local-variables ()
8712 "Return a list of all local variables in an Org mode buffer."
8713 (let (varlist)
8714 (with-current-buffer (get-buffer-create "*Org tmp*")
8715 (erase-buffer)
8716 (org-mode)
8717 (setq varlist (buffer-local-variables)))
8718 (kill-buffer "*Org tmp*")
8719 (delq nil
8720 (mapcar
8721 (lambda (x)
8722 (setq x
8723 (if (symbolp x)
8724 (list x)
8725 (list (car x) (list 'quote (cdr x)))))
8726 (if (string-match
8727 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8728 (symbol-name (car x)))
8729 x nil))
8730 varlist))))
8732 (defun org-clone-local-variables (from-buffer &optional regexp)
8733 "Clone local variables from FROM-BUFFER.
8734 Optional argument REGEXP selects variables to clone."
8735 (mapc
8736 (lambda (pair)
8737 (and (symbolp (car pair))
8738 (or (null regexp)
8739 (string-match regexp (symbol-name (car pair))))
8740 (set (make-local-variable (car pair))
8741 (cdr pair))))
8742 (buffer-local-variables from-buffer)))
8744 ;;;###autoload
8745 (defun org-run-like-in-org-mode (cmd)
8746 "Run a command, pretending that the current buffer is in Org-mode.
8747 This will temporarily bind local variables that are typically bound in
8748 Org-mode to the values they have in Org-mode, and then interactively
8749 call CMD."
8750 (org-load-modules-maybe)
8751 (unless org-local-vars
8752 (setq org-local-vars (org-get-local-variables)))
8753 (eval (list 'let org-local-vars
8754 (list 'call-interactively (list 'quote cmd)))))
8756 ;;;; Archiving
8758 (defun org-get-category (&optional pos force-refresh)
8759 "Get the category applying to position POS."
8760 (save-match-data
8761 (if force-refresh (org-refresh-category-properties))
8762 (let ((pos (or pos (point))))
8763 (or (get-text-property pos 'org-category)
8764 (progn (org-refresh-category-properties)
8765 (get-text-property pos 'org-category))))))
8767 (defun org-refresh-category-properties ()
8768 "Refresh category text properties in the buffer."
8769 (let ((case-fold-search t)
8770 (inhibit-read-only t)
8771 (def-cat (cond
8772 ((null org-category)
8773 (if buffer-file-name
8774 (file-name-sans-extension
8775 (file-name-nondirectory buffer-file-name))
8776 "???"))
8777 ((symbolp org-category) (symbol-name org-category))
8778 (t org-category)))
8779 beg end cat pos optionp)
8780 (org-unmodified
8781 (save-excursion
8782 (save-restriction
8783 (widen)
8784 (goto-char (point-min))
8785 (put-text-property (point) (point-max) 'org-category def-cat)
8786 (while (re-search-forward
8787 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8788 (setq pos (match-end 0)
8789 optionp (equal (char-after (match-beginning 0)) ?#)
8790 cat (org-trim (match-string 2)))
8791 (if optionp
8792 (setq beg (point-at-bol) end (point-max))
8793 (org-back-to-heading t)
8794 (setq beg (point) end (org-end-of-subtree t t)))
8795 (put-text-property beg end 'org-category cat)
8796 (put-text-property beg end 'org-category-position beg)
8797 (goto-char pos)))))))
8800 ;;;; Link Stuff
8802 ;;; Link abbreviations
8804 (defun org-link-expand-abbrev (link)
8805 "Apply replacements as defined in `org-link-abbrev-alist'."
8806 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8807 (let* ((key (match-string 1 link))
8808 (as (or (assoc key org-link-abbrev-alist-local)
8809 (assoc key org-link-abbrev-alist)))
8810 (tag (and (match-end 2) (match-string 3 link)))
8811 rpl)
8812 (if (not as)
8813 link
8814 (setq rpl (cdr as))
8815 (cond
8816 ((symbolp rpl) (funcall rpl tag))
8817 ((string-match "%(\\([^)]+\\))" rpl)
8818 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8819 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8820 ((string-match "%h" rpl)
8821 (replace-match (url-hexify-string (or tag "")) t t rpl))
8822 (t (concat rpl tag)))))
8823 link))
8825 ;;; Storing and inserting links
8827 (defvar org-insert-link-history nil
8828 "Minibuffer history for links inserted with `org-insert-link'.")
8830 (defvar org-stored-links nil
8831 "Contains the links stored with `org-store-link'.")
8833 (defvar org-store-link-plist nil
8834 "Plist with info about the most recently link created with `org-store-link'.")
8836 (defvar org-link-protocols nil
8837 "Link protocols added to Org-mode using `org-add-link-type'.")
8839 (defvar org-store-link-functions nil
8840 "List of functions that are called to create and store a link.
8841 Each function will be called in turn until one returns a non-nil
8842 value. Each function should check if it is responsible for creating
8843 this link (for example by looking at the major mode).
8844 If not, it must exit and return nil.
8845 If yes, it should return a non-nil value after a calling
8846 `org-store-link-props' with a list of properties and values.
8847 Special properties are:
8849 :type The link prefix, like \"http\". This must be given.
8850 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8851 This is obligatory as well.
8852 :description Optional default description for the second pair
8853 of brackets in an Org-mode link. The user can still change
8854 this when inserting this link into an Org-mode buffer.
8856 In addition to these, any additional properties can be specified
8857 and then used in remember templates.")
8859 (defun org-add-link-type (type &optional follow export)
8860 "Add TYPE to the list of `org-link-types'.
8861 Re-compute all regular expressions depending on `org-link-types'
8863 FOLLOW and EXPORT are two functions.
8865 FOLLOW should take the link path as the single argument and do whatever
8866 is necessary to follow the link, for example find a file or display
8867 a mail message.
8869 EXPORT should format the link path for export to one of the export formats.
8870 It should be a function accepting three arguments:
8872 path the path of the link, the text after the prefix (like \"http:\")
8873 desc the description of the link, if any, or a description added by
8874 org-export-normalize-links if there is none
8875 format the export format, a symbol like `html' or `latex' or `ascii'..
8877 The function may use the FORMAT information to return different values
8878 depending on the format. The return value will be put literally into
8879 the exported file. If the return value is nil, this means Org should
8880 do what it normally does with links which do not have EXPORT defined.
8882 Org-mode has a built-in default for exporting links. If you are happy with
8883 this default, there is no need to define an export function for the link
8884 type. For a simple example of an export function, see `org-bbdb.el'."
8885 (add-to-list 'org-link-types type t)
8886 (org-make-link-regexps)
8887 (if (assoc type org-link-protocols)
8888 (setcdr (assoc type org-link-protocols) (list follow export))
8889 (push (list type follow export) org-link-protocols)))
8891 (defvar org-agenda-buffer-name)
8893 ;;;###autoload
8894 (defun org-store-link (arg)
8895 "\\<org-mode-map>Store an org-link to the current location.
8896 This link is added to `org-stored-links' and can later be inserted
8897 into an org-buffer with \\[org-insert-link].
8899 For some link types, a prefix arg is interpreted:
8900 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8901 For file links, arg negates `org-context-in-file-links'."
8902 (interactive "P")
8903 (org-load-modules-maybe)
8904 (setq org-store-link-plist nil) ; reset
8905 (org-with-limited-levels
8906 (let (link cpltxt desc description search txt custom-id agenda-link)
8907 (cond
8909 ((run-hook-with-args-until-success 'org-store-link-functions)
8910 (setq link (plist-get org-store-link-plist :link)
8911 desc (or (plist-get org-store-link-plist :description) link)))
8913 ((org-src-edit-buffer-p)
8914 (let (label gc)
8915 (while (or (not label)
8916 (save-excursion
8917 (save-restriction
8918 (widen)
8919 (goto-char (point-min))
8920 (re-search-forward
8921 (regexp-quote (format org-coderef-label-format label))
8922 nil t))))
8923 (when label (message "Label exists already") (sit-for 2))
8924 (setq label (read-string "Code line label: " label)))
8925 (end-of-line 1)
8926 (setq link (format org-coderef-label-format label))
8927 (setq gc (- 79 (length link)))
8928 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8929 (insert link)
8930 (setq link (concat "(" label ")") desc nil)))
8932 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8933 ;; We are in the agenda, link to referenced location
8934 (let ((m (or (get-text-property (point) 'org-hd-marker)
8935 (get-text-property (point) 'org-marker))))
8936 (when m
8937 (org-with-point-at m
8938 (setq agenda-link
8939 (if (org-called-interactively-p 'any)
8940 (call-interactively 'org-store-link)
8941 (org-store-link nil)))))))
8943 ((eq major-mode 'calendar-mode)
8944 (let ((cd (calendar-cursor-to-date)))
8945 (setq link
8946 (format-time-string
8947 (car org-time-stamp-formats)
8948 (apply 'encode-time
8949 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8950 nil nil nil))))
8951 (org-store-link-props :type "calendar" :date cd)))
8953 ((eq major-mode 'help-mode)
8954 (setq link (concat "help:" (save-excursion
8955 (goto-char (point-min))
8956 (looking-at "^[^ ]+")
8957 (match-string 0))))
8958 (org-store-link-props :type "help"))
8960 ((eq major-mode 'w3-mode)
8961 (setq cpltxt (if (and (buffer-name)
8962 (not (string-match "Untitled" (buffer-name))))
8963 (buffer-name)
8964 (url-view-url t))
8965 link (url-view-url t))
8966 (org-store-link-props :type "w3" :url (url-view-url t)))
8968 ((eq major-mode 'w3m-mode)
8969 (setq cpltxt (or w3m-current-title w3m-current-url)
8970 link w3m-current-url)
8971 (org-store-link-props :type "w3m" :url (url-view-url t)))
8973 ((setq search (run-hook-with-args-until-success
8974 'org-create-file-search-functions))
8975 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8976 "::" search))
8977 (setq cpltxt (or description link)))
8979 ((eq major-mode 'image-mode)
8980 (setq cpltxt (concat "file:"
8981 (abbreviate-file-name buffer-file-name))
8982 link cpltxt)
8983 (org-store-link-props :type "image" :file buffer-file-name))
8985 ((eq major-mode 'dired-mode)
8986 ;; link to the file in the current line
8987 (let ((file (dired-get-filename nil t)))
8988 (setq file (if file
8989 (abbreviate-file-name
8990 (expand-file-name (dired-get-filename nil t)))
8991 ;; otherwise, no file so use current directory.
8992 default-directory))
8993 (setq cpltxt (concat "file:" file)
8994 link cpltxt)))
8996 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8997 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8998 (cond
8999 ((org-in-regexp "<<\\(.*?\\)>>")
9000 (setq cpltxt
9001 (concat "file:"
9002 (abbreviate-file-name
9003 (buffer-file-name (buffer-base-buffer)))
9004 "::" (match-string 1))
9005 link cpltxt))
9006 ((and (featurep 'org-id)
9007 (or (eq org-link-to-org-use-id t)
9008 (and (org-called-interactively-p 'any)
9009 (or (eq org-link-to-org-use-id 'create-if-interactive)
9010 (and (eq org-link-to-org-use-id
9011 'create-if-interactive-and-no-custom-id)
9012 (not custom-id))))
9013 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9014 ;; We can make a link using the ID.
9015 (setq link (condition-case nil
9016 (prog1 (org-id-store-link)
9017 (setq desc (plist-get org-store-link-plist :description)))
9018 (error
9019 ;; probably before first headline, link to file only
9020 (concat "file:"
9021 (abbreviate-file-name
9022 (buffer-file-name (buffer-base-buffer))))))))
9024 ;; Just link to current headline
9025 (setq cpltxt (concat "file:"
9026 (abbreviate-file-name
9027 (buffer-file-name (buffer-base-buffer)))))
9028 ;; Add a context search string
9029 (when (org-xor org-context-in-file-links arg)
9030 (setq txt (cond
9031 ((org-at-heading-p) nil)
9032 ((org-region-active-p)
9033 (buffer-substring (region-beginning) (region-end)))))
9034 (when (or (null txt) (string-match "\\S-" txt))
9035 (setq cpltxt
9036 (concat cpltxt "::"
9037 (condition-case nil
9038 (org-make-org-heading-search-string txt)
9039 (error "")))
9040 desc (or (nth 4 (ignore-errors
9041 (org-heading-components))) "NONE"))))
9042 (if (string-match "::\\'" cpltxt)
9043 (setq cpltxt (substring cpltxt 0 -2)))
9044 (setq link cpltxt))))
9046 ((buffer-file-name (buffer-base-buffer))
9047 ;; Just link to this file here.
9048 (setq cpltxt (concat "file:"
9049 (abbreviate-file-name
9050 (buffer-file-name (buffer-base-buffer)))))
9051 ;; Add a context string
9052 (when (org-xor org-context-in-file-links arg)
9053 (setq txt (if (org-region-active-p)
9054 (buffer-substring (region-beginning) (region-end))
9055 (buffer-substring (point-at-bol) (point-at-eol))))
9056 ;; Only use search option if there is some text.
9057 (when (string-match "\\S-" txt)
9058 (setq cpltxt
9059 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9060 desc "NONE")))
9061 (setq link cpltxt))
9063 ((org-called-interactively-p 'interactive)
9064 (error "Cannot link to a buffer which is not visiting a file"))
9066 (t (setq link nil)))
9068 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9069 (setq link (or link cpltxt)
9070 desc (or desc cpltxt))
9071 (if (equal desc "NONE") (setq desc nil))
9073 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9074 (progn
9075 (setq org-stored-links
9076 (cons (list link desc) org-stored-links))
9077 (message "Stored: %s" (or desc link))
9078 (when custom-id
9079 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9080 "::#" custom-id))
9081 (setq org-stored-links
9082 (cons (list link desc) org-stored-links))))
9083 (or agenda-link (and link (org-make-link-string link desc)))))))
9085 (defun org-store-link-props (&rest plist)
9086 "Store link properties, extract names and addresses."
9087 (let (x adr)
9088 (when (setq x (plist-get plist :from))
9089 (setq adr (mail-extract-address-components x))
9090 (setq plist (plist-put plist :fromname (car adr)))
9091 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9092 (when (setq x (plist-get plist :to))
9093 (setq adr (mail-extract-address-components x))
9094 (setq plist (plist-put plist :toname (car adr)))
9095 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9096 (let ((from (plist-get plist :from))
9097 (to (plist-get plist :to)))
9098 (when (and from to org-from-is-user-regexp)
9099 (setq plist
9100 (plist-put plist :fromto
9101 (if (string-match org-from-is-user-regexp from)
9102 (concat "to %t")
9103 (concat "from %f"))))))
9104 (setq org-store-link-plist plist))
9106 (defun org-add-link-props (&rest plist)
9107 "Add these properties to the link property list."
9108 (let (key value)
9109 (while plist
9110 (setq key (pop plist) value (pop plist))
9111 (setq org-store-link-plist
9112 (plist-put org-store-link-plist key value)))))
9114 (defun org-email-link-description (&optional fmt)
9115 "Return the description part of an email link.
9116 This takes information from `org-store-link-plist' and formats it
9117 according to FMT (default from `org-email-link-description-format')."
9118 (setq fmt (or fmt org-email-link-description-format))
9119 (let* ((p org-store-link-plist)
9120 (to (plist-get p :toaddress))
9121 (from (plist-get p :fromaddress))
9122 (table
9123 (list
9124 (cons "%c" (plist-get p :fromto))
9125 (cons "%F" (plist-get p :from))
9126 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9127 (cons "%T" (plist-get p :to))
9128 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9129 (cons "%s" (plist-get p :subject))
9130 (cons "%d" (plist-get p :date))
9131 (cons "%m" (plist-get p :message-id)))))
9132 (when (string-match "%c" fmt)
9133 ;; Check if the user wrote this message
9134 (if (and org-from-is-user-regexp from to
9135 (save-match-data (string-match org-from-is-user-regexp from)))
9136 (setq fmt (replace-match "to %t" t t fmt))
9137 (setq fmt (replace-match "from %f" t t fmt))))
9138 (org-replace-escapes fmt table)))
9140 (defun org-make-org-heading-search-string (&optional string heading)
9141 "Make search string for STRING or current headline."
9142 (interactive)
9143 (let ((s (or string (org-get-heading)))
9144 (lines org-context-in-file-links))
9145 (unless (and string (not heading))
9146 ;; We are using a headline, clean up garbage in there.
9147 (if (string-match org-todo-regexp s)
9148 (setq s (replace-match "" t t s)))
9149 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9150 (setq s (replace-match "" t t s)))
9151 (setq s (org-trim s))
9152 (if (string-match (concat "^\\(" org-quote-string "\\|"
9153 org-comment-string "\\)") s)
9154 (setq s (replace-match "" t t s)))
9155 (while (string-match org-ts-regexp s)
9156 (setq s (replace-match "" t t s))))
9157 (or string (setq s (concat "*" s))) ; Add * for headlines
9158 (when (and string (integerp lines) (> lines 0))
9159 (let ((slines (org-split-string s "\n")))
9160 (when (< lines (length slines))
9161 (setq s (mapconcat
9162 'identity
9163 (reverse (nthcdr (- (length slines) lines)
9164 (reverse slines))) "\n")))))
9165 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9167 (defun org-make-link-string (link &optional description)
9168 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9169 (unless (string-match "\\S-" link)
9170 (error "Empty link"))
9171 (when (and description
9172 (stringp description)
9173 (not (string-match "\\S-" description)))
9174 (setq description nil))
9175 (when (stringp description)
9176 ;; Remove brackets from the description, they are fatal.
9177 (while (string-match "\\[" description)
9178 (setq description (replace-match "{" t t description)))
9179 (while (string-match "\\]" description)
9180 (setq description (replace-match "}" t t description))))
9181 (when (equal link description)
9182 ;; No description needed, it is identical
9183 (setq description nil))
9184 (when (and (not description)
9185 (not (string-match (org-image-file-name-regexp) link))
9186 (not (equal link (org-link-escape link))))
9187 (setq description (org-extract-attributes link)))
9188 (setq link
9189 (cond ((string-match (org-image-file-name-regexp) link) link)
9190 ((string-match org-link-types-re link)
9191 (concat (match-string 1 link)
9192 (org-link-escape (substring link (match-end 1)))))
9193 (t (org-link-escape link))))
9194 (concat "[[" link "]"
9195 (if description (concat "[" description "]") "")
9196 "]"))
9198 (defconst org-link-escape-chars
9199 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9200 "List of characters that should be escaped in link.
9201 This is the list that is used for internal purposes.")
9203 (defconst org-link-escape-chars-browser
9204 '(?\ )
9205 "List of escapes for characters that are problematic in links.
9206 This is the list that is used before handing over to the browser.")
9208 (defun org-link-escape (text &optional table merge)
9209 "Return percent escaped representation of TEXT.
9210 TEXT is a string with the text to escape.
9211 Optional argument TABLE is a list with characters that should be
9212 escaped. When nil, `org-link-escape-chars' is used.
9213 If optional argument MERGE is set, merge TABLE into
9214 `org-link-escape-chars'."
9215 (cond
9216 ((and table merge)
9217 (mapc (lambda (defchr)
9218 (unless (member defchr table)
9219 (setq table (cons defchr table)))) org-link-escape-chars))
9220 ((null table)
9221 (setq table org-link-escape-chars)))
9222 (mapconcat
9223 (lambda (char)
9224 (if (or (member char table)
9225 (and (or (< char 32) (= char 37) (> char 126))
9226 org-url-hexify-p))
9227 (mapconcat (lambda (sequence-element)
9228 (format "%%%.2X" sequence-element))
9229 (or (encode-coding-char char 'utf-8)
9230 (error "Unable to percent escape character: %s"
9231 (char-to-string char))) "")
9232 (char-to-string char))) text ""))
9234 (defun org-link-unescape (str)
9235 "Unhex hexified Unicode strings as returned from the JavaScript function
9236 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9237 (unless (and (null str) (string= "" str))
9238 (let ((pos 0) (case-fold-search t) unhexed)
9239 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9240 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9241 (setq str (replace-match unhexed t t str))
9242 (setq pos (+ pos (length unhexed))))))
9243 str)
9245 (defun org-link-unescape-compound (hex)
9246 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9247 Note: this function also decodes single byte encodings like
9248 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9249 (save-match-data
9250 (let* ((bytes (cdr (split-string hex "%")))
9251 (ret "")
9252 (eat 0)
9253 (sum 0))
9254 (while bytes
9255 (let* ((val (string-to-number (pop bytes) 16))
9256 (shift-xor
9257 (if (= 0 eat)
9258 (cond
9259 ((>= val 252) (cons 6 252))
9260 ((>= val 248) (cons 5 248))
9261 ((>= val 240) (cons 4 240))
9262 ((>= val 224) (cons 3 224))
9263 ((>= val 192) (cons 2 192))
9264 (t (cons 0 0)))
9265 (cons 6 128))))
9266 (if (>= val 192) (setq eat (car shift-xor)))
9267 (setq val (logxor val (cdr shift-xor)))
9268 (setq sum (+ (lsh sum (car shift-xor)) val))
9269 (if (> eat 0) (setq eat (- eat 1)))
9270 (cond
9271 ((= 0 eat) ;multi byte
9272 (setq ret (concat ret (org-char-to-string sum)))
9273 (setq sum 0))
9274 ((not bytes) ; single byte(s)
9275 (setq ret (org-link-unescape-single-byte-sequence hex))))
9276 )) ;; end (while bytes
9277 ret )))
9279 (defun org-link-unescape-single-byte-sequence (hex)
9280 "Unhexify hex-encoded single byte character sequences."
9281 (mapconcat (lambda (byte)
9282 (char-to-string (string-to-number byte 16)))
9283 (cdr (split-string hex "%")) ""))
9285 (defun org-xor (a b)
9286 "Exclusive or."
9287 (if a (not b) b))
9289 (defun org-fixup-message-id-for-http (s)
9290 "Replace special characters in a message id, so it can be used in an http query."
9291 (when (string-match "%" s)
9292 (setq s (mapconcat (lambda (c)
9293 (if (eq c ?%)
9294 "%25"
9295 (char-to-string c)))
9296 s "")))
9297 (while (string-match "<" s)
9298 (setq s (replace-match "%3C" t t s)))
9299 (while (string-match ">" s)
9300 (setq s (replace-match "%3E" t t s)))
9301 (while (string-match "@" s)
9302 (setq s (replace-match "%40" t t s)))
9305 (defun org-link-prettify (link)
9306 "Return a human-readable representation of LINK.
9307 The car of LINK must be a raw link the cdr of LINK must be either
9308 a link description or nil."
9309 (let ((desc (or (cadr link) "<no description>")))
9310 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9311 "<" (car link) ">")))
9313 ;;;###autoload
9314 (defun org-insert-link-global ()
9315 "Insert a link like Org-mode does.
9316 This command can be called in any mode to insert a link in Org-mode syntax."
9317 (interactive)
9318 (org-load-modules-maybe)
9319 (org-run-like-in-org-mode 'org-insert-link))
9321 (defun org-insert-all-links (&optional keep)
9322 "Insert all links in `org-stored-links'."
9323 (interactive "P")
9324 (let ((links (copy-sequence org-stored-links)) l)
9325 (while (setq l (if keep (pop links) (pop org-stored-links)))
9326 (insert "- ")
9327 (org-insert-link nil (car l) (cadr l))
9328 (insert "\n"))))
9330 (defun org-link-fontify-links-to-this-file ()
9331 "Fontify links to the current file in `org-stored-links'."
9332 (let ((f (buffer-file-name)) a b)
9333 (setq a (mapcar (lambda(l)
9334 (let ((ll (car l)))
9335 (when (and (string-match "^file:\\(.+\\)::" ll)
9336 (equal f (expand-file-name (match-string 1 ll))))
9337 ll)))
9338 org-stored-links))
9339 (when (featurep 'org-id)
9340 (setq b (mapcar (lambda(l)
9341 (let ((ll (car l)))
9342 (when (and (string-match "^id:\\(.+\\)$" ll)
9343 (equal f (expand-file-name
9344 (or (org-id-find-id-file
9345 (match-string 1 ll)) ""))))
9346 ll)))
9347 org-stored-links)))
9348 (mapcar (lambda(l)
9349 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9350 (delq nil (append a b)))))
9352 (defvar org-link-links-in-this-file nil)
9353 (defun org-insert-link (&optional complete-file link-location default-description)
9354 "Insert a link. At the prompt, enter the link.
9356 Completion can be used to insert any of the link protocol prefixes like
9357 http or ftp in use.
9359 The history can be used to select a link previously stored with
9360 `org-store-link'. When the empty string is entered (i.e. if you just
9361 press RET at the prompt), the link defaults to the most recently
9362 stored link. As SPC triggers completion in the minibuffer, you need to
9363 use M-SPC or C-q SPC to force the insertion of a space character.
9365 You will also be prompted for a description, and if one is given, it will
9366 be displayed in the buffer instead of the link.
9368 If there is already a link at point, this command will allow you to edit link
9369 and description parts.
9371 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9372 be selected using completion. The path to the file will be relative to the
9373 current directory if the file is in the current directory or a subdirectory.
9374 Otherwise, the link will be the absolute path as completed in the minibuffer
9375 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9376 option `org-link-file-path-type'.
9378 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9379 the current directory or below.
9381 With three \\[universal-argument] prefixes, negate the meaning of
9382 `org-keep-stored-link-after-insertion'.
9384 If `org-make-link-description-function' is non-nil, this function will be
9385 called with the link target, and the result will be the default
9386 link description.
9388 If the LINK-LOCATION parameter is non-nil, this value will be
9389 used as the link location instead of reading one interactively.
9391 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9392 be used as the default description."
9393 (interactive "P")
9394 (let* ((wcf (current-window-configuration))
9395 (region (if (org-region-active-p)
9396 (buffer-substring (region-beginning) (region-end))))
9397 (remove (and region (list (region-beginning) (region-end))))
9398 (desc region)
9399 tmphist ; byte-compile incorrectly complains about this
9400 (link link-location)
9401 (abbrevs org-link-abbrev-alist-local)
9402 entry file all-prefixes auto-desc)
9403 (cond
9404 (link-location) ; specified by arg, just use it.
9405 ((org-in-regexp org-bracket-link-regexp 1)
9406 ;; We do have a link at point, and we are going to edit it.
9407 (setq remove (list (match-beginning 0) (match-end 0)))
9408 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9409 (setq link (read-string "Link: "
9410 (org-link-unescape
9411 (org-match-string-no-properties 1)))))
9412 ((or (org-in-regexp org-angle-link-re)
9413 (org-in-regexp org-plain-link-re))
9414 ;; Convert to bracket link
9415 (setq remove (list (match-beginning 0) (match-end 0))
9416 link (read-string "Link: "
9417 (org-remove-angle-brackets (match-string 0)))))
9418 ((member complete-file '((4) (16)))
9419 ;; Completing read for file names.
9420 (setq link (org-file-complete-link complete-file)))
9422 ;; Read link, with completion for stored links.
9423 (org-link-fontify-links-to-this-file)
9424 (org-switch-to-buffer-other-window "*Org Links*")
9425 (with-current-buffer "*Org Links*"
9426 (erase-buffer)
9427 (insert "Insert a link.
9428 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9429 (when org-stored-links
9430 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9431 (insert (mapconcat 'org-link-prettify
9432 (reverse org-stored-links) "\n")))
9433 (goto-char (point-min)))
9434 (let ((cw (selected-window)))
9435 (select-window (get-buffer-window "*Org Links*" 'visible))
9436 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9437 (unless (pos-visible-in-window-p (point-max))
9438 (org-fit-window-to-buffer))
9439 (and (window-live-p cw) (select-window cw)))
9440 ;; Fake a link history, containing the stored links.
9441 (setq tmphist (append (mapcar 'car org-stored-links)
9442 org-insert-link-history))
9443 (setq all-prefixes (append (mapcar 'car abbrevs)
9444 (mapcar 'car org-link-abbrev-alist)
9445 org-link-types))
9446 (unwind-protect
9447 (progn
9448 (setq link
9449 (let ((org-completion-use-ido nil)
9450 (org-completion-use-iswitchb nil))
9451 (org-completing-read
9452 "Link: "
9453 (append
9454 (mapcar (lambda (x) (list (concat x ":")))
9455 all-prefixes)
9456 (mapcar 'car org-stored-links)
9457 (mapcar 'cadr org-stored-links))
9458 nil nil nil
9459 'tmphist
9460 (caar org-stored-links))))
9461 (if (not (string-match "\\S-" link))
9462 (error "No link selected"))
9463 (mapc (lambda(l)
9464 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9465 org-stored-links)
9466 (if (or (member link all-prefixes)
9467 (and (equal ":" (substring link -1))
9468 (member (substring link 0 -1) all-prefixes)
9469 (setq link (substring link 0 -1))))
9470 (setq link (org-link-try-special-completion link))))
9471 (set-window-configuration wcf)
9472 (kill-buffer "*Org Links*"))
9473 (setq entry (assoc link org-stored-links))
9474 (or entry (push link org-insert-link-history))
9475 (setq desc (or desc (nth 1 entry)))))
9477 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9478 (not org-keep-stored-link-after-insertion))
9479 (setq org-stored-links (delq (assoc link org-stored-links)
9480 org-stored-links)))
9482 (if (string-match org-plain-link-re link)
9483 ;; URL-like link, normalize the use of angular brackets.
9484 (setq link (org-remove-angle-brackets link)))
9486 ;; Check if we are linking to the current file with a search option
9487 ;; If yes, simplify the link by using only the search option.
9488 (when (and buffer-file-name
9489 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9490 (let* ((path (match-string 1 link))
9491 (case-fold-search nil)
9492 (search (match-string 2 link)))
9493 (save-match-data
9494 (if (equal (file-truename buffer-file-name) (file-truename path))
9495 ;; We are linking to this same file, with a search option
9496 (setq link search)))))
9498 ;; Check if we can/should use a relative path. If yes, simplify the link
9499 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9500 (let* ((type (match-string 1 link))
9501 (path (match-string 2 link))
9502 (origpath path)
9503 (case-fold-search nil))
9504 (cond
9505 ((or (eq org-link-file-path-type 'absolute)
9506 (equal complete-file '(16)))
9507 (setq path (abbreviate-file-name (expand-file-name path))))
9508 ((eq org-link-file-path-type 'noabbrev)
9509 (setq path (expand-file-name path)))
9510 ((eq org-link-file-path-type 'relative)
9511 (setq path (file-relative-name path)))
9513 (save-match-data
9514 (if (string-match (concat "^" (regexp-quote
9515 (expand-file-name
9516 (file-name-as-directory
9517 default-directory))))
9518 (expand-file-name path))
9519 ;; We are linking a file with relative path name.
9520 (setq path (substring (expand-file-name path)
9521 (match-end 0)))
9522 (setq path (abbreviate-file-name (expand-file-name path)))))))
9523 (setq link (concat type path))
9524 (if (equal desc origpath)
9525 (setq desc path))))
9527 (if org-make-link-description-function
9528 (setq desc (funcall org-make-link-description-function link desc))
9529 (if default-description (setq desc default-description)
9530 (setq desc (or (and auto-desc desc)
9531 (read-string "Description: " desc)))))
9533 (unless (string-match "\\S-" desc) (setq desc nil))
9534 (if remove (apply 'delete-region remove))
9535 (insert (org-make-link-string link desc))))
9537 (defun org-link-try-special-completion (type)
9538 "If there is completion support for link type TYPE, offer it."
9539 (let ((fun (intern (concat "org-" type "-complete-link"))))
9540 (if (functionp fun)
9541 (funcall fun)
9542 (read-string "Link (no completion support): " (concat type ":")))))
9544 (defun org-file-complete-link (&optional arg)
9545 "Create a file link using completion."
9546 (let (file link)
9547 (setq file (read-file-name "File: "))
9548 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9549 (pwd1 (file-name-as-directory (abbreviate-file-name
9550 (expand-file-name ".")))))
9551 (cond
9552 ((equal arg '(16))
9553 (setq link (concat
9554 "file:"
9555 (abbreviate-file-name (expand-file-name file)))))
9556 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9557 (setq link (concat "file:" (match-string 1 file))))
9558 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9559 (expand-file-name file))
9560 (setq link (concat
9561 "file:" (match-string 1 (expand-file-name file)))))
9562 (t (setq link (concat "file:" file)))))
9563 link))
9565 (defun org-completing-read (&rest args)
9566 "Completing-read with SPACE being a normal character."
9567 (let ((enable-recursive-minibuffers t)
9568 (minibuffer-local-completion-map
9569 (copy-keymap minibuffer-local-completion-map)))
9570 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9571 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9572 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9573 (apply 'org-icompleting-read args)))
9575 (defun org-completing-read-no-i (&rest args)
9576 (let (org-completion-use-ido org-completion-use-iswitchb)
9577 (apply 'org-completing-read args)))
9579 (defun org-iswitchb-completing-read (prompt choices &rest args)
9580 "Use iswitch as a completing-read replacement to choose from choices.
9581 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9582 from."
9583 (let* ((iswitchb-use-virtual-buffers nil)
9584 (iswitchb-make-buflist-hook
9585 (lambda ()
9586 (setq iswitchb-temp-buflist choices))))
9587 (iswitchb-read-buffer prompt)))
9589 (defun org-icompleting-read (&rest args)
9590 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9591 (org-without-partial-completion
9592 (if (and org-completion-use-ido
9593 (fboundp 'ido-completing-read)
9594 (boundp 'ido-mode) ido-mode
9595 (listp (second args)))
9596 (let ((ido-enter-matching-directory nil))
9597 (apply 'ido-completing-read (concat (car args))
9598 (if (consp (car (nth 1 args)))
9599 (mapcar 'car (nth 1 args))
9600 (nth 1 args))
9601 (cddr args)))
9602 (if (and org-completion-use-iswitchb
9603 (boundp 'iswitchb-mode) iswitchb-mode
9604 (listp (second args)))
9605 (apply 'org-iswitchb-completing-read (concat (car args))
9606 (if (consp (car (nth 1 args)))
9607 (mapcar 'car (nth 1 args))
9608 (nth 1 args))
9609 (cddr args))
9610 (apply 'completing-read args)))))
9612 (defun org-extract-attributes (s)
9613 "Extract the attributes cookie from a string and set as text property."
9614 (let (a attr (start 0) key value)
9615 (save-match-data
9616 (when (string-match "{{\\([^}]+\\)}}$" s)
9617 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9618 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9619 (setq key (match-string 1 a) value (match-string 2 a)
9620 start (match-end 0)
9621 attr (plist-put attr (intern key) value))))
9622 (org-add-props s nil 'org-attr attr))
9625 (defun org-extract-attributes-from-string (tag)
9626 (let (key value attr)
9627 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9628 (setq key (match-string 1 tag) value (match-string 2 tag)
9629 tag (replace-match "" t t tag)
9630 attr (plist-put attr (intern key) value)))
9631 (cons tag attr)))
9633 (defun org-attributes-to-string (plist)
9634 "Format a property list into an HTML attribute list."
9635 (let ((s "") key value)
9636 (while plist
9637 (setq key (pop plist) value (pop plist))
9638 (and value
9639 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9642 ;;; Opening/following a link
9644 (defvar org-link-search-failed nil)
9646 (defvar org-open-link-functions nil
9647 "Hook for functions finding a plain text link.
9648 These functions must take a single argument, the link content.
9649 They will be called for links that look like [[link text][description]]
9650 when LINK TEXT does not have a protocol like \"http:\" and does not look
9651 like a filename (e.g. \"./blue.png\").
9653 These functions will be called *before* Org attempts to resolve the
9654 link by doing text searches in the current buffer - so if you want a
9655 link \"[[target]]\" to still find \"<<target>>\", your function should
9656 handle this as a special case.
9658 When the function does handle the link, it must return a non-nil value.
9659 If it decides that it is not responsible for this link, it must return
9660 nil to indicate that that Org-mode can continue with other options
9661 like exact and fuzzy text search.")
9663 (defun org-next-link ()
9664 "Move forward to the next link.
9665 If the link is in hidden text, expose it."
9666 (interactive)
9667 (when (and org-link-search-failed (eq this-command last-command))
9668 (goto-char (point-min))
9669 (message "Link search wrapped back to beginning of buffer"))
9670 (setq org-link-search-failed nil)
9671 (let* ((pos (point))
9672 (ct (org-context))
9673 (a (assoc :link ct)))
9674 (if a (goto-char (nth 2 a)))
9675 (if (re-search-forward org-any-link-re nil t)
9676 (progn
9677 (goto-char (match-beginning 0))
9678 (if (outline-invisible-p) (org-show-context)))
9679 (goto-char pos)
9680 (setq org-link-search-failed t)
9681 (error "No further link found"))))
9683 (defun org-previous-link ()
9684 "Move backward to the previous link.
9685 If the link is in hidden text, expose it."
9686 (interactive)
9687 (when (and org-link-search-failed (eq this-command last-command))
9688 (goto-char (point-max))
9689 (message "Link search wrapped back to end of buffer"))
9690 (setq org-link-search-failed nil)
9691 (let* ((pos (point))
9692 (ct (org-context))
9693 (a (assoc :link ct)))
9694 (if a (goto-char (nth 1 a)))
9695 (if (re-search-backward org-any-link-re nil t)
9696 (progn
9697 (goto-char (match-beginning 0))
9698 (if (outline-invisible-p) (org-show-context)))
9699 (goto-char pos)
9700 (setq org-link-search-failed t)
9701 (error "No further link found"))))
9703 (defun org-translate-link (s)
9704 "Translate a link string if a translation function has been defined."
9705 (if (and org-link-translation-function
9706 (fboundp org-link-translation-function)
9707 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9708 (progn
9709 (setq s (funcall org-link-translation-function
9710 (match-string 1 s) (match-string 2 s)))
9711 (concat (car s) ":" (cdr s)))
9714 (defun org-translate-link-from-planner (type path)
9715 "Translate a link from Emacs Planner syntax so that Org can follow it.
9716 This is still an experimental function, your mileage may vary."
9717 (cond
9718 ((member type '("http" "https" "news" "ftp"))
9719 ;; standard Internet links are the same.
9720 nil)
9721 ((and (equal type "irc") (string-match "^//" path))
9722 ;; Planner has two / at the beginning of an irc link, we have 1.
9723 ;; We should have zero, actually....
9724 (setq path (substring path 1)))
9725 ((and (equal type "lisp") (string-match "^/" path))
9726 ;; Planner has a slash, we do not.
9727 (setq type "elisp" path (substring path 1)))
9728 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9729 ;; A typical message link. Planner has the id after the final slash,
9730 ;; we separate it with a hash mark
9731 (setq path (concat (match-string 1 path) "#"
9732 (org-remove-angle-brackets (match-string 2 path)))))
9734 (cons type path))
9736 (defun org-find-file-at-mouse (ev)
9737 "Open file link or URL at mouse."
9738 (interactive "e")
9739 (mouse-set-point ev)
9740 (org-open-at-point 'in-emacs))
9742 (defun org-open-at-mouse (ev)
9743 "Open file link or URL at mouse.
9744 See the docstring of `org-open-file' for details."
9745 (interactive "e")
9746 (mouse-set-point ev)
9747 (if (eq major-mode 'org-agenda-mode)
9748 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9749 (org-open-at-point))
9751 (defvar org-window-config-before-follow-link nil
9752 "The window configuration before following a link.
9753 This is saved in case the need arises to restore it.")
9755 (defvar org-open-link-marker (make-marker)
9756 "Marker pointing to the location where `org-open-at-point; was called.")
9758 ;;;###autoload
9759 (defun org-open-at-point-global ()
9760 "Follow a link like Org-mode does.
9761 This command can be called in any mode to follow a link that has
9762 Org-mode syntax."
9763 (interactive)
9764 (org-run-like-in-org-mode 'org-open-at-point))
9766 ;;;###autoload
9767 (defun org-open-link-from-string (s &optional arg reference-buffer)
9768 "Open a link in the string S, as if it was in Org-mode."
9769 (interactive "sLink: \nP")
9770 (let ((reference-buffer (or reference-buffer (current-buffer))))
9771 (with-temp-buffer
9772 (let ((org-inhibit-startup (not reference-buffer)))
9773 (org-mode)
9774 (insert s)
9775 (goto-char (point-min))
9776 (when reference-buffer
9777 (setq org-link-abbrev-alist-local
9778 (with-current-buffer reference-buffer
9779 org-link-abbrev-alist-local)))
9780 (org-open-at-point arg reference-buffer)))))
9782 (defvar org-open-at-point-functions nil
9783 "Hook that is run when following a link at point.
9785 Functions in this hook must return t if they identify and follow
9786 a link at point. If they don't find anything interesting at point,
9787 they must return nil.")
9789 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9790 (defun org-open-at-point (&optional arg reference-buffer)
9791 "Open link at or after point.
9792 If there is no link at point, this function will search forward up to
9793 the end of the current line.
9794 Normally, files will be opened by an appropriate application. If the
9795 optional prefix argument ARG is non-nil, Emacs will visit the file.
9796 With a double prefix argument, try to open outside of Emacs, in the
9797 application the system uses for this file type."
9798 (interactive "P")
9799 ;; if in a code block, then open the block's results
9800 (unless (call-interactively #'org-babel-open-src-block-result)
9801 (org-load-modules-maybe)
9802 (move-marker org-open-link-marker (point))
9803 (setq org-window-config-before-follow-link (current-window-configuration))
9804 (org-remove-occur-highlights nil nil t)
9805 (cond
9806 ((and (org-at-heading-p)
9807 (not (org-at-timestamp-p t))
9808 (not (org-in-regexp
9809 (concat org-plain-link-re "\\|"
9810 org-bracket-link-regexp "\\|"
9811 org-angle-link-re "\\|"
9812 "[ \t]:[^ \t\n]+:[ \t]*$")))
9813 (not (get-text-property (point) 'org-linked-text)))
9814 (or (org-offer-links-in-entry arg)
9815 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9816 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9817 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9818 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9819 (not (org-in-regexp org-bracket-link-regexp)))
9820 (org-footnote-action))
9822 (let (type path link line search (pos (point)))
9823 (catch 'match
9824 (save-excursion
9825 (skip-chars-forward "^]\n\r")
9826 (when (org-in-regexp org-bracket-link-regexp 1)
9827 (setq link (org-extract-attributes
9828 (org-link-unescape (org-match-string-no-properties 1))))
9829 (while (string-match " *\n *" link)
9830 (setq link (replace-match " " t t link)))
9831 (setq link (org-link-expand-abbrev link))
9832 (cond
9833 ((or (file-name-absolute-p link)
9834 (string-match "^\\.\\.?/" link))
9835 (setq type "file" path link))
9836 ((string-match org-link-re-with-space3 link)
9837 (setq type (match-string 1 link) path (match-string 2 link)))
9838 ((string-match "^help:+\\(.+\\)" link)
9839 (setq type "help" path (match-string 1 link)))
9840 (t (setq type "thisfile" path link)))
9841 (throw 'match t)))
9843 (when (get-text-property (point) 'org-linked-text)
9844 (setq type "thisfile"
9845 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9846 (1+ (point)) (point))
9847 path (buffer-substring
9848 (or (previous-single-property-change pos 'org-linked-text)
9849 (point-min))
9850 (or (next-single-property-change pos 'org-linked-text)
9851 (point-max))))
9852 (throw 'match t))
9854 (save-excursion
9855 (when (or (org-in-regexp org-angle-link-re)
9856 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9857 (save-match-data (not (looking-back "\\[\\[")))))
9858 (setq type (match-string 1)
9859 path (org-link-unescape (match-string 2)))
9860 (throw 'match t)))
9861 (save-excursion
9862 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9863 (setq type "tags"
9864 path (match-string 1))
9865 (while (string-match ":" path)
9866 (setq path (replace-match "+" t t path)))
9867 (throw 'match t)))
9868 (when (org-in-regexp "<\\([^><\n]+\\)>")
9869 (setq type "tree-match"
9870 path (match-string 1))
9871 (throw 'match t)))
9872 (unless path
9873 (error "No link found"))
9875 ;; switch back to reference buffer
9876 ;; needed when if called in a temporary buffer through
9877 ;; org-open-link-from-string
9878 (with-current-buffer (or reference-buffer (current-buffer))
9880 ;; Remove any trailing spaces in path
9881 (if (string-match " +\\'" path)
9882 (setq path (replace-match "" t t path)))
9883 (if (and org-link-translation-function
9884 (fboundp org-link-translation-function))
9885 ;; Check if we need to translate the link
9886 (let ((tmp (funcall org-link-translation-function type path)))
9887 (setq type (car tmp) path (cdr tmp))))
9889 (cond
9891 ((assoc type org-link-protocols)
9892 (funcall (nth 1 (assoc type org-link-protocols)) path))
9894 ((equal type "help")
9895 (let ((f-or-v (intern path)))
9896 (cond ((fboundp f-or-v)
9897 (describe-function f-or-v))
9898 ((boundp f-or-v)
9899 (describe-variable f-or-v))
9900 (t (error "Not a known function or variable")))))
9902 ((equal type "mailto")
9903 (let ((cmd (car org-link-mailto-program))
9904 (args (cdr org-link-mailto-program)) args1
9905 (address path) (subject "") a)
9906 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9907 (setq address (match-string 1 path)
9908 subject (org-link-escape (match-string 2 path))))
9909 (while args
9910 (cond
9911 ((not (stringp (car args))) (push (pop args) args1))
9912 (t (setq a (pop args))
9913 (if (string-match "%a" a)
9914 (setq a (replace-match address t t a)))
9915 (if (string-match "%s" a)
9916 (setq a (replace-match subject t t a)))
9917 (push a args1))))
9918 (apply cmd (nreverse args1))))
9920 ((member type '("http" "https" "ftp" "news"))
9921 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9922 (org-link-escape
9923 path org-link-escape-chars-browser)
9924 path))))
9926 ((string= type "doi")
9927 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9928 (org-link-escape
9929 path org-link-escape-chars-browser)
9930 path))))
9932 ((member type '("message"))
9933 (browse-url (concat type ":" path)))
9935 ((string= type "tags")
9936 (org-tags-view arg path))
9938 ((string= type "tree-match")
9939 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9941 ((string= type "file")
9942 (if (string-match "::\\([0-9]+\\)\\'" path)
9943 (setq line (string-to-number (match-string 1 path))
9944 path (substring path 0 (match-beginning 0)))
9945 (if (string-match "::\\(.+\\)\\'" path)
9946 (setq search (match-string 1 path)
9947 path (substring path 0 (match-beginning 0)))))
9948 (if (string-match "[*?{]" (file-name-nondirectory path))
9949 (dired path)
9950 (org-open-file path arg line search)))
9952 ((string= type "shell")
9953 (let ((buf (generate-new-buffer "*Org Shell Output"))
9954 (cmd path))
9955 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9956 (string-match org-confirm-shell-link-not-regexp cmd))
9957 (not org-confirm-shell-link-function)
9958 (funcall org-confirm-shell-link-function
9959 (format "Execute \"%s\" in shell? "
9960 (org-add-props cmd nil
9961 'face 'org-warning))))
9962 (progn
9963 (message "Executing %s" cmd)
9964 (shell-command cmd buf)
9965 (if (featurep 'midnight)
9966 (setq clean-buffer-list-kill-buffer-names
9967 (cons buf clean-buffer-list-kill-buffer-names))))
9968 (error "Abort"))))
9970 ((string= type "elisp")
9971 (let ((cmd path))
9972 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9973 (string-match org-confirm-elisp-link-not-regexp cmd))
9974 (not org-confirm-elisp-link-function)
9975 (funcall org-confirm-elisp-link-function
9976 (format "Execute \"%s\" as elisp? "
9977 (org-add-props cmd nil
9978 'face 'org-warning))))
9979 (message "%s => %s" cmd
9980 (if (equal (string-to-char cmd) ?\()
9981 (eval (read cmd))
9982 (call-interactively (read cmd))))
9983 (error "Abort"))))
9985 ((and (string= type "thisfile")
9986 (run-hook-with-args-until-success
9987 'org-open-link-functions path)))
9989 ((string= type "thisfile")
9990 (if arg
9991 (switch-to-buffer-other-window
9992 (org-get-buffer-for-internal-link (current-buffer)))
9993 (org-mark-ring-push))
9994 (let ((cmd `(org-link-search
9995 ,path
9996 ,(cond ((equal arg '(4)) ''occur)
9997 ((equal arg '(16)) ''org-occur))
9998 ,pos)))
9999 (condition-case nil (let ((org-link-search-inhibit-query t))
10000 (eval cmd))
10001 (error (progn (widen) (eval cmd))))))
10003 (t (browse-url-at-point)))))))
10004 (move-marker org-open-link-marker nil)
10005 (run-hook-with-args 'org-follow-link-hook)))
10007 (defun org-offer-links-in-entry (&optional nth zero)
10008 "Offer links in the current entry and follow the selected link.
10009 If there is only one link, follow it immediately as well.
10010 If NTH is an integer, immediately pick the NTH link found.
10011 If ZERO is a string, check also this string for a link, and if
10012 there is one, offer it as link number zero."
10013 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10014 "\\(" org-angle-link-re "\\)\\|"
10015 "\\(" org-plain-link-re "\\)"))
10016 (cnt ?0)
10017 (in-emacs (if (integerp nth) nil nth))
10018 have-zero end links link c)
10019 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10020 (push (match-string 0 zero) links)
10021 (setq cnt (1- cnt) have-zero t))
10022 (save-excursion
10023 (org-back-to-heading t)
10024 (setq end (save-excursion (outline-next-heading) (point)))
10025 (while (re-search-forward re end t)
10026 (push (match-string 0) links))
10027 (setq links (org-uniquify (reverse links))))
10029 (cond
10030 ((null links)
10031 (message "No links"))
10032 ((equal (length links) 1)
10033 (setq link (list (car links))))
10034 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10035 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10036 (t ; we have to select a link
10037 (save-excursion
10038 (save-window-excursion
10039 (delete-other-windows)
10040 (with-output-to-temp-buffer "*Select Link*"
10041 (mapc (lambda (l)
10042 (if (not (string-match org-bracket-link-regexp l))
10043 (princ (format "[%c] %s\n" (incf cnt)
10044 (org-remove-angle-brackets l)))
10045 (if (match-end 3)
10046 (princ (format "[%c] %s (%s)\n" (incf cnt)
10047 (match-string 3 l) (match-string 1 l)))
10048 (princ (format "[%c] %s\n" (incf cnt)
10049 (match-string 1 l))))))
10050 links))
10051 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10052 (message "Select link to open, RET to open all:")
10053 (setq c (read-char-exclusive))
10054 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10055 (when (equal c ?q) (error "Abort"))
10056 (if (equal c ?\C-m)
10057 (setq link links)
10058 (setq nth (- c ?0))
10059 (if have-zero (setq nth (1+ nth)))
10060 (unless (and (integerp nth) (>= (length links) nth))
10061 (error "Invalid link selection"))
10062 (setq link (list (nth (1- nth) links))))))
10063 (if link
10064 (let ((buf (current-buffer)))
10065 (dolist (l link)
10066 (org-open-link-from-string l in-emacs buf))
10068 nil)))
10070 ;; Add special file links that specify the way of opening
10072 (org-add-link-type "file+sys" 'org-open-file-with-system)
10073 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10074 (defun org-open-file-with-system (path)
10075 "Open file at PATH using the system way of opening it."
10076 (org-open-file path 'system))
10077 (defun org-open-file-with-emacs (path)
10078 "Open file at PATH in Emacs."
10079 (org-open-file path 'emacs))
10080 (defun org-remove-file-link-modifiers ()
10081 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10082 (goto-char (point-min))
10083 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10084 (org-if-unprotected
10085 (replace-match "file:" t t))))
10086 (eval-after-load "org-exp"
10087 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10088 'org-remove-file-link-modifiers))
10090 ;;;; Time estimates
10092 (defun org-get-effort (&optional pom)
10093 "Get the effort estimate for the current entry."
10094 (org-entry-get pom org-effort-property))
10096 ;;; File search
10098 (defvar org-create-file-search-functions nil
10099 "List of functions to construct the right search string for a file link.
10100 These functions are called in turn with point at the location to
10101 which the link should point.
10103 A function in the hook should first test if it would like to
10104 handle this file type, for example by checking the `major-mode'
10105 or the file extension. If it decides not to handle this file, it
10106 should just return nil to give other functions a chance. If it
10107 does handle the file, it must return the search string to be used
10108 when following the link. The search string will be part of the
10109 file link, given after a double colon, and `org-open-at-point'
10110 will automatically search for it. If special measures must be
10111 taken to make the search successful, another function should be
10112 added to the companion hook `org-execute-file-search-functions',
10113 which see.
10115 A function in this hook may also use `setq' to set the variable
10116 `description' to provide a suggestion for the descriptive text to
10117 be used for this link when it gets inserted into an Org-mode
10118 buffer with \\[org-insert-link].")
10120 (defvar org-execute-file-search-functions nil
10121 "List of functions to execute a file search triggered by a link.
10123 Functions added to this hook must accept a single argument, the
10124 search string that was part of the file link, the part after the
10125 double colon. The function must first check if it would like to
10126 handle this search, for example by checking the `major-mode' or
10127 the file extension. If it decides not to handle this search, it
10128 should just return nil to give other functions a chance. If it
10129 does handle the search, it must return a non-nil value to keep
10130 other functions from trying.
10132 Each function can access the current prefix argument through the
10133 variable `current-prefix-argument'. Note that a single prefix is
10134 used to force opening a link in Emacs, so it may be good to only
10135 use a numeric or double prefix to guide the search function.
10137 In case this is needed, a function in this hook can also restore
10138 the window configuration before `org-open-at-point' was called using:
10140 (set-window-configuration org-window-config-before-follow-link)")
10142 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10143 (defun org-link-search (s &optional type avoid-pos stealth)
10144 "Search for a link search option.
10145 If S is surrounded by forward slashes, it is interpreted as a
10146 regular expression. In org-mode files, this will create an `org-occur'
10147 sparse tree. In ordinary files, `occur' will be used to list matches.
10148 If the current buffer is in `dired-mode', grep will be used to search
10149 in all files. If AVOID-POS is given, ignore matches near that position.
10151 When optional argument STEALTH is non-nil, do not modify
10152 visibility around point, thus ignoring
10153 `org-show-hierarchy-above', `org-show-following-heading' and
10154 `org-show-siblings' variables."
10155 (let ((case-fold-search t)
10156 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10157 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10158 (append '(("") (" ") ("\t") ("\n"))
10159 org-emphasis-alist)
10160 "\\|") "\\)"))
10161 (pos (point))
10162 (pre nil) (post nil)
10163 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10164 (cond
10165 ;; First check if there are any special search functions
10166 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10167 ;; Now try the builtin stuff
10168 ((and (equal (string-to-char s0) ?#)
10169 (> (length s0) 1)
10170 (save-excursion
10171 (goto-char (point-min))
10172 (and
10173 (re-search-forward
10174 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10175 (setq type 'dedicated
10176 pos (match-beginning 0))))
10177 ;; There is an exact target for this
10178 (goto-char pos)
10179 (org-back-to-heading t)))
10180 ((save-excursion
10181 (goto-char (point-min))
10182 (and
10183 (re-search-forward
10184 (concat "<<" (regexp-quote s0) ">>") nil t)
10185 (setq type 'dedicated
10186 pos (match-beginning 0))))
10187 ;; There is an exact target for this
10188 (goto-char pos))
10189 ((save-excursion
10190 (goto-char (point-min))
10191 (and
10192 (re-search-forward
10193 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10194 (setq type 'dedicated pos (match-beginning 0))))
10195 ;; Found an invisible target.
10196 (goto-char pos))
10197 ((save-excursion
10198 (goto-char (point-min))
10199 (and
10200 (re-search-forward
10201 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10202 (setq type 'dedicated pos (match-beginning 0))))
10203 ;; Found an element with a matching #+name affiliated keyword.
10204 (goto-char pos))
10205 ((and (string-match "^(\\(.*\\))$" s0)
10206 (save-excursion
10207 (goto-char (point-min))
10208 (and
10209 (re-search-forward
10210 (concat "[^[]" (regexp-quote
10211 (format org-coderef-label-format
10212 (match-string 1 s0))))
10213 nil t)
10214 (setq type 'dedicated
10215 pos (1+ (match-beginning 0))))))
10216 ;; There is a coderef target for this
10217 (goto-char pos))
10218 ((string-match "^/\\(.*\\)/$" s)
10219 ;; A regular expression
10220 (cond
10221 ((derived-mode-p 'org-mode)
10222 (org-occur (match-string 1 s)))
10223 ;;((eq major-mode 'dired-mode)
10224 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10225 (t (org-do-occur (match-string 1 s)))))
10226 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10227 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10228 (goto-char (point-min))
10229 (cond
10230 ((let (case-fold-search)
10231 (re-search-forward (format org-complex-heading-regexp-format
10232 (regexp-quote s))
10233 nil t))
10234 ;; OK, found a match
10235 (setq type 'dedicated)
10236 (goto-char (match-beginning 0)))
10237 ((and (not org-link-search-inhibit-query)
10238 (eq org-link-search-must-match-exact-headline 'query-to-create)
10239 (y-or-n-p "No match - create this as a new heading? "))
10240 (goto-char (point-max))
10241 (or (bolp) (newline))
10242 (insert "* " s "\n")
10243 (beginning-of-line 0))
10245 (goto-char pos)
10246 (error "No match"))))
10248 ;; A normal search string
10249 (when (equal (string-to-char s) ?*)
10250 ;; Anchor on headlines, post may include tags.
10251 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10252 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10253 s (substring s 1)))
10254 (remove-text-properties
10255 0 (length s)
10256 '(face nil mouse-face nil keymap nil fontified nil) s)
10257 ;; Make a series of regular expressions to find a match
10258 (setq words (org-split-string s "[ \n\r\t]+")
10260 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10261 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10262 "\\)" markers)
10263 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10264 re2a (concat "[ \t\r\n]" re2a_)
10265 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10266 re4 (concat "[^a-zA-Z_]" re4_)
10268 re1 (concat pre re2 post)
10269 re3 (concat pre (if pre re4_ re4) post)
10270 re5 (concat pre ".*" re4)
10271 re2 (concat pre re2)
10272 re2a (concat pre (if pre re2a_ re2a))
10273 re4 (concat pre (if pre re4_ re4))
10274 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10275 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10276 re5 "\\)"
10278 (cond
10279 ((eq type 'org-occur) (org-occur reall))
10280 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10281 (t (goto-char (point-min))
10282 (setq type 'fuzzy)
10283 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10284 (org-search-not-self 1 re1 nil t)
10285 (org-search-not-self 1 re2 nil t)
10286 (org-search-not-self 1 re2a nil t)
10287 (org-search-not-self 1 re3 nil t)
10288 (org-search-not-self 1 re4 nil t)
10289 (org-search-not-self 1 re5 nil t)
10291 (goto-char (match-beginning 1))
10292 (goto-char pos)
10293 (error "No match"))))))
10294 (and (derived-mode-p 'org-mode)
10295 (not stealth)
10296 (org-show-context 'link-search))
10297 type))
10299 (defun org-search-not-self (group &rest args)
10300 "Execute `re-search-forward', but only accept matches that do not
10301 enclose the position of `org-open-link-marker'."
10302 (let ((m org-open-link-marker))
10303 (catch 'exit
10304 (while (apply 're-search-forward args)
10305 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10306 (goto-char (match-end group))
10307 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10308 (> (match-beginning 0) (marker-position m))
10309 (< (match-end 0) (marker-position m)))
10310 (save-match-data
10311 (or (not (org-in-regexp
10312 org-bracket-link-analytic-regexp 1))
10313 (not (match-end 4)) ; no description
10314 (and (<= (match-beginning 4) (point))
10315 (>= (match-end 4) (point))))))
10316 (throw 'exit (point))))))))
10318 (defun org-get-buffer-for-internal-link (buffer)
10319 "Return a buffer to be used for displaying the link target of internal links."
10320 (cond
10321 ((not org-display-internal-link-with-indirect-buffer)
10322 buffer)
10323 ((string-match "(Clone)$" (buffer-name buffer))
10324 (message "Buffer is already a clone, not making another one")
10325 ;; we also do not modify visibility in this case
10326 buffer)
10327 (t ; make a new indirect buffer for displaying the link
10328 (let* ((bn (buffer-name buffer))
10329 (ibn (concat bn "(Clone)"))
10330 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10331 (with-current-buffer ib (org-overview))
10332 ib))))
10334 (defun org-do-occur (regexp &optional cleanup)
10335 "Call the Emacs command `occur'.
10336 If CLEANUP is non-nil, remove the printout of the regular expression
10337 in the *Occur* buffer. This is useful if the regex is long and not useful
10338 to read."
10339 (occur regexp)
10340 (when cleanup
10341 (let ((cwin (selected-window)) win beg end)
10342 (when (setq win (get-buffer-window "*Occur*"))
10343 (select-window win))
10344 (goto-char (point-min))
10345 (when (re-search-forward "match[a-z]+" nil t)
10346 (setq beg (match-end 0))
10347 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10348 (setq end (1- (match-beginning 0)))))
10349 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10350 (goto-char (point-min))
10351 (select-window cwin))))
10353 ;;; The mark ring for links jumps
10355 (defvar org-mark-ring nil
10356 "Mark ring for positions before jumps in Org-mode.")
10357 (defvar org-mark-ring-last-goto nil
10358 "Last position in the mark ring used to go back.")
10359 ;; Fill and close the ring
10360 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10361 (loop for i from 1 to org-mark-ring-length do
10362 (push (make-marker) org-mark-ring))
10363 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10364 org-mark-ring)
10366 (defun org-mark-ring-push (&optional pos buffer)
10367 "Put the current position or POS into the mark ring and rotate it."
10368 (interactive)
10369 (setq pos (or pos (point)))
10370 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10371 (move-marker (car org-mark-ring)
10372 (or pos (point))
10373 (or buffer (current-buffer)))
10374 (message "%s"
10375 (substitute-command-keys
10376 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10378 (defun org-mark-ring-goto (&optional n)
10379 "Jump to the previous position in the mark ring.
10380 With prefix arg N, jump back that many stored positions. When
10381 called several times in succession, walk through the entire ring.
10382 Org-mode commands jumping to a different position in the current file,
10383 or to another Org-mode file, automatically push the old position
10384 onto the ring."
10385 (interactive "p")
10386 (let (p m)
10387 (if (eq last-command this-command)
10388 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10389 (setq p org-mark-ring))
10390 (setq org-mark-ring-last-goto p)
10391 (setq m (car p))
10392 (org-pop-to-buffer-same-window (marker-buffer m))
10393 (goto-char m)
10394 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10396 (defun org-remove-angle-brackets (s)
10397 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10398 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10400 (defun org-add-angle-brackets (s)
10401 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10402 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10404 (defun org-remove-double-quotes (s)
10405 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10406 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10409 ;;; Following specific links
10411 (defun org-follow-timestamp-link ()
10412 (cond
10413 ((org-at-date-range-p t)
10414 (let ((org-agenda-start-on-weekday)
10415 (t1 (match-string 1))
10416 (t2 (match-string 2)))
10417 (setq t1 (time-to-days (org-time-string-to-time t1))
10418 t2 (time-to-days (org-time-string-to-time t2)))
10419 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10420 ((org-at-timestamp-p t)
10421 (org-agenda-list nil (time-to-days (org-time-string-to-time
10422 (substring (match-string 1) 0 10)))
10424 (t (error "This should not happen"))))
10427 ;;; Following file links
10428 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10429 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10430 (declare-function mailcap-mime-info
10431 "mailcap" (string &optional request no-decode))
10432 (defvar org-wait nil)
10433 (defun org-open-file (path &optional in-emacs line search)
10434 "Open the file at PATH.
10435 First, this expands any special file name abbreviations. Then the
10436 configuration variable `org-file-apps' is checked if it contains an
10437 entry for this file type, and if yes, the corresponding command is launched.
10439 If no application is found, Emacs simply visits the file.
10441 With optional prefix argument IN-EMACS, Emacs will visit the file.
10442 With a double \\[universal-argument] \\[universal-argument] \
10443 prefix arg, Org tries to avoid opening in Emacs
10444 and to use an external application to visit the file.
10446 Optional LINE specifies a line to go to, optional SEARCH a string
10447 to search for. If LINE or SEARCH is given, the file will be
10448 opened in Emacs, unless an entry from org-file-apps that makes
10449 use of groups in a regexp matches.
10451 If you want to change the way frames are used when following a
10452 link, please customize `org-link-frame-setup'.
10454 If the file does not exist, an error is thrown."
10455 (let* ((file (if (equal path "")
10456 buffer-file-name
10457 (substitute-in-file-name (expand-file-name path))))
10458 (file-apps (append org-file-apps (org-default-apps)))
10459 (apps (org-remove-if
10460 'org-file-apps-entry-match-against-dlink-p file-apps))
10461 (apps-dlink (org-remove-if-not
10462 'org-file-apps-entry-match-against-dlink-p file-apps))
10463 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10464 (dirp (if remp nil (file-directory-p file)))
10465 (file (if (and dirp org-open-directory-means-index-dot-org)
10466 (concat (file-name-as-directory file) "index.org")
10467 file))
10468 (a-m-a-p (assq 'auto-mode apps))
10469 (dfile (downcase file))
10470 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10471 (link (cond ((and (eq line nil)
10472 (eq search nil))
10473 file)
10474 (line
10475 (concat file "::" (number-to-string line)))
10476 (search
10477 (concat file "::" search))))
10478 (dlink (downcase link))
10479 (old-buffer (current-buffer))
10480 (old-pos (point))
10481 (old-mode major-mode)
10482 ext cmd link-match-data)
10483 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10484 (setq ext (match-string 1 dfile))
10485 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10486 (setq ext (match-string 1 dfile))))
10487 (cond
10488 ((member in-emacs '((16) system))
10489 (setq cmd (cdr (assoc 'system apps))))
10490 (in-emacs (setq cmd 'emacs))
10492 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10493 (and dirp (cdr (assoc 'directory apps)))
10494 ; first, try matching against apps-dlink
10495 ; if we get a match here, store the match data for later
10496 (let ((match (assoc-default dlink apps-dlink
10497 'string-match)))
10498 (if match
10499 (progn (setq link-match-data (match-data))
10500 match)
10501 (progn (setq in-emacs (or in-emacs line search))
10502 nil))) ; if we have no match in apps-dlink,
10503 ; always open the file in emacs if line or search
10504 ; is given (for backwards compatibility)
10505 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10506 'string-match)
10507 (cdr (assoc ext apps))
10508 (cdr (assoc t apps))))))
10509 (when (eq cmd 'system)
10510 (setq cmd (cdr (assoc 'system apps))))
10511 (when (eq cmd 'default)
10512 (setq cmd (cdr (assoc t apps))))
10513 (when (eq cmd 'mailcap)
10514 (require 'mailcap)
10515 (mailcap-parse-mailcaps)
10516 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10517 (command (mailcap-mime-info mime-type)))
10518 (if (stringp command)
10519 (setq cmd command)
10520 (setq cmd 'emacs))))
10521 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10522 (not (file-exists-p file))
10523 (not org-open-non-existing-files))
10524 (error "No such file: %s" file))
10525 (cond
10526 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10527 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10528 (while (string-match "['\"]%s['\"]" cmd)
10529 (setq cmd (replace-match "%s" t t cmd)))
10530 (while (string-match "%s" cmd)
10531 (setq cmd (replace-match
10532 (save-match-data
10533 (shell-quote-argument
10534 (convert-standard-filename file)))
10535 t t cmd)))
10537 ;; Replace "%1", "%2" etc. in command with group matches from regex
10538 (save-match-data
10539 (let ((match-index 1)
10540 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10541 (set-match-data link-match-data)
10542 (while (<= match-index number-of-groups)
10543 (let ((regex (concat "%" (number-to-string match-index)))
10544 (replace-with (match-string match-index dlink)))
10545 (while (string-match regex cmd)
10546 (setq cmd (replace-match replace-with t t cmd))))
10547 (setq match-index (+ match-index 1)))))
10549 (save-window-excursion
10550 (message "Running %s...done" cmd)
10551 (start-process-shell-command cmd nil cmd)
10552 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10553 ((or (stringp cmd)
10554 (eq cmd 'emacs))
10555 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10556 (widen)
10557 (if line (org-goto-line line)
10558 (if search (org-link-search search))))
10559 ((consp cmd)
10560 (let ((file (convert-standard-filename file)))
10561 (save-match-data
10562 (set-match-data link-match-data)
10563 (eval cmd))))
10564 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10565 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10566 (or (not (equal old-buffer (current-buffer)))
10567 (not (equal old-pos (point))))
10568 (org-mark-ring-push old-pos old-buffer))))
10570 (defun org-file-apps-entry-match-against-dlink-p (entry)
10571 "This function returns non-nil if `entry' uses a regular
10572 expression which should be matched against the whole link by
10573 org-open-file.
10575 It assumes that is the case when the entry uses a regular
10576 expression which has at least one grouping construct and the
10577 action is either a lisp form or a command string containing
10578 '%1', i.e. using at least one subexpression match as a
10579 parameter."
10580 (let ((selector (car entry))
10581 (action (cdr entry)))
10582 (if (stringp selector)
10583 (and (> (regexp-opt-depth selector) 0)
10584 (or (and (stringp action)
10585 (string-match "%[0-9]" action))
10586 (consp action)))
10587 nil)))
10589 (defun org-default-apps ()
10590 "Return the default applications for this operating system."
10591 (cond
10592 ((eq system-type 'darwin)
10593 org-file-apps-defaults-macosx)
10594 ((eq system-type 'windows-nt)
10595 org-file-apps-defaults-windowsnt)
10596 (t org-file-apps-defaults-gnu)))
10598 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10599 "Convert extensions to regular expressions in the cars of LIST.
10600 Also, weed out any non-string entries, because the return value is used
10601 only for regexp matching.
10602 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10603 point to the symbol `emacs', indicating that the file should
10604 be opened in Emacs."
10605 (append
10606 (delq nil
10607 (mapcar (lambda (x)
10608 (if (not (stringp (car x)))
10610 (if (string-match "\\W" (car x))
10612 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10613 list))
10614 (if add-auto-mode
10615 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10617 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10618 (defun org-file-remote-p (file)
10619 "Test whether FILE specifies a location on a remote system.
10620 Return non-nil if the location is indeed remote.
10622 For example, the filename \"/user@host:/foo\" specifies a location
10623 on the system \"/user@host:\"."
10624 (cond ((fboundp 'file-remote-p)
10625 (file-remote-p file))
10626 ((fboundp 'tramp-handle-file-remote-p)
10627 (tramp-handle-file-remote-p file))
10628 ((and (boundp 'ange-ftp-name-format)
10629 (string-match (car ange-ftp-name-format) file))
10630 t)))
10633 ;;;; Refiling
10635 (defun org-get-org-file ()
10636 "Read a filename, with default directory `org-directory'."
10637 (let ((default (or org-default-notes-file remember-data-file)))
10638 (read-file-name (format "File name [%s]: " default)
10639 (file-name-as-directory org-directory)
10640 default)))
10642 (defun org-notes-order-reversed-p ()
10643 "Check if the current file should receive notes in reversed order."
10644 (cond
10645 ((not org-reverse-note-order) nil)
10646 ((eq t org-reverse-note-order) t)
10647 ((not (listp org-reverse-note-order)) nil)
10648 (t (catch 'exit
10649 (let ((all org-reverse-note-order)
10650 entry)
10651 (while (setq entry (pop all))
10652 (if (string-match (car entry) buffer-file-name)
10653 (throw 'exit (cdr entry))))
10654 nil)))))
10656 (defvar org-refile-target-table nil
10657 "The list of refile targets, created by `org-refile'.")
10659 (defvar org-agenda-new-buffers nil
10660 "Buffers created to visit agenda files.")
10662 (defvar org-refile-cache nil
10663 "Cache for refile targets.")
10665 (defvar org-refile-markers nil
10666 "All the markers used for caching refile locations.")
10668 (defun org-refile-marker (pos)
10669 "Get a new refile marker, but only if caching is in use."
10670 (if (not org-refile-use-cache)
10672 (let ((m (make-marker)))
10673 (move-marker m pos)
10674 (push m org-refile-markers)
10675 m)))
10677 (defun org-refile-cache-clear ()
10678 "Clear the refile cache and disable all the markers."
10679 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10680 (setq org-refile-markers nil)
10681 (setq org-refile-cache nil)
10682 (message "Refile cache has been cleared"))
10684 (defun org-refile-cache-check-set (set)
10685 "Check if all the markers in the cache still have live buffers."
10686 (let (marker)
10687 (catch 'exit
10688 (while (and set (setq marker (nth 3 (pop set))))
10689 ;; if org-refile-use-outline-path is 'file, marker may be nil
10690 (when (and marker (null (marker-buffer marker)))
10691 (message "not found") (sit-for 3)
10692 (throw 'exit nil)))
10693 t)))
10695 (defun org-refile-cache-put (set &rest identifiers)
10696 "Push the refile targets SET into the cache, under IDENTIFIERS."
10697 (let* ((key (sha1 (prin1-to-string identifiers)))
10698 (entry (assoc key org-refile-cache)))
10699 (if entry
10700 (setcdr entry set)
10701 (push (cons key set) org-refile-cache))))
10703 (defun org-refile-cache-get (&rest identifiers)
10704 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10705 (cond
10706 ((not org-refile-cache) nil)
10707 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10709 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10710 org-refile-cache))))
10711 (and set (org-refile-cache-check-set set) set)))))
10713 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10714 "Produce a table with refile targets."
10715 (let ((case-fold-search nil)
10716 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10717 (entries (or org-refile-targets '((nil . (:level . 1)))))
10718 targets tgs txt re files f desc descre fast-path-p level pos0)
10719 (message "Getting targets...")
10720 (with-current-buffer (or default-buffer (current-buffer))
10721 (while (setq entry (pop entries))
10722 (setq files (car entry) desc (cdr entry))
10723 (setq fast-path-p nil)
10724 (cond
10725 ((null files) (setq files (list (current-buffer))))
10726 ((eq files 'org-agenda-files)
10727 (setq files (org-agenda-files 'unrestricted)))
10728 ((and (symbolp files) (fboundp files))
10729 (setq files (funcall files)))
10730 ((and (symbolp files) (boundp files))
10731 (setq files (symbol-value files))))
10732 (if (stringp files) (setq files (list files)))
10733 (cond
10734 ((eq (car desc) :tag)
10735 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10736 ((eq (car desc) :todo)
10737 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10738 ((eq (car desc) :regexp)
10739 (setq descre (cdr desc)))
10740 ((eq (car desc) :level)
10741 (setq descre (concat "^\\*\\{" (number-to-string
10742 (if org-odd-levels-only
10743 (1- (* 2 (cdr desc)))
10744 (cdr desc)))
10745 "\\}[ \t]")))
10746 ((eq (car desc) :maxlevel)
10747 (setq fast-path-p t)
10748 (setq descre (concat "^\\*\\{1," (number-to-string
10749 (if org-odd-levels-only
10750 (1- (* 2 (cdr desc)))
10751 (cdr desc)))
10752 "\\}[ \t]")))
10753 (t (error "Bad refiling target description %s" desc)))
10754 (while (setq f (pop files))
10755 (with-current-buffer
10756 (if (bufferp f) f (org-get-agenda-file-buffer f))
10758 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10759 (progn
10760 (if (bufferp f) (setq f (buffer-file-name
10761 (buffer-base-buffer f))))
10762 (setq f (and f (expand-file-name f)))
10763 (if (eq org-refile-use-outline-path 'file)
10764 (push (list (file-name-nondirectory f) f nil nil) tgs))
10765 (save-excursion
10766 (save-restriction
10767 (widen)
10768 (goto-char (point-min))
10769 (while (re-search-forward descre nil t)
10770 (goto-char (setq pos0 (point-at-bol)))
10771 (catch 'next
10772 (when org-refile-target-verify-function
10773 (save-match-data
10774 (or (funcall org-refile-target-verify-function)
10775 (throw 'next t))))
10776 (when (and (looking-at org-complex-heading-regexp)
10777 (not (member (match-string 4) excluded-entries))
10778 (match-string 4))
10779 (setq level (org-reduced-level
10780 (- (match-end 1) (match-beginning 1)))
10781 txt (org-link-display-format (match-string 4))
10782 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10783 re (format org-complex-heading-regexp-format
10784 (regexp-quote (match-string 4))))
10785 (when org-refile-use-outline-path
10786 (setq txt (mapconcat
10787 'org-protect-slash
10788 (append
10789 (if (eq org-refile-use-outline-path
10790 'file)
10791 (list (file-name-nondirectory
10792 (buffer-file-name
10793 (buffer-base-buffer))))
10794 (if (eq org-refile-use-outline-path
10795 'full-file-path)
10796 (list (buffer-file-name
10797 (buffer-base-buffer)))))
10798 (org-get-outline-path fast-path-p
10799 level txt)
10800 (list txt))
10801 "/")))
10802 (push (list txt f re (org-refile-marker (point)))
10803 tgs)))
10804 (when (= (point) pos0)
10805 ;; verification function has not moved point
10806 (goto-char (point-at-eol))))))))
10807 (when org-refile-use-cache
10808 (org-refile-cache-put tgs (buffer-file-name) descre))
10809 (setq targets (append tgs targets))
10810 ))))
10811 (message "Getting targets...done")
10812 (nreverse targets)))
10814 (defun org-protect-slash (s)
10815 (while (string-match "/" s)
10816 (setq s (replace-match "\\" t t s)))
10819 (defvar org-olpa (make-vector 20 nil))
10821 (defun org-get-outline-path (&optional fastp level heading)
10822 "Return the outline path to the current entry, as a list.
10824 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10825 routine which makes outline path derivations for an entire file,
10826 avoiding backtracing. Refile target collection makes use of that."
10827 (if fastp
10828 (progn
10829 (if (> level 19)
10830 (error "Outline path failure, more than 19 levels"))
10831 (loop for i from level upto 19 do
10832 (aset org-olpa i nil))
10833 (prog1
10834 (delq nil (append org-olpa nil))
10835 (aset org-olpa level heading)))
10836 (let (rtn case-fold-search)
10837 (save-excursion
10838 (save-restriction
10839 (widen)
10840 (while (org-up-heading-safe)
10841 (when (looking-at org-complex-heading-regexp)
10842 (push (org-match-string-no-properties 4) rtn)))
10843 rtn)))))
10845 (defun org-format-outline-path (path &optional width prefix)
10846 "Format the outline path PATH for display.
10847 Width is the maximum number of characters that is available.
10848 Prefix is a prefix to be included in the returned string,
10849 such as the file name."
10850 (setq width (or width 79))
10851 (if prefix (setq width (- width (length prefix))))
10852 (if (not path)
10853 (or prefix "")
10854 (let* ((nsteps (length path))
10855 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10856 (maxwidth (if (<= total-width width)
10857 10000 ;; everything fits
10858 ;; we need to shorten the level headings
10859 (/ (- width nsteps) nsteps)))
10860 (org-odd-levels-only nil)
10861 (n 0)
10862 (total (1+ (length prefix))))
10863 (setq maxwidth (max maxwidth 10))
10864 (concat prefix
10865 (mapconcat
10866 (lambda (h)
10867 (setq n (1+ n))
10868 (if (and (= n nsteps) (< maxwidth 10000))
10869 (setq maxwidth (- total-width total)))
10870 (if (< (length h) maxwidth)
10871 (progn (setq total (+ total (length h) 1)) h)
10872 (setq h (substring h 0 (- maxwidth 2))
10873 total (+ total maxwidth 1))
10874 (if (string-match "[ \t]+\\'" h)
10875 (setq h (substring h 0 (match-beginning 0))))
10876 (setq h (concat h "..")))
10877 (org-add-props h nil 'face
10878 (nth (% (1- n) org-n-level-faces)
10879 org-level-faces))
10881 path "/")))))
10883 (defun org-display-outline-path (&optional file current)
10884 "Display the current outline path in the echo area."
10885 (interactive "P")
10886 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10887 (case-fold-search nil)
10888 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10889 (if current (setq path (append path
10890 (save-excursion
10891 (org-back-to-heading t)
10892 (if (looking-at org-complex-heading-regexp)
10893 (list (match-string 4)))))))
10894 (message "%s"
10895 (org-format-outline-path
10896 path
10897 (1- (frame-width))
10898 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10900 (defvar org-refile-history nil
10901 "History for refiling operations.")
10903 (defvar org-after-refile-insert-hook nil
10904 "Hook run after `org-refile' has inserted its stuff at the new location.
10905 Note that this is still *before* the stuff will be removed from
10906 the *old* location.")
10908 (defvar org-capture-last-stored-marker)
10909 (defun org-refile (&optional goto default-buffer rfloc)
10910 "Move the entry or entries at point to another heading.
10911 The list of target headings is compiled using the information in
10912 `org-refile-targets', which see.
10914 At the target location, the entry is filed as a subitem of the target
10915 heading. Depending on `org-reverse-note-order', the new subitem will
10916 either be the first or the last subitem.
10918 If there is an active region, all entries in that region will be moved.
10919 However, the region must fulfill the requirement that the first heading
10920 is the first one sets the top-level of the moved text - at most siblings
10921 below it are allowed.
10923 With prefix arg GOTO, the command will only visit the target location
10924 and not actually move anything.
10926 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10927 go to the location where the last refiling operation has put the subtree.
10928 With a prefix argument of `2', refile to the running clock.
10930 RFLOC can be a refile location obtained in a different way.
10932 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10934 If you are using target caching (see `org-refile-use-cache'),
10935 you have to clear the target cache in order to find new targets.
10936 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10937 prefix argument (`C-u C-u C-u C-c C-w')."
10939 (interactive "P")
10940 (if (member goto '(0 (64)))
10941 (org-refile-cache-clear)
10942 (let* ((cbuf (current-buffer))
10943 (regionp (org-region-active-p))
10944 (region-start (and regionp (region-beginning)))
10945 (region-end (and regionp (region-end)))
10946 (region-length (and regionp (- region-end region-start)))
10947 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10948 pos it nbuf file re level reversed)
10949 (setq last-command nil)
10950 (when regionp
10951 (goto-char region-start)
10952 (or (bolp) (goto-char (point-at-bol)))
10953 (setq region-start (point))
10954 (unless (or (org-kill-is-subtree-p
10955 (buffer-substring region-start region-end))
10956 (prog1 org-refile-active-region-within-subtree
10957 (org-toggle-heading)))
10958 (error "The region is not a (sequence of) subtree(s)")))
10959 (if (equal goto '(16))
10960 (org-refile-goto-last-stored)
10961 (when (or
10962 (and (equal goto 2)
10963 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10964 (prog1
10965 (setq it (list (or org-clock-heading "running clock")
10966 (buffer-file-name
10967 (marker-buffer org-clock-hd-marker))
10969 (marker-position org-clock-hd-marker)))
10970 (setq goto nil)))
10971 (setq it (or rfloc
10972 (let (heading-text)
10973 (save-excursion
10974 (unless goto
10975 (org-back-to-heading t)
10976 (setq heading-text
10977 (nth 4 (org-heading-components))))
10978 (org-refile-get-location
10979 (cond (goto "Goto")
10980 (regionp "Refile region to")
10981 (t (concat "Refile subtree \""
10982 heading-text "\" to")))
10983 default-buffer
10984 (and (not (equal '(4) goto))
10985 org-refile-allow-creating-parent-nodes)
10986 goto))))))
10987 (setq file (nth 1 it)
10988 re (nth 2 it)
10989 pos (nth 3 it))
10990 (if (and (not goto)
10992 (equal (buffer-file-name) file)
10993 (if regionp
10994 (and (>= pos region-start)
10995 (<= pos region-end))
10996 (and (>= pos (point))
10997 (< pos (save-excursion
10998 (org-end-of-subtree t t))))))
10999 (error "Cannot refile to position inside the tree or region"))
11001 (setq nbuf (or (find-buffer-visiting file)
11002 (find-file-noselect file)))
11003 (if goto
11004 (progn
11005 (org-pop-to-buffer-same-window nbuf)
11006 (goto-char pos)
11007 (org-show-context 'org-goto))
11008 (if regionp
11009 (progn
11010 (org-kill-new (buffer-substring region-start region-end))
11011 (org-save-markers-in-region region-start region-end))
11012 (org-copy-subtree 1 nil t))
11013 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11014 (find-file-noselect file)))
11015 (setq reversed (org-notes-order-reversed-p))
11016 (save-excursion
11017 (save-restriction
11018 (widen)
11019 (if pos
11020 (progn
11021 (goto-char pos)
11022 (looking-at org-outline-regexp)
11023 (setq level (org-get-valid-level (funcall outline-level) 1))
11024 (goto-char
11025 (if reversed
11026 (or (outline-next-heading) (point-max))
11027 (or (save-excursion (org-get-next-sibling))
11028 (org-end-of-subtree t t)
11029 (point-max)))))
11030 (setq level 1)
11031 (if (not reversed)
11032 (goto-char (point-max))
11033 (goto-char (point-min))
11034 (or (outline-next-heading) (goto-char (point-max)))))
11035 (if (not (bolp)) (newline))
11036 (org-paste-subtree level)
11037 (when org-log-refile
11038 (org-add-log-setup 'refile nil nil 'findpos
11039 org-log-refile)
11040 (unless (eq org-log-refile 'note)
11041 (save-excursion (org-add-log-note))))
11042 (and org-auto-align-tags
11043 (let ((org-loop-over-headlines-in-active-region nil))
11044 (org-set-tags nil t)))
11045 (bookmark-set "org-refile-last-stored")
11046 ;; If we are refiling for capture, make sure that the
11047 ;; last-capture pointers point here
11048 (when (org-bound-and-true-p org-refile-for-capture)
11049 (bookmark-set "org-capture-last-stored-marker")
11050 (move-marker org-capture-last-stored-marker (point)))
11051 (if (fboundp 'deactivate-mark) (deactivate-mark))
11052 (run-hooks 'org-after-refile-insert-hook))))
11053 (if regionp
11054 (delete-region (point) (+ (point) region-length))
11055 (org-cut-subtree))
11056 (when (featurep 'org-inlinetask)
11057 (org-inlinetask-remove-END-maybe))
11058 (setq org-markers-to-move nil)
11059 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11061 (defun org-refile-goto-last-stored ()
11062 "Go to the location where the last refile was stored."
11063 (interactive)
11064 (bookmark-jump "org-refile-last-stored")
11065 (message "This is the location of the last refile"))
11067 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11068 no-exclude)
11069 "Prompt the user for a refile location, using PROMPT.
11070 PROMPT should not be suffixed with a colon and a space, because
11071 this function appends the default value from
11072 `org-refile-history' automatically, if that is not empty.
11073 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11074 this is used for the GOTO interface."
11075 (let ((org-refile-targets org-refile-targets)
11076 (org-refile-use-outline-path org-refile-use-outline-path)
11077 excluded-entries)
11078 (when (and (derived-mode-p 'org-mode)
11079 (not org-refile-use-cache)
11080 (not no-exclude))
11081 (org-map-tree
11082 (lambda()
11083 (setq excluded-entries
11084 (append excluded-entries (list (org-get-heading t t)))))))
11085 (setq org-refile-target-table
11086 (org-refile-get-targets default-buffer excluded-entries)))
11087 (unless org-refile-target-table
11088 (error "No refile targets"))
11089 (let* ((prompt (concat prompt
11090 (and (car org-refile-history)
11091 (concat " (default " (car org-refile-history) ")"))
11092 ": "))
11093 (cbuf (current-buffer))
11094 (partial-completion-mode nil)
11095 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11096 (cfunc (if (and org-refile-use-outline-path
11097 org-outline-path-complete-in-steps)
11098 'org-olpath-completing-read
11099 'org-icompleting-read))
11100 (extra (if org-refile-use-outline-path "/" ""))
11101 (filename (and cfn (expand-file-name cfn)))
11102 (tbl (mapcar
11103 (lambda (x)
11104 (if (and (not (member org-refile-use-outline-path
11105 '(file full-file-path)))
11106 (not (equal filename (nth 1 x))))
11107 (cons (concat (car x) extra " ("
11108 (file-name-nondirectory (nth 1 x)) ")")
11109 (cdr x))
11110 (cons (concat (car x) extra) (cdr x))))
11111 org-refile-target-table))
11112 (completion-ignore-case t)
11113 pa answ parent-target child parent old-hist)
11114 (setq old-hist org-refile-history)
11115 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11116 nil 'org-refile-history (car org-refile-history)))
11117 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11118 (org-refile-check-position pa)
11119 (if pa
11120 (progn
11121 (when (or (not org-refile-history)
11122 (not (eq old-hist org-refile-history))
11123 (not (equal (car pa) (car org-refile-history))))
11124 (setq org-refile-history
11125 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11126 org-refile-history
11127 (cdr org-refile-history))))
11128 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11129 (pop org-refile-history)))
11131 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11132 (progn
11133 (setq parent (match-string 1 answ)
11134 child (match-string 2 answ))
11135 (setq parent-target (or (assoc parent tbl)
11136 (assoc (concat parent "/") tbl)))
11137 (when (and parent-target
11138 (or (eq new-nodes t)
11139 (and (eq new-nodes 'confirm)
11140 (y-or-n-p (format "Create new node \"%s\"? "
11141 child)))))
11142 (org-refile-new-child parent-target child)))
11143 (error "Invalid target location")))))
11145 (declare-function org-string-nw-p "org-macs.el" (s))
11146 (defun org-refile-check-position (refile-pointer)
11147 "Check if the refile pointer matches the readline to which it points."
11148 (let* ((file (nth 1 refile-pointer))
11149 (re (nth 2 refile-pointer))
11150 (pos (nth 3 refile-pointer))
11151 buffer)
11152 (when (org-string-nw-p re)
11153 (setq buffer (if (markerp pos)
11154 (marker-buffer pos)
11155 (or (find-buffer-visiting file)
11156 (find-file-noselect file))))
11157 (with-current-buffer buffer
11158 (save-excursion
11159 (save-restriction
11160 (widen)
11161 (goto-char pos)
11162 (beginning-of-line 1)
11163 (unless (org-looking-at-p re)
11164 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11166 (defun org-refile-new-child (parent-target child)
11167 "Use refile target PARENT-TARGET to add new CHILD below it."
11168 (unless parent-target
11169 (error "Cannot find parent for new node"))
11170 (let ((file (nth 1 parent-target))
11171 (pos (nth 3 parent-target))
11172 level)
11173 (with-current-buffer (or (find-buffer-visiting file)
11174 (find-file-noselect file))
11175 (save-excursion
11176 (save-restriction
11177 (widen)
11178 (if pos
11179 (goto-char pos)
11180 (goto-char (point-max))
11181 (if (not (bolp)) (newline)))
11182 (when (looking-at org-outline-regexp)
11183 (setq level (funcall outline-level))
11184 (org-end-of-subtree t t))
11185 (org-back-over-empty-lines)
11186 (insert "\n" (make-string
11187 (if pos (org-get-valid-level level 1) 1) ?*)
11188 " " child "\n")
11189 (beginning-of-line 0)
11190 (list (concat (car parent-target) "/" child) file "" (point)))))))
11192 (defun org-olpath-completing-read (prompt collection &rest args)
11193 "Read an outline path like a file name."
11194 (let ((thetable collection)
11195 (org-completion-use-ido nil) ; does not work with ido.
11196 (org-completion-use-iswitchb nil)) ; or iswitchb
11197 (apply
11198 'org-icompleting-read prompt
11199 (lambda (string predicate &optional flag)
11200 (let (rtn r f (l (length string)))
11201 (cond
11202 ((eq flag nil)
11203 ;; try completion
11204 (try-completion string thetable))
11205 ((eq flag t)
11206 ;; all-completions
11207 (setq rtn (all-completions string thetable predicate))
11208 (mapcar
11209 (lambda (x)
11210 (setq r (substring x l))
11211 (if (string-match " ([^)]*)$" x)
11212 (setq f (match-string 0 x))
11213 (setq f ""))
11214 (if (string-match "/" r)
11215 (concat string (substring r 0 (match-end 0)) f)
11217 rtn))
11218 ((eq flag 'lambda)
11219 ;; exact match?
11220 (assoc string thetable)))))
11221 args)))
11223 ;;;; Dynamic blocks
11225 (defun org-find-dblock (name)
11226 "Find the first dynamic block with name NAME in the buffer.
11227 If not found, stay at current position and return nil."
11228 (let ((case-fold-search t) pos)
11229 (save-excursion
11230 (goto-char (point-min))
11231 (setq pos (and (re-search-forward
11232 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11233 (match-beginning 0))))
11234 (if pos (goto-char pos))
11235 pos))
11237 (defconst org-dblock-start-re
11238 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11239 "Matches the start line of a dynamic block, with parameters.")
11241 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11242 "Matches the end of a dynamic block.")
11244 (defun org-create-dblock (plist)
11245 "Create a dynamic block section, with parameters taken from PLIST.
11246 PLIST must contain a :name entry which is used as name of the block."
11247 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11248 (end-of-line 1)
11249 (newline))
11250 (let ((col (current-column))
11251 (name (plist-get plist :name)))
11252 (insert "#+BEGIN: " name)
11253 (while plist
11254 (if (eq (car plist) :name)
11255 (setq plist (cddr plist))
11256 (insert " " (prin1-to-string (pop plist)))))
11257 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11258 (beginning-of-line -2)))
11260 (defun org-prepare-dblock ()
11261 "Prepare dynamic block for refresh.
11262 This empties the block, puts the cursor at the insert position and returns
11263 the property list including an extra property :name with the block name."
11264 (unless (looking-at org-dblock-start-re)
11265 (error "Not at a dynamic block"))
11266 (let* ((begdel (1+ (match-end 0)))
11267 (name (org-no-properties (match-string 1)))
11268 (params (append (list :name name)
11269 (read (concat "(" (match-string 3) ")")))))
11270 (save-excursion
11271 (beginning-of-line 1)
11272 (skip-chars-forward " \t")
11273 (setq params (plist-put params :indentation-column (current-column))))
11274 (unless (re-search-forward org-dblock-end-re nil t)
11275 (error "Dynamic block not terminated"))
11276 (setq params
11277 (append params
11278 (list :content (buffer-substring
11279 begdel (match-beginning 0)))))
11280 (delete-region begdel (match-beginning 0))
11281 (goto-char begdel)
11282 (open-line 1)
11283 params))
11285 (defun org-map-dblocks (&optional command)
11286 "Apply COMMAND to all dynamic blocks in the current buffer.
11287 If COMMAND is not given, use `org-update-dblock'."
11288 (let ((cmd (or command 'org-update-dblock)))
11289 (save-excursion
11290 (goto-char (point-min))
11291 (while (re-search-forward org-dblock-start-re nil t)
11292 (goto-char (match-beginning 0))
11293 (save-excursion
11294 (condition-case nil
11295 (funcall cmd)
11296 (error (message "Error during update of dynamic block"))))
11297 (unless (re-search-forward org-dblock-end-re nil t)
11298 (error "Dynamic block not terminated"))))))
11300 (defun org-dblock-update (&optional arg)
11301 "User command for updating dynamic blocks.
11302 Update the dynamic block at point. With prefix ARG, update all dynamic
11303 blocks in the buffer."
11304 (interactive "P")
11305 (if arg
11306 (org-update-all-dblocks)
11307 (or (looking-at org-dblock-start-re)
11308 (org-beginning-of-dblock))
11309 (org-update-dblock)))
11311 (defun org-update-dblock ()
11312 "Update the dynamic block at point.
11313 This means to empty the block, parse for parameters and then call
11314 the correct writing function."
11315 (interactive)
11316 (save-window-excursion
11317 (let* ((pos (point))
11318 (line (org-current-line))
11319 (params (org-prepare-dblock))
11320 (name (plist-get params :name))
11321 (indent (plist-get params :indentation-column))
11322 (cmd (intern (concat "org-dblock-write:" name))))
11323 (message "Updating dynamic block `%s' at line %d..." name line)
11324 (funcall cmd params)
11325 (message "Updating dynamic block `%s' at line %d...done" name line)
11326 (goto-char pos)
11327 (when (and indent (> indent 0))
11328 (setq indent (make-string indent ?\ ))
11329 (save-excursion
11330 (org-beginning-of-dblock)
11331 (forward-line 1)
11332 (while (not (looking-at org-dblock-end-re))
11333 (insert indent)
11334 (beginning-of-line 2))
11335 (when (looking-at org-dblock-end-re)
11336 (and (looking-at "[ \t]+")
11337 (replace-match ""))
11338 (insert indent)))))))
11340 (defun org-beginning-of-dblock ()
11341 "Find the beginning of the dynamic block at point.
11342 Error if there is no such block at point."
11343 (let ((pos (point))
11344 beg)
11345 (end-of-line 1)
11346 (if (and (re-search-backward org-dblock-start-re nil t)
11347 (setq beg (match-beginning 0))
11348 (re-search-forward org-dblock-end-re nil t)
11349 (> (match-end 0) pos))
11350 (goto-char beg)
11351 (goto-char pos)
11352 (error "Not in a dynamic block"))))
11354 ;;;###autoload
11355 (defun org-update-all-dblocks ()
11356 "Update all dynamic blocks in the buffer.
11357 This function can be used in a hook."
11358 (interactive)
11359 (when (derived-mode-p 'org-mode)
11360 (org-map-dblocks 'org-update-dblock)))
11363 ;;;; Completion
11365 (defconst org-additional-option-like-keywords
11366 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11367 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11368 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11369 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11370 "BEGIN:" "END:"
11371 "ORGTBL" "TBLFM:" "TBLNAME:"
11372 "BEGIN_EXAMPLE" "END_EXAMPLE"
11373 "BEGIN_VERBATIM" "END_VERBATIM"
11374 "BEGIN_QUOTE" "END_QUOTE"
11375 "BEGIN_VERSE" "END_VERSE"
11376 "BEGIN_CENTER" "END_CENTER"
11377 "BEGIN_SRC" "END_SRC"
11378 "BEGIN_RESULT" "END_RESULT"
11379 "BEGIN_lstlisting" "END_lstlisting"
11380 "NAME:" "RESULTS:"
11381 "HEADER:" "HEADERS:"
11382 "COLUMNS:" "PROPERTY:"
11383 "CAPTION:" "LABEL:"
11384 "SETUPFILE:"
11385 "INCLUDE:"
11386 "BIND:"
11387 "MACRO:"))
11389 (defconst org-options-keywords
11390 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11391 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11392 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11393 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11394 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11395 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11396 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11398 (defconst org-additional-option-like-keywords-for-flyspell
11399 (delete-dups
11400 (split-string
11401 (mapconcat (lambda(k)
11402 (replace-regexp-in-string
11403 "_\\|:" " "
11404 (concat k " " (downcase k) " " (upcase k))))
11405 (append org-options-keywords org-additional-option-like-keywords)
11406 " ")
11407 " +" t)))
11409 (defcustom org-structure-template-alist
11411 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11412 "<src lang=\"?\">\n\n</src>")
11413 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11414 "<example>\n?\n</example>")
11415 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11416 "<quote>\n?\n</quote>")
11417 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11418 "<verse>\n?\n</verse>")
11419 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11420 "<center>\n?\n</center>")
11421 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11422 "<literal style=\"latex\">\n?\n</literal>")
11423 ("L" "#+LaTeX: "
11424 "<literal style=\"latex\">?</literal>")
11425 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11426 "<literal style=\"html\">\n?\n</literal>")
11427 ("H" "#+HTML: "
11428 "<literal style=\"html\">?</literal>")
11429 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11430 ("A" "#+ASCII: ")
11431 ("i" "#+INDEX: ?"
11432 "#+INDEX: ?")
11433 ("I" "#+INCLUDE: %file ?"
11434 "<include file=%file markup=\"?\">")
11436 "Structure completion elements.
11437 This is a list of abbreviation keys and values. The value gets inserted
11438 if you type `<' followed by the key and then press the completion key,
11439 usually `M-TAB'. %file will be replaced by a file name after prompting
11440 for the file using completion. The cursor will be placed at the position
11441 of the `?` in the template.
11442 There are two templates for each key, the first uses the original Org syntax,
11443 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11444 the default when the /org-mtags.el/ module has been loaded. See also the
11445 variable `org-mtags-prefer-muse-templates'."
11446 :group 'org-completion
11447 :type '(repeat
11448 (string :tag "Key")
11449 (string :tag "Template")
11450 (string :tag "Muse Template")))
11452 (defun org-try-structure-completion ()
11453 "Try to complete a structure template before point.
11454 This looks for strings like \"<e\" on an otherwise empty line and
11455 expands them."
11456 (let ((l (buffer-substring (point-at-bol) (point)))
11458 (when (and (looking-at "[ \t]*$")
11459 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11460 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11461 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11462 (match-beginning 1)) a)
11463 t)))
11465 (defun org-complete-expand-structure-template (start cell)
11466 "Expand a structure template."
11467 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11468 (rpl (nth (if musep 2 1) cell))
11469 (ind ""))
11470 (delete-region start (point))
11471 (when (string-match "\\`#\\+" rpl)
11472 (cond
11473 ((bolp))
11474 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11475 (setq ind (buffer-substring (point-at-bol) (point))))
11476 (t (newline))))
11477 (setq start (point))
11478 (if (string-match "%file" rpl)
11479 (setq rpl (replace-match
11480 (concat
11481 "\""
11482 (save-match-data
11483 (abbreviate-file-name (read-file-name "Include file: ")))
11484 "\"")
11485 t t rpl)))
11486 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11487 (concat "\n" ind)))
11488 (insert rpl)
11489 (if (re-search-backward "\\?" start t) (delete-char 1))))
11491 ;;;; TODO, DEADLINE, Comments
11493 (defun org-toggle-comment ()
11494 "Change the COMMENT state of an entry."
11495 (interactive)
11496 (save-excursion
11497 (org-back-to-heading)
11498 (let (case-fold-search)
11499 (cond
11500 ((looking-at (format org-heading-keyword-regexp-format
11501 org-comment-string))
11502 (goto-char (match-end 1))
11503 (looking-at (concat " +" org-comment-string))
11504 (replace-match "" t t)
11505 (when (eolp) (insert " ")))
11506 ((looking-at org-outline-regexp)
11507 (goto-char (match-end 0))
11508 (insert org-comment-string " "))))))
11510 (defvar org-last-todo-state-is-todo nil
11511 "This is non-nil when the last TODO state change led to a TODO state.
11512 If the last change removed the TODO tag or switched to DONE, then
11513 this is nil.")
11515 (defvar org-setting-tags nil) ; dynamically skipped
11517 (defvar org-todo-setup-filter-hook nil
11518 "Hook for functions that pre-filter todo specs.
11519 Each function takes a todo spec and returns either nil or the spec
11520 transformed into canonical form." )
11522 (defvar org-todo-get-default-hook nil
11523 "Hook for functions that get a default item for todo.
11524 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11525 nil or a string to be used for the todo mark." )
11527 (defvar org-agenda-headline-snapshot-before-repeat)
11529 (defun org-current-effective-time ()
11530 "Return current time adjusted for `org-extend-today-until' variable."
11531 (let* ((ct (org-current-time))
11532 (dct (decode-time ct))
11533 (ct1
11534 (if (and org-use-effective-time
11535 (< (nth 2 dct) org-extend-today-until))
11536 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11537 ct)))
11538 ct1))
11540 (defun org-todo-yesterday (&optional arg)
11541 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11542 (interactive "P")
11543 (if (eq major-mode 'org-agenda-mode)
11544 (apply 'org-agenda-todo-yesterday arg)
11545 (let* ((hour (third (decode-time
11546 (org-current-time))))
11547 (org-extend-today-until (1+ hour)))
11548 (org-todo arg))))
11550 (defun org-todo (&optional arg)
11551 "Change the TODO state of an item.
11552 The state of an item is given by a keyword at the start of the heading,
11553 like
11554 *** TODO Write paper
11555 *** DONE Call mom
11557 The different keywords are specified in the variable `org-todo-keywords'.
11558 By default the available states are \"TODO\" and \"DONE\".
11559 So for this example: when the item starts with TODO, it is changed to DONE.
11560 When it starts with DONE, the DONE is removed. And when neither TODO nor
11561 DONE are present, add TODO at the beginning of the heading.
11563 With \\[universal-argument] prefix arg, use completion to determine the new \
11564 state.
11565 With numeric prefix arg, switch to that state.
11566 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11567 keywords (nextset).
11568 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11569 With a numeric prefix arg of 0, inhibit note taking for the change.
11571 For calling through lisp, arg is also interpreted in the following way:
11572 'none -> empty state
11573 \"\"(empty string) -> switch to empty state
11574 'done -> switch to DONE
11575 'nextset -> switch to the next set of keywords
11576 'previousset -> switch to the previous set of keywords
11577 \"WAITING\" -> switch to the specified keyword, but only if it
11578 really is a member of `org-todo-keywords'."
11579 (interactive "P")
11580 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11581 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11582 'region-start-level 'region))
11583 org-loop-over-headlines-in-active-region)
11584 (org-map-entries
11585 `(org-todo ,arg)
11586 org-loop-over-headlines-in-active-region
11587 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11588 (if (equal arg '(16)) (setq arg 'nextset))
11589 (let ((org-blocker-hook org-blocker-hook)
11590 (case-fold-search nil))
11591 (when (equal arg '(64))
11592 (setq arg nil org-blocker-hook nil))
11593 (when (and org-blocker-hook
11594 (or org-inhibit-blocking
11595 (org-entry-get nil "NOBLOCKING")))
11596 (setq org-blocker-hook nil))
11597 (save-excursion
11598 (catch 'exit
11599 (org-back-to-heading t)
11600 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11601 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11602 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11603 (let* ((match-data (match-data))
11604 (startpos (point-at-bol))
11605 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11606 (org-log-done org-log-done)
11607 (org-log-repeat org-log-repeat)
11608 (org-todo-log-states org-todo-log-states)
11609 (org-inhibit-logging
11610 (if (equal arg 0)
11611 (progn (setq arg nil) 'note) org-inhibit-logging))
11612 (this (match-string 1))
11613 (hl-pos (match-beginning 0))
11614 (head (org-get-todo-sequence-head this))
11615 (ass (assoc head org-todo-kwd-alist))
11616 (interpret (nth 1 ass))
11617 (done-word (nth 3 ass))
11618 (final-done-word (nth 4 ass))
11619 (org-last-state (or this ""))
11620 (completion-ignore-case t)
11621 (member (member this org-todo-keywords-1))
11622 (tail (cdr member))
11623 (org-state (cond
11624 ((and org-todo-key-trigger
11625 (or (and (equal arg '(4))
11626 (eq org-use-fast-todo-selection 'prefix))
11627 (and (not arg) org-use-fast-todo-selection
11628 (not (eq org-use-fast-todo-selection
11629 'prefix)))))
11630 ;; Use fast selection
11631 (org-fast-todo-selection))
11632 ((and (equal arg '(4))
11633 (or (not org-use-fast-todo-selection)
11634 (not org-todo-key-trigger)))
11635 ;; Read a state with completion
11636 (org-icompleting-read
11637 "State: " (mapcar (lambda(x) (list x))
11638 org-todo-keywords-1)
11639 nil t))
11640 ((eq arg 'right)
11641 (if this
11642 (if tail (car tail) nil)
11643 (car org-todo-keywords-1)))
11644 ((eq arg 'left)
11645 (if (equal member org-todo-keywords-1)
11647 (if this
11648 (nth (- (length org-todo-keywords-1)
11649 (length tail) 2)
11650 org-todo-keywords-1)
11651 (org-last org-todo-keywords-1))))
11652 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11653 (setq arg nil))) ; hack to fall back to cycling
11654 (arg
11655 ;; user or caller requests a specific state
11656 (cond
11657 ((equal arg "") nil)
11658 ((eq arg 'none) nil)
11659 ((eq arg 'done) (or done-word (car org-done-keywords)))
11660 ((eq arg 'nextset)
11661 (or (car (cdr (member head org-todo-heads)))
11662 (car org-todo-heads)))
11663 ((eq arg 'previousset)
11664 (let ((org-todo-heads (reverse org-todo-heads)))
11665 (or (car (cdr (member head org-todo-heads)))
11666 (car org-todo-heads))))
11667 ((car (member arg org-todo-keywords-1)))
11668 ((stringp arg)
11669 (error "State `%s' not valid in this file" arg))
11670 ((nth (1- (prefix-numeric-value arg))
11671 org-todo-keywords-1))))
11672 ((null member) (or head (car org-todo-keywords-1)))
11673 ((equal this final-done-word) nil) ;; -> make empty
11674 ((null tail) nil) ;; -> first entry
11675 ((memq interpret '(type priority))
11676 (if (eq this-command last-command)
11677 (car tail)
11678 (if (> (length tail) 0)
11679 (or done-word (car org-done-keywords))
11680 nil)))
11682 (car tail))))
11683 (org-state (or
11684 (run-hook-with-args-until-success
11685 'org-todo-get-default-hook org-state org-last-state)
11686 org-state))
11687 (next (if org-state (concat " " org-state " ") " "))
11688 (change-plist (list :type 'todo-state-change :from this :to org-state
11689 :position startpos))
11690 dolog now-done-p)
11691 (when org-blocker-hook
11692 (setq org-last-todo-state-is-todo
11693 (not (member this org-done-keywords)))
11694 (unless (save-excursion
11695 (save-match-data
11696 (org-with-wide-buffer
11697 (run-hook-with-args-until-failure
11698 'org-blocker-hook change-plist))))
11699 (if (org-called-interactively-p 'interactive)
11700 (error "TODO state change from %s to %s blocked" this org-state)
11701 ;; fail silently
11702 (message "TODO state change from %s to %s blocked" this org-state)
11703 (throw 'exit nil))))
11704 (store-match-data match-data)
11705 (replace-match next t t)
11706 (unless (pos-visible-in-window-p hl-pos)
11707 (message "TODO state changed to %s" (org-trim next)))
11708 (unless head
11709 (setq head (org-get-todo-sequence-head org-state)
11710 ass (assoc head org-todo-kwd-alist)
11711 interpret (nth 1 ass)
11712 done-word (nth 3 ass)
11713 final-done-word (nth 4 ass)))
11714 (when (memq arg '(nextset previousset))
11715 (message "Keyword-Set %d/%d: %s"
11716 (- (length org-todo-sets) -1
11717 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11718 (length org-todo-sets)
11719 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11720 (setq org-last-todo-state-is-todo
11721 (not (member org-state org-done-keywords)))
11722 (setq now-done-p (and (member org-state org-done-keywords)
11723 (not (member this org-done-keywords))))
11724 (and logging (org-local-logging logging))
11725 (when (and (or org-todo-log-states org-log-done)
11726 (not (eq org-inhibit-logging t))
11727 (not (memq arg '(nextset previousset))))
11728 ;; we need to look at recording a time and note
11729 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11730 (nth 2 (assoc this org-todo-log-states))))
11731 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11732 (setq dolog 'time))
11733 (when (and org-state
11734 (member org-state org-not-done-keywords)
11735 (not (member this org-not-done-keywords)))
11736 ;; This is now a todo state and was not one before
11737 ;; If there was a CLOSED time stamp, get rid of it.
11738 (org-add-planning-info nil nil 'closed))
11739 (when (and now-done-p org-log-done)
11740 ;; It is now done, and it was not done before
11741 (org-add-planning-info 'closed (org-current-effective-time))
11742 (if (and (not dolog) (eq 'note org-log-done))
11743 (org-add-log-setup 'done org-state this 'findpos 'note)))
11744 (when (and org-state dolog)
11745 ;; This is a non-nil state, and we need to log it
11746 (org-add-log-setup 'state org-state this 'findpos dolog)))
11747 ;; Fixup tag positioning
11748 (org-todo-trigger-tag-changes org-state)
11749 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11750 (when org-provide-todo-statistics
11751 (org-update-parent-todo-statistics))
11752 (run-hooks 'org-after-todo-state-change-hook)
11753 (if (and arg (not (member org-state org-done-keywords)))
11754 (setq head (org-get-todo-sequence-head org-state)))
11755 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11756 ;; Do we need to trigger a repeat?
11757 (when now-done-p
11758 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11759 ;; This is for the agenda, take a snapshot of the headline.
11760 (save-match-data
11761 (setq org-agenda-headline-snapshot-before-repeat
11762 (org-get-heading))))
11763 (org-auto-repeat-maybe org-state))
11764 ;; Fixup cursor location if close to the keyword
11765 (if (and (outline-on-heading-p)
11766 (not (bolp))
11767 (save-excursion (beginning-of-line 1)
11768 (looking-at org-todo-line-regexp))
11769 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11770 (progn
11771 (goto-char (or (match-end 2) (match-end 1)))
11772 (and (looking-at " ") (just-one-space))))
11773 (when org-trigger-hook
11774 (save-excursion
11775 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11777 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11778 "Block turning an entry into a TODO, using the hierarchy.
11779 This checks whether the current task should be blocked from state
11780 changes. Such blocking occurs when:
11782 1. The task has children which are not all in a completed state.
11784 2. A task has a parent with the property :ORDERED:, and there
11785 are siblings prior to the current task with incomplete
11786 status.
11788 3. The parent of the task is blocked because it has siblings that should
11789 be done first, or is child of a block grandparent TODO entry."
11791 (if (not org-enforce-todo-dependencies)
11792 t ; if locally turned off don't block
11793 (catch 'dont-block
11794 ;; If this is not a todo state change, or if this entry is already DONE,
11795 ;; do not block
11796 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11797 (member (plist-get change-plist :from)
11798 (cons 'done org-done-keywords))
11799 (member (plist-get change-plist :to)
11800 (cons 'todo org-not-done-keywords))
11801 (not (plist-get change-plist :to)))
11802 (throw 'dont-block t))
11803 ;; If this task has children, and any are undone, it's blocked
11804 (save-excursion
11805 (org-back-to-heading t)
11806 (let ((this-level (funcall outline-level)))
11807 (outline-next-heading)
11808 (let ((child-level (funcall outline-level)))
11809 (while (and (not (eobp))
11810 (> child-level this-level))
11811 ;; this todo has children, check whether they are all
11812 ;; completed
11813 (if (and (not (org-entry-is-done-p))
11814 (org-entry-is-todo-p))
11815 (throw 'dont-block nil))
11816 (outline-next-heading)
11817 (setq child-level (funcall outline-level))))))
11818 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11819 ;; any previous siblings are undone, it's blocked
11820 (save-excursion
11821 (org-back-to-heading t)
11822 (let* ((pos (point))
11823 (parent-pos (and (org-up-heading-safe) (point))))
11824 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11825 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11826 (forward-line 1)
11827 (re-search-forward org-not-done-heading-regexp pos t))
11828 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11829 ;; Search further up the hierarchy, to see if an ancestor is blocked
11830 (while t
11831 (goto-char parent-pos)
11832 (if (not (looking-at org-not-done-heading-regexp))
11833 (throw 'dont-block t)) ; do not block, parent is not a TODO
11834 (setq pos (point))
11835 (setq parent-pos (and (org-up-heading-safe) (point)))
11836 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11837 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11838 (forward-line 1)
11839 (re-search-forward org-not-done-heading-regexp pos t))
11840 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11842 (defcustom org-track-ordered-property-with-tag nil
11843 "Should the ORDERED property also be shown as a tag?
11844 The ORDERED property decides if an entry should require subtasks to be
11845 completed in sequence. Since a property is not very visible, setting
11846 this option means that toggling the ORDERED property with the command
11847 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11848 not relevant for the behavior, but it makes things more visible.
11850 Note that toggling the tag with tags commands will not change the property
11851 and therefore not influence behavior!
11853 This can be t, meaning the tag ORDERED should be used, It can also be a
11854 string to select a different tag for this task."
11855 :group 'org-todo
11856 :type '(choice
11857 (const :tag "No tracking" nil)
11858 (const :tag "Track with ORDERED tag" t)
11859 (string :tag "Use other tag")))
11861 (defun org-toggle-ordered-property ()
11862 "Toggle the ORDERED property of the current entry.
11863 For better visibility, you can track the value of this property with a tag.
11864 See variable `org-track-ordered-property-with-tag'."
11865 (interactive)
11866 (let* ((t1 org-track-ordered-property-with-tag)
11867 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11868 (save-excursion
11869 (org-back-to-heading)
11870 (if (org-entry-get nil "ORDERED")
11871 (progn
11872 (org-delete-property "ORDERED")
11873 (and tag (org-toggle-tag tag 'off))
11874 (message "Subtasks can be completed in arbitrary order"))
11875 (org-entry-put nil "ORDERED" "t")
11876 (and tag (org-toggle-tag tag 'on))
11877 (message "Subtasks must be completed in sequence")))))
11879 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11880 (defun org-block-todo-from-checkboxes (change-plist)
11881 "Block turning an entry into a TODO, using checkboxes.
11882 This checks whether the current task should be blocked from state
11883 changes because there are unchecked boxes in this entry."
11884 (if (not org-enforce-todo-checkbox-dependencies)
11885 t ; if locally turned off don't block
11886 (catch 'dont-block
11887 ;; If this is not a todo state change, or if this entry is already DONE,
11888 ;; do not block
11889 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11890 (member (plist-get change-plist :from)
11891 (cons 'done org-done-keywords))
11892 (member (plist-get change-plist :to)
11893 (cons 'todo org-not-done-keywords))
11894 (not (plist-get change-plist :to)))
11895 (throw 'dont-block t))
11896 ;; If this task has checkboxes that are not checked, it's blocked
11897 (save-excursion
11898 (org-back-to-heading t)
11899 (let ((beg (point)) end)
11900 (outline-next-heading)
11901 (setq end (point))
11902 (goto-char beg)
11903 (if (org-list-search-forward
11904 (concat (org-item-beginning-re)
11905 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11906 "\\[[- ]\\]")
11907 end t)
11908 (progn
11909 (if (boundp 'org-blocked-by-checkboxes)
11910 (setq org-blocked-by-checkboxes t))
11911 (throw 'dont-block nil)))))
11912 t))) ; do not block
11914 (defun org-entry-blocked-p ()
11915 "Is the current entry blocked?"
11916 (if (org-entry-get nil "NOBLOCKING")
11917 nil ;; Never block this entry
11918 (not
11919 (run-hook-with-args-until-failure
11920 'org-blocker-hook
11921 (list :type 'todo-state-change
11922 :position (point)
11923 :from 'todo
11924 :to 'done)))))
11926 (defun org-update-statistics-cookies (all)
11927 "Update the statistics cookie, either from TODO or from checkboxes.
11928 This should be called with the cursor in a line with a statistics cookie."
11929 (interactive "P")
11930 (if all
11931 (progn
11932 (org-update-checkbox-count 'all)
11933 (org-map-entries 'org-update-parent-todo-statistics))
11934 (if (not (org-at-heading-p))
11935 (org-update-checkbox-count)
11936 (let ((pos (move-marker (make-marker) (point)))
11937 end l1 l2)
11938 (ignore-errors (org-back-to-heading t))
11939 (if (not (org-at-heading-p))
11940 (org-update-checkbox-count)
11941 (setq l1 (org-outline-level))
11942 (setq end (save-excursion
11943 (outline-next-heading)
11944 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11945 (point)))
11946 (if (and (save-excursion
11947 (re-search-forward
11948 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11949 (not (save-excursion (re-search-forward
11950 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11951 (org-update-checkbox-count)
11952 (if (and l2 (> l2 l1))
11953 (progn
11954 (goto-char end)
11955 (org-update-parent-todo-statistics))
11956 (goto-char pos)
11957 (beginning-of-line 1)
11958 (while (re-search-forward
11959 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11960 (point-at-eol) t)
11961 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11962 (goto-char pos)
11963 (move-marker pos nil)))))
11965 (defvar org-entry-property-inherited-from) ;; defined below
11966 (defun org-update-parent-todo-statistics ()
11967 "Update any statistics cookie in the parent of the current headline.
11968 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11969 the entire subtree and this will travel up the hierarchy and update
11970 statistics everywhere."
11971 (let* ((prop (save-excursion (org-up-heading-safe)
11972 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11973 (recursive (or (not org-hierarchical-todo-statistics)
11974 (and prop (string-match "\\<recursive\\>" prop))))
11975 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11977 (first t)
11978 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11979 level ltoggle l1 new ndel
11980 (cnt-all 0) (cnt-done 0) is-percent kwd
11981 checkbox-beg ov ovs ove cookie-present)
11982 (catch 'exit
11983 (save-excursion
11984 (beginning-of-line 1)
11985 (setq ltoggle (funcall outline-level))
11986 ;; Three situations are to consider:
11988 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11989 ;; to the top-level ancestor on the headline;
11991 ;; 2. If parent has "recursive" property, repeat up to the
11992 ;; headline setting that property, taking inheritance into
11993 ;; account;
11995 ;; 3. Else, move up to direct parent and proceed only once.
11996 (while (and (setq level (org-up-heading-safe))
11997 (or recursive first)
11998 (>= (point) lim))
11999 (setq first nil cookie-present nil)
12000 (unless (and level
12001 (not (string-match
12002 "\\<checkbox\\>"
12003 (downcase (or (org-entry-get nil "COOKIE_DATA")
12004 "")))))
12005 (throw 'exit nil))
12006 (while (re-search-forward box-re (point-at-eol) t)
12007 (setq cnt-all 0 cnt-done 0 cookie-present t)
12008 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12009 (save-match-data
12010 (unless (outline-next-heading) (throw 'exit nil))
12011 (while (and (looking-at org-complex-heading-regexp)
12012 (> (setq l1 (length (match-string 1))) level))
12013 (setq kwd (and (or recursive (= l1 ltoggle))
12014 (match-string 2)))
12015 (if (or (eq org-provide-todo-statistics 'all-headlines)
12016 (and (listp org-provide-todo-statistics)
12017 (or (member kwd org-provide-todo-statistics)
12018 (member kwd org-done-keywords))))
12019 (setq cnt-all (1+ cnt-all))
12020 (if (eq org-provide-todo-statistics t)
12021 (and kwd (setq cnt-all (1+ cnt-all)))))
12022 (and (member kwd org-done-keywords)
12023 (setq cnt-done (1+ cnt-done)))
12024 (outline-next-heading)))
12025 (setq new
12026 (if is-percent
12027 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12028 (format "[%d/%d]" cnt-done cnt-all))
12029 ndel (- (match-end 0) checkbox-beg))
12030 ;; handle overlays when updating cookie from column view
12031 (when (setq ov (car (overlays-at checkbox-beg)))
12032 (setq ovs (overlay-start ov) ove (overlay-end ov))
12033 (delete-overlay ov))
12034 (goto-char checkbox-beg)
12035 (insert new)
12036 (delete-region (point) (+ (point) ndel))
12037 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12038 (when ov (move-overlay ov ovs ove)))
12039 (when cookie-present
12040 (run-hook-with-args 'org-after-todo-statistics-hook
12041 cnt-done (- cnt-all cnt-done))))))
12042 (run-hooks 'org-todo-statistics-hook)))
12044 (defvar org-after-todo-statistics-hook nil
12045 "Hook that is called after a TODO statistics cookie has been updated.
12046 Each function is called with two arguments: the number of not-done entries
12047 and the number of done entries.
12049 For example, the following function, when added to this hook, will switch
12050 an entry to DONE when all children are done, and back to TODO when new
12051 entries are set to a TODO status. Note that this hook is only called
12052 when there is a statistics cookie in the headline!
12054 (defun org-summary-todo (n-done n-not-done)
12055 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12056 (let (org-log-done org-log-states) ; turn off logging
12057 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12060 (defvar org-todo-statistics-hook nil
12061 "Hook that is run whenever Org thinks TODO statistics should be updated.
12062 This hook runs even if there is no statistics cookie present, in which case
12063 `org-after-todo-statistics-hook' would not run.")
12065 (defun org-todo-trigger-tag-changes (state)
12066 "Apply the changes defined in `org-todo-state-tags-triggers'."
12067 (let ((l org-todo-state-tags-triggers)
12068 changes)
12069 (when (or (not state) (equal state ""))
12070 (setq changes (append changes (cdr (assoc "" l)))))
12071 (when (and (stringp state) (> (length state) 0))
12072 (setq changes (append changes (cdr (assoc state l)))))
12073 (when (member state org-not-done-keywords)
12074 (setq changes (append changes (cdr (assoc 'todo l)))))
12075 (when (member state org-done-keywords)
12076 (setq changes (append changes (cdr (assoc 'done l)))))
12077 (dolist (c changes)
12078 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12080 (defun org-local-logging (value)
12081 "Get logging settings from a property VALUE."
12082 (let* (words w a)
12083 ;; directly set the variables, they are already local.
12084 (setq org-log-done nil
12085 org-log-repeat nil
12086 org-todo-log-states nil)
12087 (setq words (org-split-string value))
12088 (while (setq w (pop words))
12089 (cond
12090 ((setq a (assoc w org-startup-options))
12091 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12092 (set (nth 1 a) (nth 2 a))))
12093 ((setq a (org-extract-log-state-settings w))
12094 (and (member (car a) org-todo-keywords-1)
12095 (push a org-todo-log-states)))))))
12097 (defun org-get-todo-sequence-head (kwd)
12098 "Return the head of the TODO sequence to which KWD belongs.
12099 If KWD is not set, check if there is a text property remembering the
12100 right sequence."
12101 (let (p)
12102 (cond
12103 ((not kwd)
12104 (or (get-text-property (point-at-bol) 'org-todo-head)
12105 (progn
12106 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12107 nil (point-at-eol)))
12108 (get-text-property p 'org-todo-head))))
12109 ((not (member kwd org-todo-keywords-1))
12110 (car org-todo-keywords-1))
12111 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12113 (defun org-fast-todo-selection ()
12114 "Fast TODO keyword selection with single keys.
12115 Returns the new TODO keyword, or nil if no state change should occur."
12116 (let* ((fulltable org-todo-key-alist)
12117 (done-keywords org-done-keywords) ;; needed for the faces.
12118 (maxlen (apply 'max (mapcar
12119 (lambda (x)
12120 (if (stringp (car x)) (string-width (car x)) 0))
12121 fulltable)))
12122 (expert nil)
12123 (fwidth (+ maxlen 3 1 3))
12124 (ncol (/ (- (window-width) 4) fwidth))
12125 tg cnt e c tbl
12126 groups ingroup)
12127 (save-excursion
12128 (save-window-excursion
12129 (if expert
12130 (set-buffer (get-buffer-create " *Org todo*"))
12131 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12132 (erase-buffer)
12133 (org-set-local 'org-done-keywords done-keywords)
12134 (setq tbl fulltable cnt 0)
12135 (while (setq e (pop tbl))
12136 (cond
12137 ((equal e '(:startgroup))
12138 (push '() groups) (setq ingroup t)
12139 (when (not (= cnt 0))
12140 (setq cnt 0)
12141 (insert "\n"))
12142 (insert "{ "))
12143 ((equal e '(:endgroup))
12144 (setq ingroup nil cnt 0)
12145 (insert "}\n"))
12146 ((equal e '(:newline))
12147 (when (not (= cnt 0))
12148 (setq cnt 0)
12149 (insert "\n")
12150 (setq e (car tbl))
12151 (while (equal (car tbl) '(:newline))
12152 (insert "\n")
12153 (setq tbl (cdr tbl)))))
12155 (setq tg (car e) c (cdr e))
12156 (if ingroup (push tg (car groups)))
12157 (setq tg (org-add-props tg nil 'face
12158 (org-get-todo-face tg)))
12159 (if (and (= cnt 0) (not ingroup)) (insert " "))
12160 (insert "[" c "] " tg (make-string
12161 (- fwidth 4 (length tg)) ?\ ))
12162 (when (= (setq cnt (1+ cnt)) ncol)
12163 (insert "\n")
12164 (if ingroup (insert " "))
12165 (setq cnt 0)))))
12166 (insert "\n")
12167 (goto-char (point-min))
12168 (if (not expert) (org-fit-window-to-buffer))
12169 (message "[a-z..]:Set [SPC]:clear")
12170 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12171 (cond
12172 ((or (= c ?\C-g)
12173 (and (= c ?q) (not (rassoc c fulltable))))
12174 (setq quit-flag t))
12175 ((= c ?\ ) nil)
12176 ((setq e (rassoc c fulltable) tg (car e))
12178 (t (setq quit-flag t)))))))
12180 (defun org-entry-is-todo-p ()
12181 (member (org-get-todo-state) org-not-done-keywords))
12183 (defun org-entry-is-done-p ()
12184 (member (org-get-todo-state) org-done-keywords))
12186 (defun org-get-todo-state ()
12187 (save-excursion
12188 (org-back-to-heading t)
12189 (and (looking-at org-todo-line-regexp)
12190 (match-end 2)
12191 (match-string 2))))
12193 (defun org-at-date-range-p (&optional inactive-ok)
12194 "Is the cursor inside a date range?"
12195 (interactive)
12196 (save-excursion
12197 (catch 'exit
12198 (let ((pos (point)))
12199 (skip-chars-backward "^[<\r\n")
12200 (skip-chars-backward "<[")
12201 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12202 (>= (match-end 0) pos)
12203 (throw 'exit t))
12204 (skip-chars-backward "^<[\r\n")
12205 (skip-chars-backward "<[")
12206 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12207 (>= (match-end 0) pos)
12208 (throw 'exit t)))
12209 nil)))
12211 (defun org-get-repeat (&optional tagline)
12212 "Check if there is a deadline/schedule with repeater in this entry."
12213 (save-match-data
12214 (save-excursion
12215 (org-back-to-heading t)
12216 (and (re-search-forward (if tagline
12217 (concat tagline "\\s-*" org-repeat-re)
12218 org-repeat-re)
12219 (org-entry-end-position) t)
12220 (match-string-no-properties 1)))))
12222 (defvar org-last-changed-timestamp)
12223 (defvar org-last-inserted-timestamp)
12224 (defvar org-log-post-message)
12225 (defvar org-log-note-purpose)
12226 (defvar org-log-note-how)
12227 (defvar org-log-note-extra)
12228 (defun org-auto-repeat-maybe (done-word)
12229 "Check if the current headline contains a repeated deadline/schedule.
12230 If yes, set TODO state back to what it was and change the base date
12231 of repeating deadline/scheduled time stamps to new date.
12232 This function is run automatically after each state change to a DONE state."
12233 ;; last-state is dynamically scoped into this function
12234 (let* ((repeat (org-get-repeat))
12235 (aa (assoc org-last-state org-todo-kwd-alist))
12236 (interpret (nth 1 aa))
12237 (head (nth 2 aa))
12238 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12239 (msg "Entry repeats: ")
12240 (org-log-done nil)
12241 (org-todo-log-states nil)
12242 re type n what ts time to-state)
12243 (when repeat
12244 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12245 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12246 org-todo-repeat-to-state))
12247 (unless (and to-state (member to-state org-todo-keywords-1))
12248 (setq to-state (if (eq interpret 'type) org-last-state head)))
12249 (org-todo to-state)
12250 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12251 (org-entry-put nil "LAST_REPEAT" (format-time-string
12252 (org-time-stamp-format t t))))
12253 (when org-log-repeat
12254 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12255 (memq 'org-add-log-note post-command-hook))
12256 ;; OK, we are already setup for some record
12257 (if (eq org-log-repeat 'note)
12258 ;; make sure we take a note, not only a time stamp
12259 (setq org-log-note-how 'note))
12260 ;; Set up for taking a record
12261 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12262 org-last-state
12263 'findpos org-log-repeat)))
12264 (org-back-to-heading t)
12265 (org-add-planning-info nil nil 'closed)
12266 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12267 org-deadline-time-regexp "\\)\\|\\("
12268 org-ts-regexp "\\)"))
12269 (while (re-search-forward
12270 re (save-excursion (outline-next-heading) (point)) t)
12271 (setq type (if (match-end 1) org-scheduled-string
12272 (if (match-end 3) org-deadline-string "Plain:"))
12273 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12274 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12275 (setq n (string-to-number (match-string 2 ts))
12276 what (match-string 3 ts))
12277 (if (equal what "w") (setq n (* n 7) what "d"))
12278 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12279 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12280 ;; Preparation, see if we need to modify the start date for the change
12281 (when (match-end 1)
12282 (setq time (save-match-data (org-time-string-to-time ts)))
12283 (cond
12284 ((equal (match-string 1 ts) ".")
12285 ;; Shift starting date to today
12286 (org-timestamp-change
12287 (- (org-today) (time-to-days time))
12288 'day))
12289 ((equal (match-string 1 ts) "+")
12290 (let ((nshiftmax 10) (nshift 0))
12291 (while (or (= nshift 0)
12292 (<= (time-to-days time)
12293 (time-to-days (current-time))))
12294 (when (= (incf nshift) nshiftmax)
12295 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12296 (error "Abort")))
12297 (org-timestamp-change n (cdr (assoc what whata)))
12298 (org-at-timestamp-p t)
12299 (setq ts (match-string 1))
12300 (setq time (save-match-data (org-time-string-to-time ts)))))
12301 (org-timestamp-change (- n) (cdr (assoc what whata)))
12302 ;; rematch, so that we have everything in place for the real shift
12303 (org-at-timestamp-p t)
12304 (setq ts (match-string 1))
12305 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12306 (org-timestamp-change n (cdr (assoc what whata)))
12307 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12308 (setq org-log-post-message msg)
12309 (message "%s" msg))))
12311 (defun org-show-todo-tree (arg)
12312 "Make a compact tree which shows all headlines marked with TODO.
12313 The tree will show the lines where the regexp matches, and all higher
12314 headlines above the match.
12315 With a \\[universal-argument] prefix, prompt for a regexp to match.
12316 With a numeric prefix N, construct a sparse tree for the Nth element
12317 of `org-todo-keywords-1'."
12318 (interactive "P")
12319 (let ((case-fold-search nil)
12320 (kwd-re
12321 (cond ((null arg) org-not-done-regexp)
12322 ((equal arg '(4))
12323 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12324 (mapcar 'list org-todo-keywords-1))))
12325 (concat "\\("
12326 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12327 "\\)\\>")))
12328 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12329 (regexp-quote (nth (1- (prefix-numeric-value arg))
12330 org-todo-keywords-1)))
12331 (t (error "Invalid prefix argument: %s" arg)))))
12332 (message "%d TODO entries found"
12333 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12335 (defun org-deadline (&optional remove time)
12336 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12337 With argument REMOVE, remove any deadline from the item.
12338 With argument TIME, set the deadline at the corresponding date. TIME
12339 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12340 (interactive "P")
12341 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12342 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12343 'region-start-level 'region))
12344 org-loop-over-headlines-in-active-region)
12345 (org-map-entries
12346 `(org-deadline ',remove ,time)
12347 org-loop-over-headlines-in-active-region
12348 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12349 (let* ((old-date (org-entry-get nil "DEADLINE"))
12350 (repeater (and old-date
12351 (string-match
12352 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12353 old-date)
12354 (match-string 1 old-date))))
12355 (if remove
12356 (progn
12357 (when (and old-date org-log-redeadline)
12358 (org-add-log-setup 'deldeadline nil old-date 'findpos
12359 org-log-redeadline))
12360 (org-remove-timestamp-with-keyword org-deadline-string)
12361 (message "Item no longer has a deadline."))
12362 (org-add-planning-info 'deadline time 'closed)
12363 (when (and old-date org-log-redeadline
12364 (not (equal old-date
12365 (substring org-last-inserted-timestamp 1 -1))))
12366 (org-add-log-setup 'redeadline nil old-date 'findpos
12367 org-log-redeadline))
12368 (when repeater
12369 (save-excursion
12370 (org-back-to-heading t)
12371 (when (re-search-forward (concat org-deadline-string " "
12372 org-last-inserted-timestamp)
12373 (save-excursion
12374 (outline-next-heading) (point)) t)
12375 (goto-char (1- (match-end 0)))
12376 (insert " " repeater)
12377 (setq org-last-inserted-timestamp
12378 (concat (substring org-last-inserted-timestamp 0 -1)
12379 " " repeater
12380 (substring org-last-inserted-timestamp -1))))))
12381 (message "Deadline on %s" org-last-inserted-timestamp)))))
12383 (defun org-schedule (&optional remove time)
12384 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12385 With argument REMOVE, remove any scheduling date from the item.
12386 With argument TIME, scheduled at the corresponding date. TIME can
12387 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12388 (interactive "P")
12389 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12390 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12391 'region-start-level 'region))
12392 org-loop-over-headlines-in-active-region)
12393 (org-map-entries
12394 `(org-schedule ',remove ,time)
12395 org-loop-over-headlines-in-active-region
12396 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12397 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12398 (repeater (and old-date
12399 (string-match
12400 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12401 old-date)
12402 (match-string 1 old-date))))
12403 (if remove
12404 (progn
12405 (when (and old-date org-log-reschedule)
12406 (org-add-log-setup 'delschedule nil old-date 'findpos
12407 org-log-reschedule))
12408 (org-remove-timestamp-with-keyword org-scheduled-string)
12409 (message "Item is no longer scheduled."))
12410 (org-add-planning-info 'scheduled time 'closed)
12411 (when (and old-date org-log-reschedule
12412 (not (equal old-date
12413 (substring org-last-inserted-timestamp 1 -1))))
12414 (org-add-log-setup 'reschedule nil old-date 'findpos
12415 org-log-reschedule))
12416 (when repeater
12417 (save-excursion
12418 (org-back-to-heading t)
12419 (when (re-search-forward (concat org-scheduled-string " "
12420 org-last-inserted-timestamp)
12421 (save-excursion
12422 (outline-next-heading) (point)) t)
12423 (goto-char (1- (match-end 0)))
12424 (insert " " repeater)
12425 (setq org-last-inserted-timestamp
12426 (concat (substring org-last-inserted-timestamp 0 -1)
12427 " " repeater
12428 (substring org-last-inserted-timestamp -1))))))
12429 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12431 (defun org-get-scheduled-time (pom &optional inherit)
12432 "Get the scheduled time as a time tuple, of a format suitable
12433 for calling org-schedule with, or if there is no scheduling,
12434 returns nil."
12435 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12436 (when time
12437 (apply 'encode-time (org-parse-time-string time)))))
12439 (defun org-get-deadline-time (pom &optional inherit)
12440 "Get the deadline as a time tuple, of a format suitable for
12441 calling org-deadline with, or if there is no scheduling, returns
12442 nil."
12443 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12444 (when time
12445 (apply 'encode-time (org-parse-time-string time)))))
12447 (defun org-remove-timestamp-with-keyword (keyword)
12448 "Remove all time stamps with KEYWORD in the current entry."
12449 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12450 beg)
12451 (save-excursion
12452 (org-back-to-heading t)
12453 (setq beg (point))
12454 (outline-next-heading)
12455 (while (re-search-backward re beg t)
12456 (replace-match "")
12457 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12458 (equal (char-before) ?\ ))
12459 (backward-delete-char 1)
12460 (if (string-match "^[ \t]*$" (buffer-substring
12461 (point-at-bol) (point-at-eol)))
12462 (delete-region (point-at-bol)
12463 (min (point-max) (1+ (point-at-eol))))))))))
12465 (defun org-add-planning-info (what &optional time &rest remove)
12466 "Insert new timestamp with keyword in the line directly after the headline.
12467 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12468 If non is given, the user is prompted for a date.
12469 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12470 be removed."
12471 (interactive)
12472 (let (org-time-was-given org-end-time-was-given ts
12473 end default-time default-input)
12475 (catch 'exit
12476 (when (and (memq what '(scheduled deadline))
12477 (or (not time)
12478 (and (stringp time)
12479 (string-match "^[-+]+[0-9]" time))))
12480 ;; Try to get a default date/time from existing timestamp
12481 (save-excursion
12482 (org-back-to-heading t)
12483 (setq end (save-excursion (outline-next-heading) (point)))
12484 (when (re-search-forward (if (eq what 'scheduled)
12485 org-scheduled-time-regexp
12486 org-deadline-time-regexp)
12487 end t)
12488 (setq ts (match-string 1)
12489 default-time
12490 (apply 'encode-time (org-parse-time-string ts))
12491 default-input (and ts (org-get-compact-tod ts))))))
12492 (when what
12493 (setq time
12494 (if (stringp time)
12495 ;; This is a string (relative or absolute), set proper date
12496 (apply 'encode-time
12497 (org-read-date-analyze
12498 time default-time (decode-time default-time)))
12499 ;; If necessary, get the time from the user
12500 (or time (org-read-date nil 'to-time nil nil
12501 default-time default-input)))))
12503 (when (and org-insert-labeled-timestamps-at-point
12504 (member what '(scheduled deadline)))
12505 (insert
12506 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12507 (org-insert-time-stamp time org-time-was-given
12508 nil nil nil (list org-end-time-was-given))
12509 (setq what nil))
12510 (save-excursion
12511 (save-restriction
12512 (let (col list elt ts buffer-invisibility-spec)
12513 (org-back-to-heading t)
12514 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12515 (goto-char (match-end 1))
12516 (setq col (current-column))
12517 (goto-char (match-end 0))
12518 (if (eobp) (insert "\n") (forward-char 1))
12519 (when (and (not what)
12520 (not (looking-at
12521 (concat "[ \t]*"
12522 org-keyword-time-not-clock-regexp))))
12523 ;; Nothing to add, nothing to remove...... :-)
12524 (throw 'exit nil))
12525 (if (and (not (looking-at org-outline-regexp))
12526 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12527 "[^\r\n]*"))
12528 (not (equal (match-string 1) org-clock-string)))
12529 (narrow-to-region (match-beginning 0) (match-end 0))
12530 (insert-before-markers "\n")
12531 (backward-char 1)
12532 (narrow-to-region (point) (point))
12533 (and org-adapt-indentation (org-indent-to-column col)))
12534 ;; Check if we have to remove something.
12535 (setq list (cons what remove))
12536 (while list
12537 (setq elt (pop list))
12538 (when (or (and (eq elt 'scheduled)
12539 (re-search-forward org-scheduled-time-regexp nil t))
12540 (and (eq elt 'deadline)
12541 (re-search-forward org-deadline-time-regexp nil t))
12542 (and (eq elt 'closed)
12543 (re-search-forward org-closed-time-regexp nil t)))
12544 (replace-match "")
12545 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12546 (and (looking-at "[ \t]+") (replace-match ""))
12547 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12548 (when what
12549 (insert
12550 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12551 (cond ((eq what 'scheduled) org-scheduled-string)
12552 ((eq what 'deadline) org-deadline-string)
12553 ((eq what 'closed) org-closed-string))
12554 " ")
12555 (setq ts (org-insert-time-stamp
12556 time
12557 (or org-time-was-given
12558 (and (eq what 'closed) org-log-done-with-time))
12559 (eq what 'closed)
12560 nil nil (list org-end-time-was-given)))
12561 (insert
12562 (if (not (or (bolp) (eq (char-before) ?\ )
12563 (memq (char-after) '(32 10))
12564 (eobp))) " " ""))
12565 (end-of-line 1))
12566 (goto-char (point-min))
12567 (widen)
12568 (if (and (looking-at "[ \t]*\n")
12569 (equal (char-before) ?\n))
12570 (delete-region (1- (point)) (point-at-eol)))
12571 ts))))))
12573 (defvar org-log-note-marker (make-marker))
12574 (defvar org-log-note-purpose nil)
12575 (defvar org-log-note-state nil)
12576 (defvar org-log-note-previous-state nil)
12577 (defvar org-log-note-how nil)
12578 (defvar org-log-note-extra nil)
12579 (defvar org-log-note-window-configuration nil)
12580 (defvar org-log-note-return-to (make-marker))
12581 (defvar org-log-note-effective-time nil
12582 "Remembered current time so that dynamically scoped
12583 `org-extend-today-until' affects tha timestamps in state change
12584 log")
12586 (defvar org-log-post-message nil
12587 "Message to be displayed after a log note has been stored.
12588 The auto-repeater uses this.")
12590 (defun org-add-note ()
12591 "Add a note to the current entry.
12592 This is done in the same way as adding a state change note."
12593 (interactive)
12594 (org-add-log-setup 'note nil nil 'findpos nil))
12596 (defvar org-property-end-re)
12597 (defun org-add-log-setup (&optional purpose state prev-state
12598 findpos how extra)
12599 "Set up the post command hook to take a note.
12600 If this is about to TODO state change, the new state is expected in STATE.
12601 When FINDPOS is non-nil, find the correct position for the note in
12602 the current entry. If not, assume that it can be inserted at point.
12603 HOW is an indicator what kind of note should be created.
12604 EXTRA is additional text that will be inserted into the notes buffer."
12605 (let* ((org-log-into-drawer (org-log-into-drawer))
12606 (drawer (cond ((stringp org-log-into-drawer)
12607 org-log-into-drawer)
12608 (org-log-into-drawer "LOGBOOK"))))
12609 (save-restriction
12610 (save-excursion
12611 (when findpos
12612 (org-back-to-heading t)
12613 (narrow-to-region (point) (save-excursion
12614 (outline-next-heading) (point)))
12615 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12616 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12617 "[^\r\n]*\\)?"))
12618 (goto-char (match-end 0))
12619 (cond
12620 (drawer
12621 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12622 nil t)
12623 (progn
12624 (goto-char (match-end 0))
12625 (or org-log-states-order-reversed
12626 (and (re-search-forward org-property-end-re nil t)
12627 (goto-char (1- (match-beginning 0))))))
12628 (insert "\n:" drawer ":\n:END:")
12629 (beginning-of-line 0)
12630 (org-indent-line)
12631 (beginning-of-line 2)
12632 (org-indent-line)
12633 (end-of-line 0)))
12634 ((and org-log-state-notes-insert-after-drawers
12635 (save-excursion
12636 (forward-line) (looking-at org-drawer-regexp)))
12637 (forward-line)
12638 (while (looking-at org-drawer-regexp)
12639 (goto-char (match-end 0))
12640 (re-search-forward org-property-end-re (point-max) t)
12641 (forward-line))
12642 (forward-line -1)))
12643 (unless org-log-states-order-reversed
12644 (and (= (char-after) ?\n) (forward-char 1))
12645 (org-skip-over-state-notes)
12646 (skip-chars-backward " \t\n\r")))
12647 (move-marker org-log-note-marker (point))
12648 (setq org-log-note-purpose purpose
12649 org-log-note-state state
12650 org-log-note-previous-state prev-state
12651 org-log-note-how how
12652 org-log-note-extra extra
12653 org-log-note-effective-time (org-current-effective-time))
12654 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12656 (defun org-skip-over-state-notes ()
12657 "Skip past the list of State notes in an entry."
12658 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12659 (when (ignore-errors (goto-char (org-in-item-p)))
12660 (let* ((struct (org-list-struct))
12661 (prevs (org-list-prevs-alist struct)))
12662 (while (looking-at "[ \t]*- State")
12663 (goto-char (or (org-list-get-next-item (point) struct prevs)
12664 (org-list-get-item-end (point) struct)))))))
12666 (defun org-add-log-note (&optional purpose)
12667 "Pop up a window for taking a note, and add this note later at point."
12668 (remove-hook 'post-command-hook 'org-add-log-note)
12669 (setq org-log-note-window-configuration (current-window-configuration))
12670 (delete-other-windows)
12671 (move-marker org-log-note-return-to (point))
12672 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12673 (goto-char org-log-note-marker)
12674 (org-switch-to-buffer-other-window "*Org Note*")
12675 (erase-buffer)
12676 (if (memq org-log-note-how '(time state))
12677 (let (current-prefix-arg) (org-store-log-note))
12678 (let ((org-inhibit-startup t)) (org-mode))
12679 (insert (format "# Insert note for %s.
12680 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12681 (cond
12682 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12683 ((eq org-log-note-purpose 'done) "closed todo item")
12684 ((eq org-log-note-purpose 'state)
12685 (format "state change from \"%s\" to \"%s\""
12686 (or org-log-note-previous-state "")
12687 (or org-log-note-state "")))
12688 ((eq org-log-note-purpose 'reschedule)
12689 "rescheduling")
12690 ((eq org-log-note-purpose 'delschedule)
12691 "no longer scheduled")
12692 ((eq org-log-note-purpose 'redeadline)
12693 "changing deadline")
12694 ((eq org-log-note-purpose 'deldeadline)
12695 "removing deadline")
12696 ((eq org-log-note-purpose 'refile)
12697 "refiling")
12698 ((eq org-log-note-purpose 'note)
12699 "this entry")
12700 (t (error "This should not happen")))))
12701 (if org-log-note-extra (insert org-log-note-extra))
12702 (org-set-local 'org-finish-function 'org-store-log-note)
12703 (run-hooks 'org-log-buffer-setup-hook)))
12705 (defvar org-note-abort nil) ; dynamically scoped
12706 (defun org-store-log-note ()
12707 "Finish taking a log note, and insert it to where it belongs."
12708 (let ((txt (buffer-string))
12709 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12710 lines ind bul)
12711 (kill-buffer (current-buffer))
12712 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12713 (setq txt (replace-match "" t t txt)))
12714 (if (string-match "\\s-+\\'" txt)
12715 (setq txt (replace-match "" t t txt)))
12716 (setq lines (org-split-string txt "\n"))
12717 (when (and note (string-match "\\S-" note))
12718 (setq note
12719 (org-replace-escapes
12720 note
12721 (list (cons "%u" (user-login-name))
12722 (cons "%U" user-full-name)
12723 (cons "%t" (format-time-string
12724 (org-time-stamp-format 'long 'inactive)
12725 org-log-note-effective-time))
12726 (cons "%T" (format-time-string
12727 (org-time-stamp-format 'long nil)
12728 org-log-note-effective-time))
12729 (cons "%d" (format-time-string
12730 (org-time-stamp-format nil 'inactive)
12731 org-log-note-effective-time))
12732 (cons "%D" (format-time-string
12733 (org-time-stamp-format nil nil)
12734 org-log-note-effective-time))
12735 (cons "%s" (if org-log-note-state
12736 (concat "\"" org-log-note-state "\"")
12737 ""))
12738 (cons "%S" (if org-log-note-previous-state
12739 (concat "\"" org-log-note-previous-state "\"")
12740 "\"\"")))))
12741 (if lines (setq note (concat note " \\\\")))
12742 (push note lines))
12743 (when (or current-prefix-arg org-note-abort)
12744 (when org-log-into-drawer
12745 (org-remove-empty-drawer-at
12746 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12747 org-log-note-marker))
12748 (setq lines nil))
12749 (when lines
12750 (with-current-buffer (marker-buffer org-log-note-marker)
12751 (save-excursion
12752 (goto-char org-log-note-marker)
12753 (move-marker org-log-note-marker nil)
12754 (end-of-line 1)
12755 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12756 (setq ind (save-excursion
12757 (if (ignore-errors (goto-char (org-in-item-p)))
12758 (let ((struct (org-list-struct)))
12759 (org-list-get-ind
12760 (org-list-get-top-point struct) struct))
12761 (skip-chars-backward " \r\t\n")
12762 (cond
12763 ((and (org-at-heading-p)
12764 org-adapt-indentation)
12765 (1+ (org-current-level)))
12766 ((org-at-heading-p) 0)
12767 (t (org-get-indentation))))))
12768 (setq bul (org-list-bullet-string "-"))
12769 (org-indent-line-to ind)
12770 (insert bul (pop lines))
12771 (let ((ind-body (+ (length bul) ind)))
12772 (while lines
12773 (insert "\n")
12774 (org-indent-line-to ind-body)
12775 (insert (pop lines))))
12776 (message "Note stored")
12777 (org-back-to-heading t)
12778 (org-cycle-hide-drawers 'children)))))
12779 (set-window-configuration org-log-note-window-configuration)
12780 (with-current-buffer (marker-buffer org-log-note-return-to)
12781 (goto-char org-log-note-return-to))
12782 (move-marker org-log-note-return-to nil)
12783 (and org-log-post-message (message "%s" org-log-post-message)))
12785 (defun org-remove-empty-drawer-at (drawer pos)
12786 "Remove an empty drawer DRAWER at position POS.
12787 POS may also be a marker."
12788 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12789 (save-excursion
12790 (save-restriction
12791 (widen)
12792 (goto-char pos)
12793 (if (org-in-regexp
12794 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12795 (replace-match ""))))))
12797 (defvar org-ts-type nil)
12798 (defun org-sparse-tree (&optional arg type)
12799 "Create a sparse tree, prompt for the details.
12800 This command can create sparse trees. You first need to select the type
12801 of match used to create the tree:
12803 t Show all TODO entries.
12804 T Show entries with a specific TODO keyword.
12805 m Show entries selected by a tags/property match.
12806 p Enter a property name and its value (both with completion on existing
12807 names/values) and show entries with that property.
12808 r Show entries matching a regular expression (`/' can be used as well).
12809 b Show deadlines and scheduled items before a date.
12810 a Show deadlines and scheduled items after a date.
12811 d Show deadlines due within `org-deadline-warning-days'.
12812 D Show deadlines and scheduled items between a date range."
12813 (interactive "P")
12814 (let (ans kwd value ts-type)
12815 (setq type (or type org-sparse-tree-default-date-type))
12816 (setq org-ts-type type)
12817 (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"
12818 (cond ((eq type 'all) "all timestamps")
12819 ((eq type 'scheduled) "only scheduled")
12820 ((eq type 'deadline) "only deadline")
12821 ((eq type 'active) "only active timestamps")
12822 ((eq type 'inactive) "only inactive timestamps")
12823 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12824 (t "scheduled/deadline")))
12825 (setq ans (read-char-exclusive))
12826 (cond
12827 ((equal ans ?c)
12828 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12829 ((equal ans ?d)
12830 (call-interactively 'org-check-deadlines))
12831 ((equal ans ?b)
12832 (call-interactively 'org-check-before-date))
12833 ((equal ans ?a)
12834 (call-interactively 'org-check-after-date))
12835 ((equal ans ?D)
12836 (call-interactively 'org-check-dates-range))
12837 ((equal ans ?t)
12838 (org-show-todo-tree nil))
12839 ((equal ans ?T)
12840 (org-show-todo-tree '(4)))
12841 ((member ans '(?T ?m))
12842 (call-interactively 'org-match-sparse-tree))
12843 ((member ans '(?p ?P))
12844 (setq kwd (org-icompleting-read "Property: "
12845 (mapcar 'list (org-buffer-property-keys))))
12846 (setq value (org-icompleting-read "Value: "
12847 (mapcar 'list (org-property-values kwd))))
12848 (unless (string-match "\\`{.*}\\'" value)
12849 (setq value (concat "\"" value "\"")))
12850 (org-match-sparse-tree arg (concat kwd "=" value)))
12851 ((member ans '(?r ?R ?/))
12852 (call-interactively 'org-occur))
12853 (t (error "No such sparse tree command \"%c\"" ans)))))
12855 (defvar org-occur-highlights nil
12856 "List of overlays used for occur matches.")
12857 (make-variable-buffer-local 'org-occur-highlights)
12858 (defvar org-occur-parameters nil
12859 "Parameters of the active org-occur calls.
12860 This is a list, each call to org-occur pushes as cons cell,
12861 containing the regular expression and the callback, onto the list.
12862 The list can contain several entries if `org-occur' has been called
12863 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12864 will only contain one set of parameters. When the highlights are
12865 removed (for example with `C-c C-c', or with the next edit (depending
12866 on `org-remove-highlights-with-change'), this variable is emptied
12867 as well.")
12868 (make-variable-buffer-local 'org-occur-parameters)
12870 (defun org-occur (regexp &optional keep-previous callback)
12871 "Make a compact tree which shows all matches of REGEXP.
12872 The tree will show the lines where the regexp matches, and all higher
12873 headlines above the match. It will also show the heading after the match,
12874 to make sure editing the matching entry is easy.
12875 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12876 call to `org-occur' will be kept, to allow stacking of calls to this
12877 command.
12878 If CALLBACK is non-nil, it is a function which is called to confirm
12879 that the match should indeed be shown."
12880 (interactive "sRegexp: \nP")
12881 (when (equal regexp "")
12882 (error "Regexp cannot be empty"))
12883 (unless keep-previous
12884 (org-remove-occur-highlights nil nil t))
12885 (push (cons regexp callback) org-occur-parameters)
12886 (let ((cnt 0))
12887 (save-excursion
12888 (goto-char (point-min))
12889 (if (or (not keep-previous) ; do not want to keep
12890 (not org-occur-highlights)) ; no previous matches
12891 ;; hide everything
12892 (org-overview))
12893 (while (re-search-forward regexp nil t)
12894 (when (or (not callback)
12895 (save-match-data (funcall callback)))
12896 (setq cnt (1+ cnt))
12897 (when org-highlight-sparse-tree-matches
12898 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12899 (org-show-context 'occur-tree))))
12900 (when org-remove-highlights-with-change
12901 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12902 nil 'local))
12903 (unless org-sparse-tree-open-archived-trees
12904 (org-hide-archived-subtrees (point-min) (point-max)))
12905 (run-hooks 'org-occur-hook)
12906 (if (org-called-interactively-p 'interactive)
12907 (message "%d match(es) for regexp %s" cnt regexp))
12908 cnt))
12910 (defun org-occur-next-match (&optional n reset)
12911 "Function for `next-error-function' to find sparse tree matches.
12912 N is the number of matches to move, when negative move backwards.
12913 RESET is entirely ignored - this function always goes back to the
12914 starting point when no match is found."
12915 (let* ((limit (if (< n 0) (point-min) (point-max)))
12916 (search-func (if (< n 0)
12917 'previous-single-char-property-change
12918 'next-single-char-property-change))
12919 (n (abs n))
12920 (pos (point))
12922 (catch 'exit
12923 (while (setq p1 (funcall search-func (point) 'org-type))
12924 (when (equal p1 limit)
12925 (goto-char pos)
12926 (error "No more matches"))
12927 (when (equal (get-char-property p1 'org-type) 'org-occur)
12928 (setq n (1- n))
12929 (when (= n 0)
12930 (goto-char p1)
12931 (throw 'exit (point))))
12932 (goto-char p1))
12933 (goto-char p1)
12934 (error "No more matches"))))
12936 (defun org-show-context (&optional key)
12937 "Make sure point and context are visible.
12938 How much context is shown depends upon the variables
12939 `org-show-hierarchy-above', `org-show-following-heading',
12940 `org-show-entry-below' and `org-show-siblings'."
12941 (let ((heading-p (org-at-heading-p t))
12942 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12943 (following-p (org-get-alist-option org-show-following-heading key))
12944 (entry-p (org-get-alist-option org-show-entry-below key))
12945 (siblings-p (org-get-alist-option org-show-siblings key)))
12946 (catch 'exit
12947 ;; Show heading or entry text
12948 (if (and heading-p (not entry-p))
12949 (org-flag-heading nil) ; only show the heading
12950 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12951 (org-show-hidden-entry))) ; show entire entry
12952 (when following-p
12953 ;; Show next sibling, or heading below text
12954 (save-excursion
12955 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12956 (org-flag-heading nil))))
12957 (when siblings-p (org-show-siblings))
12958 (when hierarchy-p
12959 ;; show all higher headings, possibly with siblings
12960 (save-excursion
12961 (while (and (condition-case nil
12962 (progn (org-up-heading-all 1) t)
12963 (error nil))
12964 (not (bobp)))
12965 (org-flag-heading nil)
12966 (when siblings-p (org-show-siblings))))))))
12968 (defvar org-reveal-start-hook nil
12969 "Hook run before revealing a location.")
12971 (defun org-reveal (&optional siblings)
12972 "Show current entry, hierarchy above it, and the following headline.
12973 This can be used to show a consistent set of context around locations
12974 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12975 not t for the search context.
12977 With optional argument SIBLINGS, on each level of the hierarchy all
12978 siblings are shown. This repairs the tree structure to what it would
12979 look like when opened with hierarchical calls to `org-cycle'.
12980 With double optional argument \\[universal-argument] \\[universal-argument], \
12981 go to the parent and show the
12982 entire tree."
12983 (interactive "P")
12984 (run-hooks 'org-reveal-start-hook)
12985 (let ((org-show-hierarchy-above t)
12986 (org-show-following-heading t)
12987 (org-show-siblings (if siblings t org-show-siblings)))
12988 (org-show-context nil))
12989 (when (equal siblings '(16))
12990 (save-excursion
12991 (when (org-up-heading-safe)
12992 (org-show-subtree)
12993 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12995 (defun org-highlight-new-match (beg end)
12996 "Highlight from BEG to END and mark the highlight is an occur headline."
12997 (let ((ov (make-overlay beg end)))
12998 (overlay-put ov 'face 'secondary-selection)
12999 (overlay-put ov 'org-type 'org-occur)
13000 (push ov org-occur-highlights)))
13002 (defun org-remove-occur-highlights (&optional beg end noremove)
13003 "Remove the occur highlights from the buffer.
13004 BEG and END are ignored. If NOREMOVE is nil, remove this function
13005 from the `before-change-functions' in the current buffer."
13006 (interactive)
13007 (unless org-inhibit-highlight-removal
13008 (mapc 'delete-overlay org-occur-highlights)
13009 (setq org-occur-highlights nil)
13010 (setq org-occur-parameters nil)
13011 (unless noremove
13012 (remove-hook 'before-change-functions
13013 'org-remove-occur-highlights 'local))))
13015 ;;;; Priorities
13017 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13018 "Regular expression matching the priority indicator.")
13020 (defvar org-remove-priority-next-time nil)
13022 (defun org-priority-up ()
13023 "Increase the priority of the current item."
13024 (interactive)
13025 (org-priority 'up))
13027 (defun org-priority-down ()
13028 "Decrease the priority of the current item."
13029 (interactive)
13030 (org-priority 'down))
13032 (defun org-priority (&optional action)
13033 "Change the priority of an item.
13034 ACTION can be `set', `up', `down', or a character."
13035 (interactive)
13036 (unless org-enable-priority-commands
13037 (error "Priority commands are disabled"))
13038 (setq action (or action 'set))
13039 (let (current new news have remove)
13040 (save-excursion
13041 (org-back-to-heading t)
13042 (if (looking-at org-priority-regexp)
13043 (setq current (string-to-char (match-string 2))
13044 have t))
13045 (cond
13046 ((eq action 'remove)
13047 (setq remove t new ?\ ))
13048 ((or (eq action 'set)
13049 (if (featurep 'xemacs) (characterp action) (integerp action)))
13050 (if (not (eq action 'set))
13051 (setq new action)
13052 (message "Priority %c-%c, SPC to remove: "
13053 org-highest-priority org-lowest-priority)
13054 (save-match-data
13055 (setq new (read-char-exclusive))))
13056 (if (and (= (upcase org-highest-priority) org-highest-priority)
13057 (= (upcase org-lowest-priority) org-lowest-priority))
13058 (setq new (upcase new)))
13059 (cond ((equal new ?\ ) (setq remove t))
13060 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13061 (error "Priority must be between `%c' and `%c'"
13062 org-highest-priority org-lowest-priority))))
13063 ((eq action 'up)
13064 (setq new (if have
13065 (1- current) ; normal cycling
13066 ;; last priority was empty
13067 (if (eq last-command this-command)
13068 org-lowest-priority ; wrap around empty to lowest
13069 ;; default
13070 (if org-priority-start-cycle-with-default
13071 org-default-priority
13072 (1- org-default-priority))))))
13073 ((eq action 'down)
13074 (setq new (if have
13075 (1+ current) ; normal cycling
13076 ;; last priority was empty
13077 (if (eq last-command this-command)
13078 org-highest-priority ; wrap around empty to highest
13079 ;; default
13080 (if org-priority-start-cycle-with-default
13081 org-default-priority
13082 (1+ org-default-priority))))))
13083 (t (error "Invalid action")))
13084 (if (or (< (upcase new) org-highest-priority)
13085 (> (upcase new) org-lowest-priority))
13086 (if (and (memq action '(up down))
13087 (not have) (not (eq last-command this-command)))
13088 ;; `new' is from default priority
13089 (error
13090 "The default can not be set, see `org-default-priority' why")
13091 ;; normal cycling: `new' is beyond highest/lowest priority
13092 ;; and is wrapped around to the empty priority
13093 (setq remove t)))
13094 (setq news (format "%c" new))
13095 (if have
13096 (if remove
13097 (replace-match "" t t nil 1)
13098 (replace-match news t t nil 2))
13099 (if remove
13100 (error "No priority cookie found in line")
13101 (let ((case-fold-search nil))
13102 (looking-at org-todo-line-regexp))
13103 (if (match-end 2)
13104 (progn
13105 (goto-char (match-end 2))
13106 (insert " [#" news "]"))
13107 (goto-char (match-beginning 3))
13108 (insert "[#" news "] "))))
13109 (org-preserve-lc (org-set-tags nil 'align)))
13110 (if remove
13111 (message "Priority removed")
13112 (message "Priority of current item set to %s" news))))
13114 (defun org-get-priority (s)
13115 "Find priority cookie and return priority."
13116 (if (functionp org-get-priority-function)
13117 (funcall org-get-priority-function)
13118 (save-match-data
13119 (if (not (string-match org-priority-regexp s))
13120 (* 1000 (- org-lowest-priority org-default-priority))
13121 (* 1000 (- org-lowest-priority
13122 (string-to-char (match-string 2 s))))))))
13124 ;;;; Tags
13126 (defvar org-agenda-archives-mode)
13127 (defvar org-map-continue-from nil
13128 "Position from where mapping should continue.
13129 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13131 (defvar org-scanner-tags nil
13132 "The current tag list while the tags scanner is running.")
13133 (defvar org-trust-scanner-tags nil
13134 "Should `org-get-tags-at' use the tags for the scanner.
13135 This is for internal dynamical scoping only.
13136 When this is non-nil, the function `org-get-tags-at' will return the value
13137 of `org-scanner-tags' instead of building the list by itself. This
13138 can lead to large speed-ups when the tags scanner is used in a file with
13139 many entries, and when the list of tags is retrieved, for example to
13140 obtain a list of properties. Building the tags list for each entry in such
13141 a file becomes an N^2 operation - but with this variable set, it scales
13142 as N.")
13144 (defun org-scan-tags (action matcher todo-only &optional start-level)
13145 "Scan headline tags with inheritance and produce output ACTION.
13147 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13148 or `agenda' to produce an entry list for an agenda view. It can also be
13149 a Lisp form or a function that should be called at each matched headline, in
13150 this case the return value is a list of all return values from these calls.
13152 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13153 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13154 only lines with a not-done TODO keyword are included in the output.
13155 This should be the same variable that was scoped into
13156 and set by `org-make-tags-matcher' when it constructed MATCHER.
13158 START-LEVEL can be a string with asterisks, reducing the scope to
13159 headlines matching this string."
13160 (require 'org-agenda)
13161 (let* ((re (concat "^"
13162 (if start-level
13163 ;; Get the correct level to match
13164 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13165 org-outline-regexp)
13166 " *\\(\\<\\("
13167 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13168 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13169 (props (list 'face 'default
13170 'done-face 'org-agenda-done
13171 'undone-face 'default
13172 'mouse-face 'highlight
13173 'org-not-done-regexp org-not-done-regexp
13174 'org-todo-regexp org-todo-regexp
13175 'org-complex-heading-regexp org-complex-heading-regexp
13176 'help-echo
13177 (format "mouse-2 or RET jump to org file %s"
13178 (abbreviate-file-name
13179 (or (buffer-file-name (buffer-base-buffer))
13180 (buffer-name (buffer-base-buffer)))))))
13181 (case-fold-search nil)
13182 (org-map-continue-from nil)
13183 lspos tags tags-list
13184 (tags-alist (list (cons 0 org-file-tags)))
13185 (llast 0) rtn rtn1 level category i txt
13186 todo marker entry priority)
13187 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13188 (setq action (list 'lambda nil action)))
13189 (save-excursion
13190 (goto-char (point-min))
13191 (when (eq action 'sparse-tree)
13192 (org-overview)
13193 (org-remove-occur-highlights))
13194 (while (re-search-forward re nil t)
13195 (setq org-map-continue-from nil)
13196 (catch :skip
13197 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13198 tags (if (match-end 4) (org-match-string-no-properties 4)))
13199 (goto-char (setq lspos (match-beginning 0)))
13200 (setq level (org-reduced-level (funcall outline-level))
13201 category (org-get-category))
13202 (setq i llast llast level)
13203 ;; remove tag lists from same and sublevels
13204 (while (>= i level)
13205 (when (setq entry (assoc i tags-alist))
13206 (setq tags-alist (delete entry tags-alist)))
13207 (setq i (1- i)))
13208 ;; add the next tags
13209 (when tags
13210 (setq tags (org-split-string tags ":")
13211 tags-alist
13212 (cons (cons level tags) tags-alist)))
13213 ;; compile tags for current headline
13214 (setq tags-list
13215 (if org-use-tag-inheritance
13216 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13217 tags)
13218 org-scanner-tags tags-list)
13219 (when org-use-tag-inheritance
13220 (setcdr (car tags-alist)
13221 (mapcar (lambda (x)
13222 (setq x (copy-sequence x))
13223 (org-add-prop-inherited x))
13224 (cdar tags-alist))))
13225 (when (and tags org-use-tag-inheritance
13226 (or (not (eq t org-use-tag-inheritance))
13227 org-tags-exclude-from-inheritance))
13228 ;; selective inheritance, remove uninherited ones
13229 (setcdr (car tags-alist)
13230 (org-remove-uninherited-tags (cdar tags-alist))))
13231 (when (and
13233 ;; eval matcher only when the todo condition is OK
13234 (and (or (not todo-only) (member todo org-not-done-keywords))
13235 (let ((case-fold-search t) (org-trust-scanner-tags t))
13236 (eval matcher)))
13238 ;; Call the skipper, but return t if it does not skip,
13239 ;; so that the `and' form continues evaluating
13240 (progn
13241 (unless (eq action 'sparse-tree) (org-agenda-skip))
13244 ;; Check if timestamps are deselecting this entry
13245 (or (not todo-only)
13246 (and (member todo org-not-done-keywords)
13247 (or (not org-agenda-tags-todo-honor-ignore-options)
13248 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13250 ;; Extra check for the archive tag
13251 ;; FIXME: Does the skipper already do this????
13253 (not (member org-archive-tag tags-list))
13254 ;; we have an archive tag, should we use this anyway?
13255 (or (not org-agenda-skip-archived-trees)
13256 (and (eq action 'agenda) org-agenda-archives-mode))))
13258 ;; select this headline
13260 (cond
13261 ((eq action 'sparse-tree)
13262 (and org-highlight-sparse-tree-matches
13263 (org-get-heading) (match-end 0)
13264 (org-highlight-new-match
13265 (match-beginning 1) (match-end 1)))
13266 (org-show-context 'tags-tree))
13267 ((eq action 'agenda)
13268 (setq txt (org-agenda-format-item
13270 (concat
13271 (if (eq org-tags-match-list-sublevels 'indented)
13272 (make-string (1- level) ?.) "")
13273 (org-get-heading))
13274 category
13275 tags-list)
13276 priority (org-get-priority txt))
13277 (goto-char lspos)
13278 (setq marker (org-agenda-new-marker))
13279 (org-add-props txt props
13280 'org-marker marker 'org-hd-marker marker 'org-category category
13281 'todo-state todo
13282 'priority priority 'type "tagsmatch")
13283 (push txt rtn))
13284 ((functionp action)
13285 (setq org-map-continue-from nil)
13286 (save-excursion
13287 (setq rtn1 (funcall action))
13288 (push rtn1 rtn)))
13289 (t (error "Invalid action")))
13291 ;; if we are to skip sublevels, jump to end of subtree
13292 (unless org-tags-match-list-sublevels
13293 (org-end-of-subtree t)
13294 (backward-char 1))))
13295 ;; Get the correct position from where to continue
13296 (if org-map-continue-from
13297 (goto-char org-map-continue-from)
13298 (and (= (point) lspos) (end-of-line 1)))))
13299 (when (and (eq action 'sparse-tree)
13300 (not org-sparse-tree-open-archived-trees))
13301 (org-hide-archived-subtrees (point-min) (point-max)))
13302 (nreverse rtn)))
13304 (defun org-remove-uninherited-tags (tags)
13305 "Remove all tags that are not inherited from the list TAGS."
13306 (cond
13307 ((eq org-use-tag-inheritance t)
13308 (if org-tags-exclude-from-inheritance
13309 (org-delete-all org-tags-exclude-from-inheritance tags)
13310 tags))
13311 ((not org-use-tag-inheritance) nil)
13312 ((stringp org-use-tag-inheritance)
13313 (delq nil (mapcar
13314 (lambda (x)
13315 (if (and (string-match org-use-tag-inheritance x)
13316 (not (member x org-tags-exclude-from-inheritance)))
13317 x nil))
13318 tags)))
13319 ((listp org-use-tag-inheritance)
13320 (delq nil (mapcar
13321 (lambda (x)
13322 (if (member x org-use-tag-inheritance) x nil))
13323 tags)))))
13325 (defun org-match-sparse-tree (&optional todo-only match)
13326 "Create a sparse tree according to tags string MATCH.
13327 MATCH can contain positive and negative selection of tags, like
13328 \"+WORK+URGENT-WITHBOSS\".
13329 If optional argument TODO-ONLY is non-nil, only select lines that are
13330 also TODO lines."
13331 (interactive "P")
13332 (org-agenda-prepare-buffers (list (current-buffer)))
13333 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13335 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13337 (defvar org-cached-props nil)
13338 (defun org-cached-entry-get (pom property)
13339 (if (or (eq t org-use-property-inheritance)
13340 (and (stringp org-use-property-inheritance)
13341 (string-match org-use-property-inheritance property))
13342 (and (listp org-use-property-inheritance)
13343 (member property org-use-property-inheritance)))
13344 ;; Caching is not possible, check it directly
13345 (org-entry-get pom property 'inherit)
13346 ;; Get all properties, so that we can do complicated checks easily
13347 (cdr (assoc property (or org-cached-props
13348 (setq org-cached-props
13349 (org-entry-properties pom)))))))
13351 (defun org-global-tags-completion-table (&optional files)
13352 "Return the list of all tags in all agenda buffer/files.
13353 Optional FILES argument is a list of files which can be used
13354 instead of the agenda files."
13355 (save-excursion
13356 (org-uniquify
13357 (delq nil
13358 (apply 'append
13359 (mapcar
13360 (lambda (file)
13361 (set-buffer (find-file-noselect file))
13362 (append (org-get-buffer-tags)
13363 (mapcar (lambda (x) (if (stringp (car-safe x))
13364 (list (car-safe x)) nil))
13365 org-tag-alist)))
13366 (if (and files (car files))
13367 files
13368 (org-agenda-files))))))))
13370 (defun org-make-tags-matcher (match)
13371 "Create the TAGS/TODO matcher form for the selection string MATCH.
13373 The variable `todo-only' is scoped dynamically into this function.
13374 It will be set to t if the matcher restricts matching to TODO entries,
13375 otherwise will not be touched.
13377 Returns a cons of the selection string MATCH and the constructed
13378 lisp form implementing the matcher. The matcher is to be evaluated
13379 at an Org entry, with point on the headline, and returns t if the
13380 entry matches the selection string MATCH. The returned lisp form
13381 references two variables with information about the entry, which
13382 must be bound around the form's evaluation: todo, the TODO keyword
13383 at the entry (or nil of none); and tags-list, the list of all tags
13384 at the entry including inherited ones. Additionally, the category
13385 of the entry (if any) must be specified as the text property
13386 'org-category on the headline.
13388 See also `org-scan-tags'.
13390 (declare (special todo-only))
13391 (unless (boundp 'todo-only)
13392 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13393 (unless match
13394 ;; Get a new match request, with completion
13395 (let ((org-last-tags-completion-table
13396 (org-global-tags-completion-table)))
13397 (setq match (org-completing-read-no-i
13398 "Match: " 'org-tags-completion-function nil nil nil
13399 'org-tags-history))))
13401 ;; Parse the string and create a lisp form
13402 (let ((match0 match)
13403 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13404 minus tag mm
13405 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13406 orterms term orlist re-p str-p level-p level-op time-p
13407 prop-p pn pv po gv rest)
13408 (if (string-match "/+" match)
13409 ;; match contains also a todo-matching request
13410 (progn
13411 (setq tagsmatch (substring match 0 (match-beginning 0))
13412 todomatch (substring match (match-end 0)))
13413 (if (string-match "^!" todomatch)
13414 (setq todo-only t todomatch (substring todomatch 1)))
13415 (if (string-match "^\\s-*$" todomatch)
13416 (setq todomatch nil)))
13417 ;; only matching tags
13418 (setq tagsmatch match todomatch nil))
13420 ;; Make the tags matcher
13421 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13422 (setq tagsmatcher t)
13423 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13424 (while (setq term (pop orterms))
13425 (while (and (equal (substring term -1) "\\") orterms)
13426 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13427 (while (string-match re term)
13428 (setq rest (substring term (match-end 0))
13429 minus (and (match-end 1)
13430 (equal (match-string 1 term) "-"))
13431 tag (save-match-data (replace-regexp-in-string
13432 "\\\\-" "-"
13433 (match-string 2 term)))
13434 re-p (equal (string-to-char tag) ?{)
13435 level-p (match-end 4)
13436 prop-p (match-end 5)
13437 mm (cond
13438 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13439 (level-p
13440 (setq level-op (org-op-to-function (match-string 3 term)))
13441 `(,level-op level ,(string-to-number
13442 (match-string 4 term))))
13443 (prop-p
13444 (setq pn (match-string 5 term)
13445 po (match-string 6 term)
13446 pv (match-string 7 term)
13447 re-p (equal (string-to-char pv) ?{)
13448 str-p (equal (string-to-char pv) ?\")
13449 time-p (save-match-data
13450 (string-match "^\"[[<].*[]>]\"$" pv))
13451 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13452 (if time-p (setq pv (org-matcher-time pv)))
13453 (setq po (org-op-to-function po (if time-p 'time str-p)))
13454 (cond
13455 ((equal pn "CATEGORY")
13456 (setq gv '(get-text-property (point) 'org-category)))
13457 ((equal pn "TODO")
13458 (setq gv 'todo))
13460 (setq gv `(org-cached-entry-get nil ,pn))))
13461 (if re-p
13462 (if (eq po 'org<>)
13463 `(not (string-match ,pv (or ,gv "")))
13464 `(string-match ,pv (or ,gv "")))
13465 (if str-p
13466 `(,po (or ,gv "") ,pv)
13467 `(,po (string-to-number (or ,gv ""))
13468 ,(string-to-number pv) ))))
13469 (t `(member ,tag tags-list)))
13470 mm (if minus (list 'not mm) mm)
13471 term rest)
13472 (push mm tagsmatcher))
13473 (push (if (> (length tagsmatcher) 1)
13474 (cons 'and tagsmatcher)
13475 (car tagsmatcher))
13476 orlist)
13477 (setq tagsmatcher nil))
13478 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13479 (setq tagsmatcher
13480 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13481 ;; Make the todo matcher
13482 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13483 (setq todomatcher t)
13484 (setq orterms (org-split-string todomatch "|") orlist nil)
13485 (while (setq term (pop orterms))
13486 (while (string-match re term)
13487 (setq minus (and (match-end 1)
13488 (equal (match-string 1 term) "-"))
13489 kwd (match-string 2 term)
13490 re-p (equal (string-to-char kwd) ?{)
13491 term (substring term (match-end 0))
13492 mm (if re-p
13493 `(string-match ,(substring kwd 1 -1) todo)
13494 (list 'equal 'todo kwd))
13495 mm (if minus (list 'not mm) mm))
13496 (push mm todomatcher))
13497 (push (if (> (length todomatcher) 1)
13498 (cons 'and todomatcher)
13499 (car todomatcher))
13500 orlist)
13501 (setq todomatcher nil))
13502 (setq todomatcher (if (> (length orlist) 1)
13503 (cons 'or orlist) (car orlist))))
13505 ;; Return the string and lisp forms of the matcher
13506 (setq matcher (if todomatcher
13507 (list 'and tagsmatcher todomatcher)
13508 tagsmatcher))
13509 (when todo-only
13510 (setq matcher (list 'and '(member todo org-not-done-keywords)
13511 matcher)))
13512 (cons match0 matcher)))
13514 (defun org-op-to-function (op &optional stringp)
13515 "Turn an operator into the appropriate function."
13516 (setq op
13517 (cond
13518 ((equal op "<" ) '(< string< org-time<))
13519 ((equal op ">" ) '(> org-string> org-time>))
13520 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13521 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13522 ((member op '("=" "==")) '(= string= org-time=))
13523 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13524 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13526 (defun org<> (a b) (not (= a b)))
13527 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13528 (defun org-string>= (a b) (not (string< a b)))
13529 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13530 (defun org-string<> (a b) (not (string= a b)))
13531 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13532 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
13537 (defun org-2ft (s)
13538 "Convert S to a floating point time.
13539 If S is already a number, just return it. If it is a string, parse
13540 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13541 (cond
13542 ((numberp s) s)
13543 ((stringp s)
13544 (condition-case nil
13545 (float-time (apply 'encode-time (org-parse-time-string s)))
13546 (error 0.)))
13547 (t 0.)))
13549 (defun org-time-today ()
13550 "Time in seconds today at 0:00.
13551 Returns the float number of seconds since the beginning of the
13552 epoch to the beginning of today (00:00)."
13553 (float-time (apply 'encode-time
13554 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13556 (defun org-matcher-time (s)
13557 "Interpret a time comparison value."
13558 (save-match-data
13559 (cond
13560 ((string= s "<now>") (float-time))
13561 ((string= s "<today>") (org-time-today))
13562 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13563 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13564 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13565 (+ (org-time-today)
13566 (* (string-to-number (match-string 1 s))
13567 (cdr (assoc (match-string 2 s)
13568 '(("d" . 86400.0) ("w" . 604800.0)
13569 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13570 (t (org-2ft s)))))
13572 (defun org-match-any-p (re list)
13573 "Does re match any element of list?"
13574 (setq list (mapcar (lambda (x) (string-match re x)) list))
13575 (delq nil list))
13577 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13578 (defvar org-tags-overlay (make-overlay 1 1))
13579 (org-detach-overlay org-tags-overlay)
13581 (defun org-get-local-tags-at (&optional pos)
13582 "Get a list of tags defined in the current headline."
13583 (org-get-tags-at pos 'local))
13585 (defun org-get-local-tags ()
13586 "Get a list of tags defined in the current headline."
13587 (org-get-tags-at nil 'local))
13589 (defun org-get-tags-at (&optional pos local)
13590 "Get a list of all headline tags applicable at POS.
13591 POS defaults to point. If tags are inherited, the list contains
13592 the targets in the same sequence as the headlines appear, i.e.
13593 the tags of the current headline come last.
13594 When LOCAL is non-nil, only return tags from the current headline,
13595 ignore inherited ones."
13596 (interactive)
13597 (if (and org-trust-scanner-tags
13598 (or (not pos) (equal pos (point)))
13599 (not local))
13600 org-scanner-tags
13601 (let (tags ltags lastpos parent)
13602 (save-excursion
13603 (save-restriction
13604 (widen)
13605 (goto-char (or pos (point)))
13606 (save-match-data
13607 (catch 'done
13608 (condition-case nil
13609 (progn
13610 (org-back-to-heading t)
13611 (while (not (equal lastpos (point)))
13612 (setq lastpos (point))
13613 (when (looking-at
13614 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13615 (setq ltags (org-split-string
13616 (org-match-string-no-properties 1) ":"))
13617 (when parent
13618 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13619 (setq tags (append
13620 (if parent
13621 (org-remove-uninherited-tags ltags)
13622 ltags)
13623 tags)))
13624 (or org-use-tag-inheritance (throw 'done t))
13625 (if local (throw 'done t))
13626 (or (org-up-heading-safe) (error nil))
13627 (setq parent t)))
13628 (error nil)))))
13629 (if local
13630 tags
13631 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13633 (defun org-add-prop-inherited (s)
13634 (add-text-properties 0 (length s) '(inherited t) s)
13637 (defun org-toggle-tag (tag &optional onoff)
13638 "Toggle the tag TAG for the current line.
13639 If ONOFF is `on' or `off', don't toggle but set to this state."
13640 (let (res current)
13641 (save-excursion
13642 (org-back-to-heading t)
13643 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13644 (point-at-eol) t)
13645 (progn
13646 (setq current (match-string 1))
13647 (replace-match ""))
13648 (setq current ""))
13649 (setq current (nreverse (org-split-string current ":")))
13650 (cond
13651 ((eq onoff 'on)
13652 (setq res t)
13653 (or (member tag current) (push tag current)))
13654 ((eq onoff 'off)
13655 (or (not (member tag current)) (setq current (delete tag current))))
13656 (t (if (member tag current)
13657 (setq current (delete tag current))
13658 (setq res t)
13659 (push tag current))))
13660 (end-of-line 1)
13661 (if current
13662 (progn
13663 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13664 (org-set-tags nil t))
13665 (delete-horizontal-space))
13666 (run-hooks 'org-after-tags-change-hook))
13667 res))
13669 (defun org-align-tags-here (to-col)
13670 ;; Assumes that this is a headline
13671 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13672 (beginning-of-line 1)
13673 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13674 (< pos (match-beginning 2)))
13675 (progn
13676 (setq tags-l (- (match-end 2) (match-beginning 2)))
13677 (goto-char (match-beginning 1))
13678 (insert " ")
13679 (delete-region (point) (1+ (match-beginning 2)))
13680 (setq ncol (max (current-column)
13681 (1+ col)
13682 (if (> to-col 0)
13683 to-col
13684 (- (abs to-col) tags-l))))
13685 (setq p (point))
13686 (insert (make-string (- ncol (current-column)) ?\ ))
13687 (setq ncol (current-column))
13688 (when indent-tabs-mode (tabify p (point-at-eol)))
13689 (org-move-to-column (min ncol col) t))
13690 (goto-char pos))))
13692 (defun org-set-tags-command (&optional arg just-align)
13693 "Call the set-tags command for the current entry."
13694 (interactive "P")
13695 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13696 (org-set-tags arg just-align)
13697 (save-excursion
13698 (org-back-to-heading t)
13699 (org-set-tags arg just-align))))
13701 (defun org-set-tags-to (data)
13702 "Set the tags of the current entry to DATA, replacing the current tags.
13703 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13704 If DATA is nil or the empty string, any tags will be removed."
13705 (interactive "sTags: ")
13706 (setq data
13707 (cond
13708 ((eq data nil) "")
13709 ((equal data "") "")
13710 ((stringp data)
13711 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13712 ":"))
13713 ((listp data)
13714 (concat ":" (mapconcat 'identity data ":") ":"))))
13715 (when data
13716 (save-excursion
13717 (org-back-to-heading t)
13718 (when (looking-at org-complex-heading-regexp)
13719 (if (match-end 5)
13720 (progn
13721 (goto-char (match-beginning 5))
13722 (insert data)
13723 (delete-region (point) (point-at-eol))
13724 (org-set-tags nil 'align))
13725 (goto-char (point-at-eol))
13726 (insert " " data)
13727 (org-set-tags nil 'align)))
13728 (beginning-of-line 1)
13729 (if (looking-at ".*?\\([ \t]+\\)$")
13730 (delete-region (match-beginning 1) (match-end 1))))))
13732 (defun org-align-all-tags ()
13733 "Align the tags i all headings."
13734 (interactive)
13735 (save-excursion
13736 (or (ignore-errors (org-back-to-heading t))
13737 (outline-next-heading))
13738 (if (org-at-heading-p)
13739 (org-set-tags t)
13740 (message "No headings"))))
13742 (defvar org-indent-indentation-per-level)
13743 (defun org-set-tags (&optional arg just-align)
13744 "Set the tags for the current headline.
13745 With prefix ARG, realign all tags in headings in the current buffer."
13746 (interactive "P")
13747 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13748 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13749 'region-start-level 'region))
13750 org-loop-over-headlines-in-active-region)
13751 (org-map-entries
13752 ;; We don't use ARG and JUST-ALIGN here these args are not
13753 ;; useful when looping over headlines
13754 `(org-set-tags)
13755 org-loop-over-headlines-in-active-region
13756 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13757 (let* ((re org-outline-regexp-bol)
13758 (current (unless arg (org-get-tags-string)))
13759 (col (current-column))
13760 (org-setting-tags t)
13761 table current-tags inherited-tags ; computed below when needed
13762 tags p0 c0 c1 rpl di tc level)
13763 (if arg
13764 (save-excursion
13765 (goto-char (point-min))
13766 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13767 (while (re-search-forward re nil t)
13768 (org-set-tags nil t)
13769 (end-of-line 1)))
13770 (message "All tags realigned to column %d" org-tags-column))
13771 (if just-align
13772 (setq tags current)
13773 ;; Get a new set of tags from the user
13774 (save-excursion
13775 (setq table (append org-tag-persistent-alist
13776 (or org-tag-alist (org-get-buffer-tags))
13777 (and
13778 org-complete-tags-always-offer-all-agenda-tags
13779 (org-global-tags-completion-table
13780 (org-agenda-files))))
13781 org-last-tags-completion-table table
13782 current-tags (org-split-string current ":")
13783 inherited-tags (nreverse
13784 (nthcdr (length current-tags)
13785 (nreverse (org-get-tags-at))))
13786 tags
13787 (if (or (eq t org-use-fast-tag-selection)
13788 (and org-use-fast-tag-selection
13789 (delq nil (mapcar 'cdr table))))
13790 (org-fast-tag-selection
13791 current-tags inherited-tags table
13792 (if org-fast-tag-selection-include-todo
13793 org-todo-key-alist))
13794 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13795 (org-trim
13796 (org-icompleting-read "Tags: "
13797 'org-tags-completion-function
13798 nil nil current 'org-tags-history))))))
13799 (while (string-match "[-+&]+" tags)
13800 ;; No boolean logic, just a list
13801 (setq tags (replace-match ":" t t tags))))
13803 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13805 (if org-tags-sort-function
13806 (setq tags (mapconcat 'identity
13807 (sort (org-split-string
13808 tags (org-re "[^[:alnum:]_@#%]+"))
13809 org-tags-sort-function) ":")))
13811 (if (string-match "\\`[\t ]*\\'" tags)
13812 (setq tags "")
13813 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13814 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13816 ;; Insert new tags at the correct column
13817 (beginning-of-line 1)
13818 (setq level (or (and (looking-at org-outline-regexp)
13819 (- (match-end 0) (point) 1))
13821 (cond
13822 ((and (equal current "") (equal tags "")))
13823 ((re-search-forward
13824 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13825 (point-at-eol) t)
13826 (if (equal tags "")
13827 (setq rpl "")
13828 (goto-char (match-beginning 0))
13829 (setq c0 (current-column)
13830 ;; compute offset for the case of org-indent-mode active
13831 di (if org-indent-mode
13832 (* (1- org-indent-indentation-per-level) (1- level))
13834 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13835 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13836 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13837 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13838 (replace-match rpl t t)
13839 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13840 tags)
13841 (t (error "Tags alignment failed")))
13842 (org-move-to-column col)
13843 (unless just-align
13844 (run-hooks 'org-after-tags-change-hook))))))
13846 (defun org-change-tag-in-region (beg end tag off)
13847 "Add or remove TAG for each entry in the region.
13848 This works in the agenda, and also in an org-mode buffer."
13849 (interactive
13850 (list (region-beginning) (region-end)
13851 (let ((org-last-tags-completion-table
13852 (if (derived-mode-p 'org-mode)
13853 (org-get-buffer-tags)
13854 (org-global-tags-completion-table))))
13855 (org-icompleting-read
13856 "Tag: " 'org-tags-completion-function nil nil nil
13857 'org-tags-history))
13858 (progn
13859 (message "[s]et or [r]emove? ")
13860 (equal (read-char-exclusive) ?r))))
13861 (if (fboundp 'deactivate-mark) (deactivate-mark))
13862 (let ((agendap (equal major-mode 'org-agenda-mode))
13863 l1 l2 m buf pos newhead (cnt 0))
13864 (goto-char end)
13865 (setq l2 (1- (org-current-line)))
13866 (goto-char beg)
13867 (setq l1 (org-current-line))
13868 (loop for l from l1 to l2 do
13869 (org-goto-line l)
13870 (setq m (get-text-property (point) 'org-hd-marker))
13871 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13872 (and agendap m))
13873 (setq buf (if agendap (marker-buffer m) (current-buffer))
13874 pos (if agendap m (point)))
13875 (with-current-buffer buf
13876 (save-excursion
13877 (save-restriction
13878 (goto-char pos)
13879 (setq cnt (1+ cnt))
13880 (org-toggle-tag tag (if off 'off 'on))
13881 (setq newhead (org-get-heading)))))
13882 (and agendap (org-agenda-change-all-lines newhead m))))
13883 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13885 (defun org-tags-completion-function (string predicate &optional flag)
13886 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13887 (confirm (lambda (x) (stringp (car x)))))
13888 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13889 (setq s1 (match-string 1 string)
13890 s2 (match-string 2 string))
13891 (setq s1 "" s2 string))
13892 (cond
13893 ((eq flag nil)
13894 ;; try completion
13895 (setq rtn (try-completion s2 ctable confirm))
13896 (if (stringp rtn)
13897 (setq rtn
13898 (concat s1 s2 (substring rtn (length s2))
13899 (if (and org-add-colon-after-tag-completion
13900 (assoc rtn ctable))
13901 ":" ""))))
13902 rtn)
13903 ((eq flag t)
13904 ;; all-completions
13905 (all-completions s2 ctable confirm)
13907 ((eq flag 'lambda)
13908 ;; exact match?
13909 (assoc s2 ctable)))
13912 (defun org-fast-tag-insert (kwd tags face &optional end)
13913 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13914 (insert (format "%-12s" (concat kwd ":"))
13915 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13916 (or end "")))
13918 (defun org-fast-tag-show-exit (flag)
13919 (save-excursion
13920 (org-goto-line 3)
13921 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13922 (replace-match ""))
13923 (when flag
13924 (end-of-line 1)
13925 (org-move-to-column (- (window-width) 19) t)
13926 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13928 (defun org-set-current-tags-overlay (current prefix)
13929 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13930 (if (featurep 'xemacs)
13931 (org-overlay-display org-tags-overlay (concat prefix s)
13932 'secondary-selection)
13933 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13934 (org-overlay-display org-tags-overlay (concat prefix s)))))
13936 (defvar org-last-tag-selection-key nil)
13937 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13938 "Fast tag selection with single keys.
13939 CURRENT is the current list of tags in the headline, INHERITED is the
13940 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13941 possibly with grouping information. TODO-TABLE is a similar table with
13942 TODO keywords, should these have keys assigned to them.
13943 If the keys are nil, a-z are automatically assigned.
13944 Returns the new tags string, or nil to not change the current settings."
13945 (let* ((fulltable (append table todo-table))
13946 (maxlen (apply 'max (mapcar
13947 (lambda (x)
13948 (if (stringp (car x)) (string-width (car x)) 0))
13949 fulltable)))
13950 (buf (current-buffer))
13951 (expert (eq org-fast-tag-selection-single-key 'expert))
13952 (buffer-tags nil)
13953 (fwidth (+ maxlen 3 1 3))
13954 (ncol (/ (- (window-width) 4) fwidth))
13955 (i-face 'org-done)
13956 (c-face 'org-todo)
13957 tg cnt e c char c1 c2 ntable tbl rtn
13958 ov-start ov-end ov-prefix
13959 (exit-after-next org-fast-tag-selection-single-key)
13960 (done-keywords org-done-keywords)
13961 groups ingroup)
13962 (save-excursion
13963 (beginning-of-line 1)
13964 (if (looking-at
13965 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13966 (setq ov-start (match-beginning 1)
13967 ov-end (match-end 1)
13968 ov-prefix "")
13969 (setq ov-start (1- (point-at-eol))
13970 ov-end (1+ ov-start))
13971 (skip-chars-forward "^\n\r")
13972 (setq ov-prefix
13973 (concat
13974 (buffer-substring (1- (point)) (point))
13975 (if (> (current-column) org-tags-column)
13977 (make-string (- org-tags-column (current-column)) ?\ ))))))
13978 (move-overlay org-tags-overlay ov-start ov-end)
13979 (save-window-excursion
13980 (if expert
13981 (set-buffer (get-buffer-create " *Org tags*"))
13982 (delete-other-windows)
13983 (split-window-vertically)
13984 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13985 (erase-buffer)
13986 (org-set-local 'org-done-keywords done-keywords)
13987 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13988 (org-fast-tag-insert "Current" current c-face "\n\n")
13989 (org-fast-tag-show-exit exit-after-next)
13990 (org-set-current-tags-overlay current ov-prefix)
13991 (setq tbl fulltable char ?a cnt 0)
13992 (while (setq e (pop tbl))
13993 (cond
13994 ((equal (car e) :startgroup)
13995 (push '() groups) (setq ingroup t)
13996 (when (not (= cnt 0))
13997 (setq cnt 0)
13998 (insert "\n"))
13999 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14000 ((equal (car e) :endgroup)
14001 (setq ingroup nil cnt 0)
14002 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14003 ((equal e '(:newline))
14004 (when (not (= cnt 0))
14005 (setq cnt 0)
14006 (insert "\n")
14007 (setq e (car tbl))
14008 (while (equal (car tbl) '(:newline))
14009 (insert "\n")
14010 (setq tbl (cdr tbl)))))
14012 (setq tg (copy-sequence (car e)) c2 nil)
14013 (if (cdr e)
14014 (setq c (cdr e))
14015 ;; automatically assign a character.
14016 (setq c1 (string-to-char
14017 (downcase (substring
14018 tg (if (= (string-to-char tg) ?@) 1 0)))))
14019 (if (or (rassoc c1 ntable) (rassoc c1 table))
14020 (while (or (rassoc char ntable) (rassoc char table))
14021 (setq char (1+ char)))
14022 (setq c2 c1))
14023 (setq c (or c2 char)))
14024 (if ingroup (push tg (car groups)))
14025 (setq tg (org-add-props tg nil 'face
14026 (cond
14027 ((not (assoc tg table))
14028 (org-get-todo-face tg))
14029 ((member tg current) c-face)
14030 ((member tg inherited) i-face))))
14031 (if (and (= cnt 0) (not ingroup)) (insert " "))
14032 (insert "[" c "] " tg (make-string
14033 (- fwidth 4 (length tg)) ?\ ))
14034 (push (cons tg c) ntable)
14035 (when (= (setq cnt (1+ cnt)) ncol)
14036 (insert "\n")
14037 (if ingroup (insert " "))
14038 (setq cnt 0)))))
14039 (setq ntable (nreverse ntable))
14040 (insert "\n")
14041 (goto-char (point-min))
14042 (if (not expert) (org-fit-window-to-buffer))
14043 (setq rtn
14044 (catch 'exit
14045 (while t
14046 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14047 (if (not groups) "no " "")
14048 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14049 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14050 (setq org-last-tag-selection-key c)
14051 (cond
14052 ((= c ?\r) (throw 'exit t))
14053 ((= c ?!)
14054 (setq groups (not groups))
14055 (goto-char (point-min))
14056 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14057 ((= c ?\C-c)
14058 (if (not expert)
14059 (org-fast-tag-show-exit
14060 (setq exit-after-next (not exit-after-next)))
14061 (setq expert nil)
14062 (delete-other-windows)
14063 (set-window-buffer (split-window-vertically) " *Org tags*")
14064 (org-switch-to-buffer-other-window " *Org tags*")
14065 (org-fit-window-to-buffer)))
14066 ((or (= c ?\C-g)
14067 (and (= c ?q) (not (rassoc c ntable))))
14068 (org-detach-overlay org-tags-overlay)
14069 (setq quit-flag t))
14070 ((= c ?\ )
14071 (setq current nil)
14072 (if exit-after-next (setq exit-after-next 'now)))
14073 ((= c ?\t)
14074 (condition-case nil
14075 (setq tg (org-icompleting-read
14076 "Tag: "
14077 (or buffer-tags
14078 (with-current-buffer buf
14079 (org-get-buffer-tags)))))
14080 (quit (setq tg "")))
14081 (when (string-match "\\S-" tg)
14082 (add-to-list 'buffer-tags (list tg))
14083 (if (member tg current)
14084 (setq current (delete tg current))
14085 (push tg current)))
14086 (if exit-after-next (setq exit-after-next 'now)))
14087 ((setq e (rassoc c todo-table) tg (car e))
14088 (with-current-buffer buf
14089 (save-excursion (org-todo tg)))
14090 (if exit-after-next (setq exit-after-next 'now)))
14091 ((setq e (rassoc c ntable) tg (car e))
14092 (if (member tg current)
14093 (setq current (delete tg current))
14094 (loop for g in groups do
14095 (if (member tg g)
14096 (mapc (lambda (x)
14097 (setq current (delete x current)))
14098 g)))
14099 (push tg current))
14100 (if exit-after-next (setq exit-after-next 'now))))
14102 ;; Create a sorted list
14103 (setq current
14104 (sort current
14105 (lambda (a b)
14106 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14107 (if (eq exit-after-next 'now) (throw 'exit t))
14108 (goto-char (point-min))
14109 (beginning-of-line 2)
14110 (delete-region (point) (point-at-eol))
14111 (org-fast-tag-insert "Current" current c-face)
14112 (org-set-current-tags-overlay current ov-prefix)
14113 (while (re-search-forward
14114 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14115 (setq tg (match-string 1))
14116 (add-text-properties
14117 (match-beginning 1) (match-end 1)
14118 (list 'face
14119 (cond
14120 ((member tg current) c-face)
14121 ((member tg inherited) i-face)
14122 (t (get-text-property (match-beginning 1) 'face))))))
14123 (goto-char (point-min)))))
14124 (org-detach-overlay org-tags-overlay)
14125 (if rtn
14126 (mapconcat 'identity current ":")
14127 nil))))
14129 (defun org-get-tags-string ()
14130 "Get the TAGS string in the current headline."
14131 (unless (org-at-heading-p t)
14132 (error "Not on a heading"))
14133 (save-excursion
14134 (beginning-of-line 1)
14135 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14136 (org-match-string-no-properties 1)
14137 "")))
14139 (defun org-get-tags ()
14140 "Get the list of tags specified in the current headline."
14141 (org-split-string (org-get-tags-string) ":"))
14143 (defun org-get-buffer-tags ()
14144 "Get a table of all tags used in the buffer, for completion."
14145 (let (tags)
14146 (save-excursion
14147 (goto-char (point-min))
14148 (while (re-search-forward
14149 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14150 (when (equal (char-after (point-at-bol 0)) ?*)
14151 (mapc (lambda (x) (add-to-list 'tags x))
14152 (org-split-string (org-match-string-no-properties 1) ":")))))
14153 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14154 (mapcar 'list tags)))
14156 ;;;; The mapping API
14158 ;;;###autoload
14159 (defun org-map-entries (func &optional match scope &rest skip)
14160 "Call FUNC at each headline selected by MATCH in SCOPE.
14162 FUNC is a function or a lisp form. The function will be called without
14163 arguments, with the cursor positioned at the beginning of the headline.
14164 The return values of all calls to the function will be collected and
14165 returned as a list.
14167 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14168 does not need to preserve point. After evaluation, the cursor will be
14169 moved to the end of the line (presumably of the headline of the
14170 processed entry) and search continues from there. Under some
14171 circumstances, this may not produce the wanted results. For example,
14172 if you have removed (e.g. archived) the current (sub)tree it could
14173 mean that the next entry will be skipped entirely. In such cases, you
14174 can specify the position from where search should continue by making
14175 FUNC set the variable `org-map-continue-from' to the desired buffer
14176 position.
14178 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14179 Only headlines that are matched by this query will be considered during
14180 the iteration. When MATCH is nil or t, all headlines will be
14181 visited by the iteration.
14183 SCOPE determines the scope of this command. It can be any of:
14185 nil The current buffer, respecting the restriction if any
14186 tree The subtree started with the entry at point
14187 region The entries within the active region, if any
14188 region-start-level
14189 The entries within the active region, but only those at
14190 the same level than the first one.
14191 file The current buffer, without restriction
14192 file-with-archives
14193 The current buffer, and any archives associated with it
14194 agenda All agenda files
14195 agenda-with-archives
14196 All agenda files with any archive files associated with them
14197 \(file1 file2 ...)
14198 If this is a list, all files in the list will be scanned
14200 The remaining args are treated as settings for the skipping facilities of
14201 the scanner. The following items can be given here:
14203 archive skip trees with the archive tag.
14204 comment skip trees with the COMMENT keyword
14205 function or Emacs Lisp form:
14206 will be used as value for `org-agenda-skip-function', so whenever
14207 the function returns t, FUNC will not be called for that
14208 entry and search will continue from the point where the
14209 function leaves it.
14211 If your function needs to retrieve the tags including inherited tags
14212 at the *current* entry, you can use the value of the variable
14213 `org-scanner-tags' which will be much faster than getting the value
14214 with `org-get-tags-at'. If your function gets properties with
14215 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14216 to t around the call to `org-entry-properties' to get the same speedup.
14217 Note that if your function moves around to retrieve tags and properties at
14218 a *different* entry, you cannot use these techniques."
14219 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14220 (not (org-region-active-p)))
14221 (let* ((org-agenda-archives-mode nil) ; just to make sure
14222 (org-agenda-skip-archived-trees (memq 'archive skip))
14223 (org-agenda-skip-comment-trees (memq 'comment skip))
14224 (org-agenda-skip-function
14225 (car (org-delete-all '(comment archive) skip)))
14226 (org-tags-match-list-sublevels t)
14227 (start-level (eq scope 'region-start-level))
14228 matcher file res
14229 org-todo-keywords-for-agenda
14230 org-done-keywords-for-agenda
14231 org-todo-keyword-alist-for-agenda
14232 org-drawers-for-agenda
14233 org-tag-alist-for-agenda
14234 todo-only)
14236 (cond
14237 ((eq match t) (setq matcher t))
14238 ((eq match nil) (setq matcher t))
14239 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14241 (save-excursion
14242 (save-restriction
14243 (cond ((eq scope 'tree)
14244 (org-back-to-heading t)
14245 (org-narrow-to-subtree)
14246 (setq scope nil))
14247 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14248 (org-region-active-p))
14249 ;; If needed, set start-level to a string like "2"
14250 (when start-level
14251 (save-excursion
14252 (goto-char (region-beginning))
14253 (unless (org-at-heading-p) (outline-next-heading))
14254 (setq start-level (org-current-level))))
14255 (narrow-to-region (region-beginning)
14256 (save-excursion
14257 (goto-char (region-end))
14258 (unless (and (bolp) (org-at-heading-p))
14259 (outline-next-heading))
14260 (point)))
14261 (setq scope nil)))
14263 (if (not scope)
14264 (progn
14265 (org-agenda-prepare-buffers
14266 (list (buffer-file-name (current-buffer))))
14267 (setq res (org-scan-tags func matcher todo-only start-level)))
14268 ;; Get the right scope
14269 (cond
14270 ((and scope (listp scope) (symbolp (car scope)))
14271 (setq scope (eval scope)))
14272 ((eq scope 'agenda)
14273 (setq scope (org-agenda-files t)))
14274 ((eq scope 'agenda-with-archives)
14275 (setq scope (org-agenda-files t))
14276 (setq scope (org-add-archive-files scope)))
14277 ((eq scope 'file)
14278 (setq scope (list (buffer-file-name))))
14279 ((eq scope 'file-with-archives)
14280 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14281 (org-agenda-prepare-buffers scope)
14282 (while (setq file (pop scope))
14283 (with-current-buffer (org-find-base-buffer-visiting file)
14284 (save-excursion
14285 (save-restriction
14286 (widen)
14287 (goto-char (point-min))
14288 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14289 res)))
14291 ;;;; Properties
14293 ;;; Setting and retrieving properties
14295 (defconst org-special-properties
14296 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14297 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14298 "The special properties valid in Org-mode.
14300 These are properties that are not defined in the property drawer,
14301 but in some other way.")
14303 (defconst org-default-properties
14304 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14305 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14306 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14307 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14308 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14309 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14310 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14311 "Some properties that are used by Org-mode for various purposes.
14312 Being in this list makes sure that they are offered for completion.")
14314 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14315 "Regular expression matching the first line of a property drawer.")
14317 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14318 "Regular expression matching the last line of a property drawer.")
14320 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14321 "Regular expression matching the first line of a property drawer.")
14323 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14324 "Regular expression matching the first line of a property drawer.")
14326 (defconst org-property-drawer-re
14327 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14328 org-property-end-re "\\)\n?")
14329 "Matches an entire property drawer.")
14331 (defconst org-clock-drawer-re
14332 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14333 org-property-end-re "\\)\n?")
14334 "Matches an entire clock drawer.")
14336 (defsubst org-re-property (property)
14337 "Return a regexp matching a PROPERTY line.
14338 Match group 1 will be set to the value."
14339 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14341 (defsubst org-re-property-keyword (property)
14342 "Return a regexp matching a PROPERTY line, possibly with no
14343 value for the property."
14344 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14346 (defun org-property-action ()
14347 "Do an action on properties."
14348 (interactive)
14349 (let (c)
14350 (org-at-property-p)
14351 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14352 (setq c (read-char-exclusive))
14353 (cond
14354 ((equal c ?s)
14355 (call-interactively 'org-set-property))
14356 ((equal c ?d)
14357 (call-interactively 'org-delete-property))
14358 ((equal c ?D)
14359 (call-interactively 'org-delete-property-globally))
14360 ((equal c ?c)
14361 (call-interactively 'org-compute-property-at-point))
14362 (t (error "No such property action %c" c)))))
14364 (defun org-inc-effort ()
14365 "Increment the value of the effort property in the current entry."
14366 (interactive)
14367 (org-set-effort nil t))
14369 (defun org-set-effort (&optional value increment)
14370 "Set the effort property of the current entry.
14371 With numerical prefix arg, use the nth allowed value, 0 stands for the
14372 10th allowed value.
14374 When INCREMENT is non-nil, set the property to the next allowed value."
14375 (interactive "P")
14376 (if (equal value 0) (setq value 10))
14377 (let* ((completion-ignore-case t)
14378 (prop org-effort-property)
14379 (cur (org-entry-get nil prop))
14380 (allowed (org-property-get-allowed-values nil prop 'table))
14381 (existing (mapcar 'list (org-property-values prop)))
14383 (val (cond
14384 ((stringp value) value)
14385 ((and allowed (integerp value))
14386 (or (car (nth (1- value) allowed))
14387 (car (org-last allowed))))
14388 ((and allowed increment)
14389 (or (caadr (member (list cur) allowed))
14390 (error "Allowed effort values are not set")))
14391 (allowed
14392 (message "Select 1-9,0, [RET%s]: %s"
14393 (if cur (concat "=" cur) "")
14394 (mapconcat 'car allowed " "))
14395 (setq rpl (read-char-exclusive))
14396 (if (equal rpl ?\r)
14398 (setq rpl (- rpl ?0))
14399 (if (equal rpl 0) (setq rpl 10))
14400 (if (and (> rpl 0) (<= rpl (length allowed)))
14401 (car (nth (1- rpl) allowed))
14402 (org-completing-read "Effort: " allowed nil))))
14404 (let (org-completion-use-ido org-completion-use-iswitchb)
14405 (org-completing-read
14406 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14407 (concat "[" cur "]") "")
14408 ": ")
14409 existing nil nil "" nil cur))))))
14410 (unless (equal (org-entry-get nil prop) val)
14411 (org-entry-put nil prop val))
14412 (message "%s is now %s" prop val)))
14414 (defun org-at-property-p ()
14415 "Is cursor inside a property drawer?"
14416 (save-excursion
14417 (beginning-of-line 1)
14418 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14419 (save-match-data ;; Used by calling procedures
14420 (let ((p (point))
14421 (range (unless (org-before-first-heading-p)
14422 (org-get-property-block))))
14423 (and range (<= (car range) p) (< p (cdr range))))))))
14425 (defun org-get-property-block (&optional beg end force)
14426 "Return the (beg . end) range of the body of the property drawer.
14427 BEG and END are the beginning and end of the current subtree, or of
14428 the part before the first headline. If they are not given, they will
14429 be found. If the drawer does not exist and FORCE is non-nil, create
14430 the drawer."
14431 (catch 'exit
14432 (save-excursion
14433 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14434 (progn (org-back-to-heading t) (point))))
14435 (end (or end (and (not (outline-next-heading)) (point-max))
14436 (point))))
14437 (goto-char beg)
14438 (if (re-search-forward org-property-start-re end t)
14439 (setq beg (1+ (match-end 0)))
14440 (if force
14441 (save-excursion
14442 (org-insert-property-drawer)
14443 (setq end (progn (outline-next-heading) (point))))
14444 (throw 'exit nil))
14445 (goto-char beg)
14446 (if (re-search-forward org-property-start-re end t)
14447 (setq beg (1+ (match-end 0)))))
14448 (if (re-search-forward org-property-end-re end t)
14449 (setq end (match-beginning 0))
14450 (or force (throw 'exit nil))
14451 (goto-char beg)
14452 (setq end beg)
14453 (org-indent-line)
14454 (insert ":END:\n"))
14455 (cons beg end)))))
14457 (defun org-entry-properties (&optional pom which specific)
14458 "Get all properties of the entry at point-or-marker POM.
14459 This includes the TODO keyword, the tags, time strings for deadline,
14460 scheduled, and clocking, and any additional properties defined in the
14461 entry. The return value is an alist, keys may occur multiple times
14462 if the property key was used several times.
14463 POM may also be nil, in which case the current entry is used.
14464 If WHICH is nil or `all', get all properties. If WHICH is
14465 `special' or `standard', only get that subclass. If WHICH
14466 is a string only get exactly this property. SPECIFIC can be a string, the
14467 specific property we are interested in. Specifying it can speed
14468 things up because then unnecessary parsing is avoided."
14469 (setq which (or which 'all))
14470 (org-with-point-at pom
14471 (let ((clockstr (substring org-clock-string 0 -1))
14472 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14473 (case-fold-search nil)
14474 beg end range props sum-props key key1 value string clocksum clocksumt)
14475 (save-excursion
14476 (when (condition-case nil
14477 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14478 (error nil))
14479 (setq beg (point))
14480 (setq sum-props (get-text-property (point) 'org-summaries))
14481 (setq clocksum (get-text-property (point) :org-clock-minutes)
14482 clocksumt (get-text-property (point) :org-clock-minutes-today))
14483 (outline-next-heading)
14484 (setq end (point))
14485 (when (memq which '(all special))
14486 ;; Get the special properties, like TODO and tags
14487 (goto-char beg)
14488 (when (and (or (not specific) (string= specific "TODO"))
14489 (looking-at org-todo-line-regexp) (match-end 2))
14490 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14491 (when (and (or (not specific) (string= specific "PRIORITY"))
14492 (looking-at org-priority-regexp))
14493 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14494 (when (or (not specific) (string= specific "FILE"))
14495 (push (cons "FILE" buffer-file-name) props))
14496 (when (and (or (not specific) (string= specific "TAGS"))
14497 (setq value (org-get-tags-string))
14498 (string-match "\\S-" value))
14499 (push (cons "TAGS" value) props))
14500 (when (and (or (not specific) (string= specific "ALLTAGS"))
14501 (setq value (org-get-tags-at)))
14502 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14503 ":"))
14504 props))
14505 (when (or (not specific) (string= specific "BLOCKED"))
14506 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14507 (when (or (not specific)
14508 (member specific
14509 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14510 "TIMESTAMP" "TIMESTAMP_IA")))
14511 (catch 'match
14512 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14513 (setq key (if (match-end 1)
14514 (substring (org-match-string-no-properties 1)
14515 0 -1))
14516 string (if (equal key clockstr)
14517 (org-trim
14518 (buffer-substring-no-properties
14519 (match-beginning 3) (goto-char
14520 (point-at-eol))))
14521 (substring (org-match-string-no-properties 3)
14522 1 -1)))
14523 ;; Get the correct property name from the key. This is
14524 ;; necessary if the user has configured time keywords.
14525 (setq key1 (concat key ":"))
14526 (cond
14527 ((not key)
14528 (setq key
14529 (if (= (char-after (match-beginning 3)) ?\[)
14530 "TIMESTAMP_IA" "TIMESTAMP")))
14531 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14532 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14533 ((equal key1 org-closed-string) (setq key "CLOSED"))
14534 ((equal key1 org-clock-string) (setq key "CLOCK")))
14535 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14536 (progn
14537 (push (cons key string) props)
14538 ;; no need to search further if match is found
14539 (throw 'match t))
14540 (when (or (equal key "CLOCK") (not (assoc key props)))
14541 (push (cons key string) props)))))))
14543 (when (memq which '(all standard))
14544 ;; Get the standard properties, like :PROP: ...
14545 (setq range (org-get-property-block beg end))
14546 (when range
14547 (goto-char (car range))
14548 (while (re-search-forward
14549 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14550 (cdr range) t)
14551 (setq key (org-match-string-no-properties 1)
14552 value (org-trim (or (org-match-string-no-properties 2) "")))
14553 (unless (member key excluded)
14554 (push (cons key (or value "")) props)))))
14555 (if clocksum
14556 (push (cons "CLOCKSUM"
14557 (org-columns-number-to-string (/ (float clocksum) 60.)
14558 'add_times))
14559 props))
14560 (if clocksumt
14561 (push (cons "CLOCKSUM_T"
14562 (org-columns-number-to-string (/ (float clocksumt) 60.)
14563 'add_times))
14564 props))
14565 (unless (assoc "CATEGORY" props)
14566 (push (cons "CATEGORY" (org-get-category)) props))
14567 (append sum-props (nreverse props)))))))
14569 (defun org-entry-get (pom property &optional inherit literal-nil)
14570 "Get value of PROPERTY for entry or content at point-or-marker POM.
14571 If INHERIT is non-nil and the entry does not have the property,
14572 then also check higher levels of the hierarchy.
14573 If INHERIT is the symbol `selective', use inheritance only if the setting
14574 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14575 If the property is present but empty, the return value is the empty string.
14576 If the property is not present at all, nil is returned.
14578 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14579 do not interpret it as the list atom nil. This is used for inheritance
14580 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14581 (org-with-point-at pom
14582 (if (and inherit (if (eq inherit 'selective)
14583 (org-property-inherit-p property)
14585 (org-entry-get-with-inheritance property literal-nil)
14586 (if (member property org-special-properties)
14587 ;; We need a special property. Use `org-entry-properties' to
14588 ;; retrieve it, but specify the wanted property
14589 (cdr (assoc property (org-entry-properties nil 'special property)))
14590 (let* ((range (org-get-property-block))
14591 (props (list (or (assoc property org-file-properties)
14592 (assoc property org-global-properties)
14593 (assoc property org-global-properties-fixed))))
14594 (ap (lambda (key)
14595 (when (re-search-forward
14596 (org-re-property key) (cdr range) t)
14597 (setq props
14598 (org-update-property-plist
14600 (if (match-end 1)
14601 (org-match-string-no-properties 1) "")
14602 props)))))
14603 val)
14604 (when (and range (goto-char (car range)))
14605 (funcall ap property)
14606 (goto-char (car range))
14607 (while (funcall ap (concat property "+")))
14608 (setq val (cdr (assoc property props)))
14609 (when val (if literal-nil val (org-not-nil val)))))))))
14611 (defun org-property-or-variable-value (var &optional inherit)
14612 "Check if there is a property fixing the value of VAR.
14613 If yes, return this value. If not, return the current value of the variable."
14614 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14615 (if (and prop (stringp prop) (string-match "\\S-" prop))
14616 (read prop)
14617 (symbol-value var))))
14619 (defun org-entry-delete (pom property)
14620 "Delete the property PROPERTY from entry at point-or-marker POM."
14621 (org-with-point-at pom
14622 (if (member property org-special-properties)
14623 nil ; cannot delete these properties.
14624 (let ((range (org-get-property-block)))
14625 (if (and range
14626 (goto-char (car range))
14627 (re-search-forward
14628 (org-re-property property)
14629 (cdr range) t))
14630 (progn
14631 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14633 nil)))))
14635 ;; Multi-values properties are properties that contain multiple values
14636 ;; These values are assumed to be single words, separated by whitespace.
14637 (defun org-entry-add-to-multivalued-property (pom property value)
14638 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14639 (let* ((old (org-entry-get pom property))
14640 (values (and old (org-split-string old "[ \t]"))))
14641 (setq value (org-entry-protect-space value))
14642 (unless (member value values)
14643 (setq values (cons value values))
14644 (org-entry-put pom property
14645 (mapconcat 'identity values " ")))))
14647 (defun org-entry-remove-from-multivalued-property (pom property value)
14648 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14649 (let* ((old (org-entry-get pom property))
14650 (values (and old (org-split-string old "[ \t]"))))
14651 (setq value (org-entry-protect-space value))
14652 (when (member value values)
14653 (setq values (delete value values))
14654 (org-entry-put pom property
14655 (mapconcat 'identity values " ")))))
14657 (defun org-entry-member-in-multivalued-property (pom property value)
14658 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14659 (let* ((old (org-entry-get pom property))
14660 (values (and old (org-split-string old "[ \t]"))))
14661 (setq value (org-entry-protect-space value))
14662 (member value values)))
14664 (defun org-entry-get-multivalued-property (pom property)
14665 "Return a list of values in a multivalued property."
14666 (let* ((value (org-entry-get pom property))
14667 (values (and value (org-split-string value "[ \t]"))))
14668 (mapcar 'org-entry-restore-space values)))
14670 (defun org-entry-put-multivalued-property (pom property &rest values)
14671 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14672 VALUES should be a list of strings. Spaces will be protected."
14673 (org-entry-put pom property
14674 (mapconcat 'org-entry-protect-space values " "))
14675 (let* ((value (org-entry-get pom property))
14676 (values (and value (org-split-string value "[ \t]"))))
14677 (mapcar 'org-entry-restore-space values)))
14679 (defun org-entry-protect-space (s)
14680 "Protect spaces and newline in string S."
14681 (while (string-match " " s)
14682 (setq s (replace-match "%20" t t s)))
14683 (while (string-match "\n" s)
14684 (setq s (replace-match "%0A" t t s)))
14687 (defun org-entry-restore-space (s)
14688 "Restore spaces and newline in string S."
14689 (while (string-match "%20" s)
14690 (setq s (replace-match " " t t s)))
14691 (while (string-match "%0A" s)
14692 (setq s (replace-match "\n" t t s)))
14695 (defvar org-entry-property-inherited-from (make-marker)
14696 "Marker pointing to the entry from where a property was inherited.
14697 Each call to `org-entry-get-with-inheritance' will set this marker to the
14698 location of the entry where the inheritance search matched. If there was
14699 no match, the marker will point nowhere.
14700 Note that also `org-entry-get' calls this function, if the INHERIT flag
14701 is set.")
14703 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14704 "Get PROPERTY of entry or content at point, search higher levels if needed.
14705 The search will stop at the first ancestor which has the property defined.
14706 If the value found is \"nil\", return nil to show that the property
14707 should be considered as undefined (this is the meaning of nil here).
14708 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14709 (move-marker org-entry-property-inherited-from nil)
14710 (let (tmp)
14711 (save-excursion
14712 (save-restriction
14713 (widen)
14714 (catch 'ex
14715 (while t
14716 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14717 (or (ignore-errors (org-back-to-heading t))
14718 (goto-char (point-min)))
14719 (move-marker org-entry-property-inherited-from (point))
14720 (throw 'ex tmp))
14721 (or (ignore-errors (org-up-heading-safe))
14722 (throw 'ex nil))))))
14723 (setq tmp (or tmp
14724 (cdr (assoc property org-file-properties))
14725 (cdr (assoc property org-global-properties))
14726 (cdr (assoc property org-global-properties-fixed))))
14727 (if literal-nil tmp (org-not-nil tmp))))
14729 (defvar org-property-changed-functions nil
14730 "Hook called when the value of a property has changed.
14731 Each hook function should accept two arguments, the name of the property
14732 and the new value.")
14734 (defun org-entry-put (pom property value)
14735 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14736 (org-with-point-at pom
14737 (org-back-to-heading t)
14738 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14739 range)
14740 (cond
14741 ((equal property "TODO")
14742 (when (and (stringp value) (string-match "\\S-" value)
14743 (not (member value org-todo-keywords-1)))
14744 (error "\"%s\" is not a valid TODO state" value))
14745 (if (or (not value)
14746 (not (string-match "\\S-" value)))
14747 (setq value 'none))
14748 (org-todo value)
14749 (org-set-tags nil 'align))
14750 ((equal property "PRIORITY")
14751 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14752 (string-to-char value) ?\ ))
14753 (org-set-tags nil 'align))
14754 ((equal property "CLOCKSUM")
14755 (if (not (re-search-forward
14756 (concat org-clock-string "\\]--\\(\\[[^]]+\\]\\)") nil t))
14757 (error "Cannot find a clock log")
14758 (goto-char (- (match-end 1) 2))
14759 (cond
14760 ((eq value 'earlier) (org-timestamp-down))
14761 ((eq value 'later) (org-timestamp-up)))
14762 (org-clock-sum-current-item)))
14763 ((equal property "SCHEDULED")
14764 (if (re-search-forward org-scheduled-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-schedule)))
14769 (call-interactively 'org-schedule)))
14770 ((equal property "DEADLINE")
14771 (if (re-search-forward org-deadline-time-regexp end t)
14772 (cond
14773 ((eq value 'earlier) (org-timestamp-change -1 'day))
14774 ((eq value 'later) (org-timestamp-change 1 'day))
14775 (t (call-interactively 'org-deadline)))
14776 (call-interactively 'org-deadline)))
14777 ((member property org-special-properties)
14778 (error "The %s property can not yet be set with `org-entry-put'"
14779 property))
14780 (t ; a non-special property
14781 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14782 (setq range (org-get-property-block beg end 'force))
14783 (goto-char (car range))
14784 (if (re-search-forward
14785 (org-re-property-keyword property) (cdr range) t)
14786 (progn
14787 (delete-region (match-beginning 0) (match-end 0))
14788 (goto-char (match-beginning 0)))
14789 (goto-char (cdr range))
14790 (insert "\n")
14791 (backward-char 1)
14792 (org-indent-line))
14793 (insert ":" property ":")
14794 (and value (insert " " value))
14795 (org-indent-line)))))
14796 (run-hook-with-args 'org-property-changed-functions property value)))
14798 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14799 "Get all property keys in the current buffer.
14800 With INCLUDE-SPECIALS, also list the special properties that reflect things
14801 like tags and TODO state.
14802 With INCLUDE-DEFAULTS, also include properties that has special meaning
14803 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14804 and others.
14805 With INCLUDE-COLUMNS, also include property names given in COLUMN
14806 formats in the current buffer."
14807 (let (rtn range cfmt s p)
14808 (save-excursion
14809 (save-restriction
14810 (widen)
14811 (goto-char (point-min))
14812 (while (re-search-forward org-property-start-re nil t)
14813 (setq range (org-get-property-block))
14814 (goto-char (car range))
14815 (while (re-search-forward
14816 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14817 (cdr range) t)
14818 (add-to-list 'rtn (org-match-string-no-properties 1)))
14819 (outline-next-heading))))
14821 (when include-specials
14822 (setq rtn (append org-special-properties rtn)))
14824 (when include-defaults
14825 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14826 (add-to-list 'rtn org-effort-property))
14828 (when include-columns
14829 (save-excursion
14830 (save-restriction
14831 (widen)
14832 (goto-char (point-min))
14833 (while (re-search-forward
14834 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14835 nil t)
14836 (setq cfmt (match-string 2) s 0)
14837 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14838 cfmt s)
14839 (setq s (match-end 0)
14840 p (match-string 1 cfmt))
14841 (unless (or (equal p "ITEM")
14842 (member p org-special-properties))
14843 (add-to-list 'rtn (match-string 1 cfmt))))))))
14845 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14847 (defun org-property-values (key)
14848 "Return a list of all values of property KEY in the current buffer."
14849 (save-excursion
14850 (save-restriction
14851 (widen)
14852 (goto-char (point-min))
14853 (let ((re (org-re-property key))
14854 values)
14855 (while (re-search-forward re nil t)
14856 (add-to-list 'values (org-trim (match-string 1))))
14857 (delete "" values)))))
14859 (defun org-insert-property-drawer ()
14860 "Insert a property drawer into the current entry."
14861 (org-back-to-heading t)
14862 (looking-at org-outline-regexp)
14863 (let ((indent (if org-adapt-indentation
14864 (- (match-end 0) (match-beginning 0))
14866 (beg (point))
14867 (re (concat "^[ \t]*" org-keyword-time-regexp))
14868 end hiddenp)
14869 (outline-next-heading)
14870 (setq end (point))
14871 (goto-char beg)
14872 (while (re-search-forward re end t))
14873 (setq hiddenp (outline-invisible-p))
14874 (end-of-line 1)
14875 (and (equal (char-after) ?\n) (forward-char 1))
14876 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14877 (if (member (match-string 1) '("CLOCK:" ":END:"))
14878 ;; just skip this line
14879 (beginning-of-line 2)
14880 ;; Drawer start, find the end
14881 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14882 (beginning-of-line 1)))
14883 (org-skip-over-state-notes)
14884 (skip-chars-backward " \t\n\r")
14885 (if (eq (char-before) ?*) (forward-char 1))
14886 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14887 (beginning-of-line 0)
14888 (org-indent-to-column indent)
14889 (beginning-of-line 2)
14890 (org-indent-to-column indent)
14891 (beginning-of-line 0)
14892 (if hiddenp
14893 (save-excursion
14894 (org-back-to-heading t)
14895 (hide-entry))
14896 (org-flag-drawer t))))
14898 (defun org-insert-drawer (&optional arg drawer)
14899 "Insert a drawer at point.
14901 Optional argument DRAWER, when non-nil, is a string representing
14902 drawer's name. Otherwise, the user is prompted for a name.
14904 If a region is active, insert the drawer around that region
14905 instead.
14907 Point is left between drawer's boundaries."
14908 (interactive "P")
14909 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14910 "LOGBOOK"))
14911 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14912 ;; internally by Org. They are meant to be inserted
14913 ;; automatically.
14914 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14915 ;; Remove system drawers from list. Note: For some reason,
14916 ;; `org-completing-read' ignores the predicate while
14917 ;; `completing-read' handles it fine.
14918 (drawer (if arg "PROPERTIES"
14919 (or drawer
14920 (completing-read
14921 "Drawer: " org-drawers
14922 (lambda (d) (not (member d system-drawers))))))))
14923 (cond
14924 ;; With C-u, fall back on `org-insert-property-drawer'
14925 (arg (org-insert-property-drawer))
14926 ;; With an active region, insert a drawer at point.
14927 ((not (org-region-active-p))
14928 (progn
14929 (unless (bolp) (insert "\n"))
14930 (insert (format ":%s:\n\n:END:\n" drawer))
14931 (forward-line -2)))
14932 ;; Otherwise, insert the drawer at point
14934 (let ((rbeg (region-beginning))
14935 (rend (copy-marker (region-end))))
14936 (unwind-protect
14937 (progn
14938 (goto-char rbeg)
14939 (beginning-of-line)
14940 (when (save-excursion
14941 (re-search-forward org-outline-regexp-bol rend t))
14942 (error "Drawers cannot contain headlines"))
14943 ;; Position point at the beginning of the first
14944 ;; non-blank line in region. Insert drawer's opening
14945 ;; there, then indent it.
14946 (org-skip-whitespace)
14947 (beginning-of-line)
14948 (insert ":" drawer ":\n")
14949 (forward-line -1)
14950 (indent-for-tab-command)
14951 ;; Move point to the beginning of the first blank line
14952 ;; after the last non-blank line in region. Insert
14953 ;; drawer's closing, then indent it.
14954 (goto-char rend)
14955 (skip-chars-backward " \r\t\n")
14956 (insert "\n:END:")
14957 (indent-for-tab-command)
14958 (unless (eolp) (insert "\n")))
14959 ;; Clear marker, whatever the outcome of insertion is.
14960 (set-marker rend nil)))))))
14962 (defvar org-property-set-functions-alist nil
14963 "Property set function alist.
14964 Each entry should have the following format:
14966 (PROPERTY . READ-FUNCTION)
14968 The read function will be called with the same argument as
14969 `org-completing-read'.")
14971 (defun org-set-property-function (property)
14972 "Get the function that should be used to set PROPERTY.
14973 This is computed according to `org-property-set-functions-alist'."
14974 (or (cdr (assoc property org-property-set-functions-alist))
14975 'org-completing-read))
14977 (defun org-read-property-value (property)
14978 "Read PROPERTY value from user."
14979 (let* ((completion-ignore-case t)
14980 (allowed (org-property-get-allowed-values nil property 'table))
14981 (cur (org-entry-get nil property))
14982 (prompt (concat property " value"
14983 (if (and cur (string-match "\\S-" cur))
14984 (concat " [" cur "]") "") ": "))
14985 (set-function (org-set-property-function property))
14986 (val (if allowed
14987 (funcall set-function prompt allowed nil
14988 (not (get-text-property 0 'org-unrestricted
14989 (caar allowed))))
14990 (let (org-completion-use-ido org-completion-use-iswitchb)
14991 (funcall set-function prompt
14992 (mapcar 'list (org-property-values property))
14993 nil nil "" nil cur)))))
14994 (if (equal val "")
14996 val)))
14998 (defvar org-last-set-property nil)
14999 (defun org-read-property-name ()
15000 "Read a property name."
15001 (let* ((completion-ignore-case t)
15002 (keys (org-buffer-property-keys nil t t))
15003 (default-prop (or (save-excursion
15004 (save-match-data
15005 (beginning-of-line)
15006 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15007 (null (string= (match-string 1) "END"))
15008 (match-string 1))))
15009 org-last-set-property))
15010 (property (org-icompleting-read
15011 (concat "Property"
15012 (if default-prop (concat " [" default-prop "]") "")
15013 ": ")
15014 (mapcar 'list keys)
15015 nil nil nil nil
15016 default-prop
15018 (if (member property keys)
15019 property
15020 (or (cdr (assoc (downcase property)
15021 (mapcar (lambda (x) (cons (downcase x) x))
15022 keys)))
15023 property))))
15025 (defun org-set-property (property value)
15026 "In the current entry, set PROPERTY to VALUE.
15027 When called interactively, this will prompt for a property name, offering
15028 completion on existing and default properties. And then it will prompt
15029 for a value, offering completion either on allowed values (via an inherited
15030 xxx_ALL property) or on existing values in other instances of this property
15031 in the current file."
15032 (interactive (list nil nil))
15033 (let* ((property (or property (org-read-property-name)))
15034 (value (or value (org-read-property-value property)))
15035 (fn (cdr (assoc property org-properties-postprocess-alist))))
15036 (setq org-last-set-property property)
15037 ;; Possibly postprocess the inserted value:
15038 (when fn (setq value (funcall fn value)))
15039 (unless (equal (org-entry-get nil property) value)
15040 (org-entry-put nil property value))))
15042 (defun org-delete-property (property)
15043 "In the current entry, delete PROPERTY."
15044 (interactive
15045 (let* ((completion-ignore-case t)
15046 (prop (org-icompleting-read "Property: "
15047 (org-entry-properties nil 'standard))))
15048 (list prop)))
15049 (message "Property %s %s" property
15050 (if (org-entry-delete nil property)
15051 "deleted"
15052 "was not present in the entry")))
15054 (defun org-delete-property-globally (property)
15055 "Remove PROPERTY globally, from all entries."
15056 (interactive
15057 (let* ((completion-ignore-case t)
15058 (prop (org-icompleting-read
15059 "Globally remove property: "
15060 (mapcar 'list (org-buffer-property-keys)))))
15061 (list prop)))
15062 (save-excursion
15063 (save-restriction
15064 (widen)
15065 (goto-char (point-min))
15066 (let ((cnt 0))
15067 (while (re-search-forward
15068 (org-re-property property)
15069 nil t)
15070 (setq cnt (1+ cnt))
15071 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15072 (message "Property \"%s\" removed from %d entries" property cnt)))))
15074 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15076 (defun org-compute-property-at-point ()
15077 "Compute the property at point.
15078 This looks for an enclosing column format, extracts the operator and
15079 then applies it to the property in the column format's scope."
15080 (interactive)
15081 (unless (org-at-property-p)
15082 (error "Not at a property"))
15083 (let ((prop (org-match-string-no-properties 2)))
15084 (org-columns-get-format-and-top-level)
15085 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15086 (error "No operator defined for property %s" prop))
15087 (org-columns-compute prop)))
15089 (defvar org-property-allowed-value-functions nil
15090 "Hook for functions supplying allowed values for a specific property.
15091 The functions must take a single argument, the name of the property, and
15092 return a flat list of allowed values. If \":ETC\" is one of
15093 the values, this means that these values are intended as defaults for
15094 completion, but that other values should be allowed too.
15095 The functions must return nil if they are not responsible for this
15096 property.")
15098 (defun org-property-get-allowed-values (pom property &optional table)
15099 "Get allowed values for the property PROPERTY.
15100 When TABLE is non-nil, return an alist that can directly be used for
15101 completion."
15102 (let (vals)
15103 (cond
15104 ((equal property "TODO")
15105 (setq vals (org-with-point-at pom
15106 (append org-todo-keywords-1 '("")))))
15107 ((equal property "PRIORITY")
15108 (let ((n org-lowest-priority))
15109 (while (>= n org-highest-priority)
15110 (push (char-to-string n) vals)
15111 (setq n (1- n)))))
15112 ((member property org-special-properties))
15113 ((setq vals (run-hook-with-args-until-success
15114 'org-property-allowed-value-functions property)))
15116 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15117 (when (and vals (string-match "\\S-" vals))
15118 (setq vals (car (read-from-string (concat "(" vals ")"))))
15119 (setq vals (mapcar (lambda (x)
15120 (cond ((stringp x) x)
15121 ((numberp x) (number-to-string x))
15122 ((symbolp x) (symbol-name x))
15123 (t "???")))
15124 vals)))))
15125 (when (member ":ETC" vals)
15126 (setq vals (remove ":ETC" vals))
15127 (org-add-props (car vals) '(org-unrestricted t)))
15128 (if table (mapcar 'list vals) vals)))
15130 (defun org-property-previous-allowed-value (&optional previous)
15131 "Switch to the next allowed value for this property."
15132 (interactive)
15133 (org-property-next-allowed-value t))
15135 (defun org-property-next-allowed-value (&optional previous)
15136 "Switch to the next allowed value for this property."
15137 (interactive)
15138 (unless (org-at-property-p)
15139 (error "Not at a property"))
15140 (let* ((key (match-string 2))
15141 (value (match-string 3))
15142 (allowed (or (org-property-get-allowed-values (point) key)
15143 (and (member value '("[ ]" "[-]" "[X]"))
15144 '("[ ]" "[X]"))))
15145 nval)
15146 (unless allowed
15147 (error "Allowed values for this property have not been defined"))
15148 (if previous (setq allowed (reverse allowed)))
15149 (if (member value allowed)
15150 (setq nval (car (cdr (member value allowed)))))
15151 (setq nval (or nval (car allowed)))
15152 (if (equal nval value)
15153 (error "Only one allowed value for this property"))
15154 (org-at-property-p)
15155 (replace-match (concat " :" key ": " nval) t t)
15156 (org-indent-line)
15157 (beginning-of-line 1)
15158 (skip-chars-forward " \t")
15159 (run-hook-with-args 'org-property-changed-functions key nval)))
15161 (defun org-find-olp (path &optional this-buffer)
15162 "Return a marker pointing to the entry at outline path OLP.
15163 If anything goes wrong, throw an error.
15164 You can wrap this call to catch the error like this:
15166 (condition-case msg
15167 (org-mobile-locate-entry (match-string 4))
15168 (error (nth 1 msg)))
15170 The return value will then be either a string with the error message,
15171 or a marker if everything is OK.
15173 If THIS-BUFFER is set, the outline path does not contain a file,
15174 only headings."
15175 (let* ((file (if this-buffer buffer-file-name (pop path)))
15176 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15177 (level 1)
15178 (lmin 1)
15179 (lmax 1)
15180 limit re end found pos heading cnt flevel)
15181 (unless buffer (error "File not found :%s" file))
15182 (with-current-buffer buffer
15183 (save-excursion
15184 (save-restriction
15185 (widen)
15186 (setq limit (point-max))
15187 (goto-char (point-min))
15188 (while (setq heading (pop path))
15189 (setq re (format org-complex-heading-regexp-format
15190 (regexp-quote heading)))
15191 (setq cnt 0 pos (point))
15192 (while (re-search-forward re end t)
15193 (setq level (- (match-end 1) (match-beginning 1)))
15194 (if (and (>= level lmin) (<= level lmax))
15195 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15196 (when (= cnt 0) (error "Heading not found on level %d: %s"
15197 lmax heading))
15198 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15199 lmax heading))
15200 (goto-char found)
15201 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15202 (setq end (save-excursion (org-end-of-subtree t t))))
15203 (when (org-at-heading-p)
15204 (move-marker (make-marker) (point))))))))
15206 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15207 "Find node HEADING in BUFFER.
15208 Return a marker to the heading if it was found, or nil if not.
15209 If POS-ONLY is set, return just the position instead of a marker.
15211 The heading text must match exact, but it may have a TODO keyword,
15212 a priority cookie and tags in the standard locations."
15213 (with-current-buffer (or buffer (current-buffer))
15214 (save-excursion
15215 (save-restriction
15216 (widen)
15217 (goto-char (point-min))
15218 (let (case-fold-search)
15219 (if (re-search-forward
15220 (format org-complex-heading-regexp-format
15221 (regexp-quote heading)) nil t)
15222 (if pos-only
15223 (match-beginning 0)
15224 (move-marker (make-marker) (match-beginning 0)))))))))
15226 (defun org-find-exact-heading-in-directory (heading &optional dir)
15227 "Find Org node headline HEADING in all .org files in directory DIR.
15228 When the target headline is found, return a marker to this location."
15229 (let ((files (directory-files (or dir default-directory)
15230 nil "\\`[^.#].*\\.org\\'"))
15231 file visiting m buffer)
15232 (catch 'found
15233 (while (setq file (pop files))
15234 (message "trying %s" file)
15235 (setq visiting (org-find-base-buffer-visiting file))
15236 (setq buffer (or visiting (find-file-noselect file)))
15237 (setq m (org-find-exact-headline-in-buffer
15238 heading buffer))
15239 (when (and (not m) (not visiting)) (kill-buffer buffer))
15240 (and m (throw 'found m))))))
15242 (defun org-find-entry-with-id (ident)
15243 "Locate the entry that contains the ID property with exact value IDENT.
15244 IDENT can be a string, a symbol or a number, this function will search for
15245 the string representation of it.
15246 Return the position where this entry starts, or nil if there is no such entry."
15247 (interactive "sID: ")
15248 (let ((id (cond
15249 ((stringp ident) ident)
15250 ((symbol-name ident) (symbol-name ident))
15251 ((numberp ident) (number-to-string ident))
15252 (t (error "IDENT %s must be a string, symbol or number" ident))))
15253 (case-fold-search nil))
15254 (save-excursion
15255 (save-restriction
15256 (widen)
15257 (goto-char (point-min))
15258 (when (re-search-forward
15259 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15260 nil t)
15261 (org-back-to-heading t)
15262 (point))))))
15264 ;;;; Timestamps
15266 (defvar org-last-changed-timestamp nil)
15267 (defvar org-last-inserted-timestamp nil
15268 "The last time stamp inserted with `org-insert-time-stamp'.")
15269 (defvar org-time-was-given) ; dynamically scoped parameter
15270 (defvar org-end-time-was-given) ; dynamically scoped parameter
15271 (defvar org-ts-what) ; dynamically scoped parameter
15273 (defun org-time-stamp (arg &optional inactive)
15274 "Prompt for a date/time and insert a time stamp.
15275 If the user specifies a time like HH:MM or if this command is
15276 called with at least one prefix argument, the time stamp contains
15277 the date and the time. Otherwise, only the date is be included.
15279 All parts of a date not specified by the user is filled in from
15280 the current date/time. So if you just press return without
15281 typing anything, the time stamp will represent the current
15282 date/time.
15284 If there is already a timestamp at the cursor, it will be
15285 modified.
15287 With two universal prefix arguments, insert an active timestamp
15288 with the current time without prompting the user."
15289 (interactive "P")
15290 (let* ((ts nil)
15291 (default-time
15292 ;; Default time is either today, or, when entering a range,
15293 ;; the range start.
15294 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15295 (save-excursion
15296 (re-search-backward
15297 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15298 (- (point) 20) t)))
15299 (apply 'encode-time (org-parse-time-string (match-string 1)))
15300 (current-time)))
15301 (default-input (and ts (org-get-compact-tod ts)))
15302 (repeater (save-excursion
15303 (save-match-data
15304 (beginning-of-line)
15305 (when (re-search-forward
15306 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15307 (save-excursion (progn (end-of-line) (point))) t)
15308 (match-string 0)))))
15309 org-time-was-given org-end-time-was-given time)
15310 (cond
15311 ((and (org-at-timestamp-p t)
15312 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15313 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15314 (insert "--")
15315 (setq time (let ((this-command this-command))
15316 (org-read-date arg 'totime nil nil
15317 default-time default-input inactive)))
15318 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15319 ((org-at-timestamp-p t)
15320 (setq time (let ((this-command this-command))
15321 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15322 (when (org-at-timestamp-p t) ; just to get the match data
15323 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15324 (replace-match "")
15325 (setq org-last-changed-timestamp
15326 (org-insert-time-stamp
15327 time (or org-time-was-given arg)
15328 inactive nil nil (list org-end-time-was-given)))
15329 (when repeater (goto-char (1- (point))) (insert " " repeater)
15330 (setq org-last-changed-timestamp
15331 (concat (substring org-last-inserted-timestamp 0 -1)
15332 " " repeater ">"))))
15333 (message "Timestamp updated"))
15334 ((equal arg '(16))
15335 (org-insert-time-stamp (current-time) t))
15337 (setq time (let ((this-command this-command))
15338 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15339 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15340 nil nil (list org-end-time-was-given))))))
15342 ;; FIXME: can we use this for something else, like computing time differences?
15343 (defun org-get-compact-tod (s)
15344 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15345 (let* ((t1 (match-string 1 s))
15346 (h1 (string-to-number (match-string 2 s)))
15347 (m1 (string-to-number (match-string 3 s)))
15348 (t2 (and (match-end 4) (match-string 5 s)))
15349 (h2 (and t2 (string-to-number (match-string 6 s))))
15350 (m2 (and t2 (string-to-number (match-string 7 s))))
15351 dh dm)
15352 (if (not t2)
15354 (setq dh (- h2 h1) dm (- m2 m1))
15355 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15356 (concat t1 "+" (number-to-string dh)
15357 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15359 (defun org-time-stamp-inactive (&optional arg)
15360 "Insert an inactive time stamp.
15361 An inactive time stamp is enclosed in square brackets instead of angle
15362 brackets. It is inactive in the sense that it does not trigger agenda entries,
15363 does not link to the calendar and cannot be changed with the S-cursor keys.
15364 So these are more for recording a certain time/date."
15365 (interactive "P")
15366 (org-time-stamp arg 'inactive))
15368 (defvar org-date-ovl (make-overlay 1 1))
15369 (overlay-put org-date-ovl 'face 'org-date-selected)
15370 (org-detach-overlay org-date-ovl)
15372 (defvar org-ans1) ; dynamically scoped parameter
15373 (defvar org-ans2) ; dynamically scoped parameter
15375 (defvar org-plain-time-of-day-regexp) ; defined below
15377 (defvar org-overriding-default-time nil) ; dynamically scoped
15378 (defvar org-read-date-overlay nil)
15379 (defvar org-dcst nil) ; dynamically scoped
15380 (defvar org-read-date-history nil)
15381 (defvar org-read-date-final-answer nil)
15382 (defvar org-read-date-analyze-futurep nil)
15383 (defvar org-read-date-analyze-forced-year nil)
15384 (defvar org-read-date-inactive)
15386 (defun org-read-date (&optional org-with-time to-time from-string prompt
15387 default-time default-input inactive)
15388 "Read a date, possibly a time, and make things smooth for the user.
15389 The prompt will suggest to enter an ISO date, but you can also enter anything
15390 which will at least partially be understood by `parse-time-string'.
15391 Unrecognized parts of the date will default to the current day, month, year,
15392 hour and minute. If this command is called to replace a timestamp at point,
15393 or to enter the second timestamp of a range, the default time is taken
15394 from the existing stamp. Furthermore, the command prefers the future,
15395 so if you are giving a date where the year is not given, and the day-month
15396 combination is already past in the current year, it will assume you
15397 mean next year. For details, see the manual. A few examples:
15399 3-2-5 --> 2003-02-05
15400 feb 15 --> currentyear-02-15
15401 2/15 --> currentyear-02-15
15402 sep 12 9 --> 2009-09-12
15403 12:45 --> today 12:45
15404 22 sept 0:34 --> currentyear-09-22 0:34
15405 12 --> currentyear-currentmonth-12
15406 Fri --> nearest Friday (today or later)
15407 etc.
15409 Furthermore you can specify a relative date by giving, as the *first* thing
15410 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15411 change in days weeks, months, years.
15412 With a single plus or minus, the date is relative to today. With a double
15413 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15414 +4d --> four days from today
15415 +4 --> same as above
15416 +2w --> two weeks from today
15417 ++5 --> five days from default date
15419 The function understands only English month and weekday abbreviations.
15421 While prompting, a calendar is popped up - you can also select the
15422 date with the mouse (button 1). The calendar shows a period of three
15423 months. To scroll it to other months, use the keys `>' and `<'.
15424 If you don't like the calendar, turn it off with
15425 \(setq org-read-date-popup-calendar nil)
15427 With optional argument TO-TIME, the date will immediately be converted
15428 to an internal time.
15429 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15430 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15431 still enter a time, and this function will inform the calling routine
15432 about this change. The calling routine may then choose to change the
15433 format used to insert the time stamp into the buffer to include the time.
15434 With optional argument FROM-STRING, read from this string instead from
15435 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15436 the time/date that is used for everything that is not specified by the
15437 user."
15438 (require 'parse-time)
15439 (let* ((org-time-stamp-rounding-minutes
15440 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15441 (org-dcst org-display-custom-times)
15442 (ct (org-current-time))
15443 (org-def (or org-overriding-default-time default-time ct))
15444 (org-defdecode (decode-time org-def))
15445 (dummy (progn
15446 (when (< (nth 2 org-defdecode) org-extend-today-until)
15447 (setcar (nthcdr 2 org-defdecode) -1)
15448 (setcar (nthcdr 1 org-defdecode) 59)
15449 (setq org-def (apply 'encode-time org-defdecode)
15450 org-defdecode (decode-time org-def)))))
15451 (calendar-frame-setup nil)
15452 (calendar-setup nil)
15453 (calendar-move-hook nil)
15454 (calendar-view-diary-initially-flag nil)
15455 (calendar-view-holidays-initially-flag nil)
15456 (timestr (format-time-string
15457 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15458 (prompt (concat (if prompt (concat prompt " ") "")
15459 (format "Date+time [%s]: " timestr)))
15460 ans (org-ans0 "") org-ans1 org-ans2 final)
15462 (cond
15463 (from-string (setq ans from-string))
15464 (org-read-date-popup-calendar
15465 (save-excursion
15466 (save-window-excursion
15467 (calendar)
15468 (org-eval-in-calendar '(setq cursor-type nil) t)
15469 (unwind-protect
15470 (progn
15471 (calendar-forward-day (- (time-to-days org-def)
15472 (calendar-absolute-from-gregorian
15473 (calendar-current-date))))
15474 (org-eval-in-calendar nil t)
15475 (let* ((old-map (current-local-map))
15476 (map (copy-keymap calendar-mode-map))
15477 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15478 (org-defkey map (kbd "RET") 'org-calendar-select)
15479 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15480 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15481 (org-defkey minibuffer-local-map [(meta shift left)]
15482 (lambda () (interactive)
15483 (org-eval-in-calendar '(calendar-backward-month 1))))
15484 (org-defkey minibuffer-local-map [(meta shift right)]
15485 (lambda () (interactive)
15486 (org-eval-in-calendar '(calendar-forward-month 1))))
15487 (org-defkey minibuffer-local-map [(meta shift up)]
15488 (lambda () (interactive)
15489 (org-eval-in-calendar '(calendar-backward-year 1))))
15490 (org-defkey minibuffer-local-map [(meta shift down)]
15491 (lambda () (interactive)
15492 (org-eval-in-calendar '(calendar-forward-year 1))))
15493 (org-defkey minibuffer-local-map [?\e (shift left)]
15494 (lambda () (interactive)
15495 (org-eval-in-calendar '(calendar-backward-month 1))))
15496 (org-defkey minibuffer-local-map [?\e (shift right)]
15497 (lambda () (interactive)
15498 (org-eval-in-calendar '(calendar-forward-month 1))))
15499 (org-defkey minibuffer-local-map [?\e (shift up)]
15500 (lambda () (interactive)
15501 (org-eval-in-calendar '(calendar-backward-year 1))))
15502 (org-defkey minibuffer-local-map [?\e (shift down)]
15503 (lambda () (interactive)
15504 (org-eval-in-calendar '(calendar-forward-year 1))))
15505 (org-defkey minibuffer-local-map [(shift up)]
15506 (lambda () (interactive)
15507 (org-eval-in-calendar '(calendar-backward-week 1))))
15508 (org-defkey minibuffer-local-map [(shift down)]
15509 (lambda () (interactive)
15510 (org-eval-in-calendar '(calendar-forward-week 1))))
15511 (org-defkey minibuffer-local-map [(shift left)]
15512 (lambda () (interactive)
15513 (org-eval-in-calendar '(calendar-backward-day 1))))
15514 (org-defkey minibuffer-local-map [(shift right)]
15515 (lambda () (interactive)
15516 (org-eval-in-calendar '(calendar-forward-day 1))))
15517 (org-defkey minibuffer-local-map ">"
15518 (lambda () (interactive)
15519 (org-eval-in-calendar '(scroll-calendar-left 1))))
15520 (org-defkey minibuffer-local-map "<"
15521 (lambda () (interactive)
15522 (org-eval-in-calendar '(scroll-calendar-right 1))))
15523 (org-defkey minibuffer-local-map "\C-v"
15524 (lambda () (interactive)
15525 (org-eval-in-calendar
15526 '(calendar-scroll-left-three-months 1))))
15527 (org-defkey minibuffer-local-map "\M-v"
15528 (lambda () (interactive)
15529 (org-eval-in-calendar
15530 '(calendar-scroll-right-three-months 1))))
15531 (run-hooks 'org-read-date-minibuffer-setup-hook)
15532 (unwind-protect
15533 (progn
15534 (use-local-map map)
15535 (setq org-read-date-inactive inactive)
15536 (add-hook 'post-command-hook 'org-read-date-display)
15537 (setq org-ans0 (read-string prompt default-input
15538 'org-read-date-history nil))
15539 ;; org-ans0: from prompt
15540 ;; org-ans1: from mouse click
15541 ;; org-ans2: from calendar motion
15542 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15543 (remove-hook 'post-command-hook 'org-read-date-display)
15544 (use-local-map old-map)
15545 (when org-read-date-overlay
15546 (delete-overlay org-read-date-overlay)
15547 (setq org-read-date-overlay nil)))))
15548 (bury-buffer "*Calendar*")))))
15550 (t ; Naked prompt only
15551 (unwind-protect
15552 (setq ans (read-string prompt default-input
15553 'org-read-date-history timestr))
15554 (when org-read-date-overlay
15555 (delete-overlay org-read-date-overlay)
15556 (setq org-read-date-overlay nil)))))
15558 (setq final (org-read-date-analyze ans org-def org-defdecode))
15560 (when org-read-date-analyze-forced-year
15561 (message "Year was forced into %s"
15562 (if org-read-date-force-compatible-dates
15563 "compatible range (1970-2037)"
15564 "range representable on this machine"))
15565 (ding))
15567 ;; One round trip to get rid of 34th of August and stuff like that....
15568 (setq final (decode-time (apply 'encode-time final)))
15570 (setq org-read-date-final-answer ans)
15572 (if to-time
15573 (apply 'encode-time final)
15574 (if (and (boundp 'org-time-was-given) org-time-was-given)
15575 (format "%04d-%02d-%02d %02d:%02d"
15576 (nth 5 final) (nth 4 final) (nth 3 final)
15577 (nth 2 final) (nth 1 final))
15578 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15580 (defvar org-def)
15581 (defvar org-defdecode)
15582 (defvar org-with-time)
15583 (defun org-read-date-display ()
15584 "Display the current date prompt interpretation in the minibuffer."
15585 (when org-read-date-display-live
15586 (when org-read-date-overlay
15587 (delete-overlay org-read-date-overlay))
15588 (when (minibufferp (current-buffer))
15589 (save-excursion
15590 (end-of-line 1)
15591 (while (not (equal (buffer-substring
15592 (max (point-min) (- (point) 4)) (point))
15593 " "))
15594 (insert " ")))
15595 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15596 " " (or org-ans1 org-ans2)))
15597 (org-end-time-was-given nil)
15598 (f (org-read-date-analyze ans org-def org-defdecode))
15599 (fmts (if org-dcst
15600 org-time-stamp-custom-formats
15601 org-time-stamp-formats))
15602 (fmt (if (or org-with-time
15603 (and (boundp 'org-time-was-given) org-time-was-given))
15604 (cdr fmts)
15605 (car fmts)))
15606 (txt (format-time-string fmt (apply 'encode-time f)))
15607 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15608 (txt (concat "=> " txt)))
15609 (when (and org-end-time-was-given
15610 (string-match org-plain-time-of-day-regexp txt))
15611 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15612 org-end-time-was-given
15613 (substring txt (match-end 0)))))
15614 (when org-read-date-analyze-futurep
15615 (setq txt (concat txt " (=>F)")))
15616 (setq org-read-date-overlay
15617 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15618 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15620 (defun org-read-date-analyze (ans org-def org-defdecode)
15621 "Analyze the combined answer of the date prompt."
15622 ;; FIXME: cleanup and comment
15623 (let ((nowdecode (decode-time (current-time)))
15624 delta deltan deltaw deltadef year month day
15625 hour minute second wday pm h2 m2 tl wday1
15626 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15627 (setq org-read-date-analyze-futurep nil
15628 org-read-date-analyze-forced-year nil)
15629 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15630 (setq ans "+0"))
15632 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15633 (unless (save-match-data (string-match org-plain-time-of-day-regexp ans))
15634 (setq ans (replace-match "" t t ans)
15635 deltan (car delta)
15636 deltaw (nth 1 delta)
15637 deltadef (nth 2 delta))))
15639 ;; Check if there is an iso week date in there
15640 ;; If yes, store the info and postpone interpreting it until the rest
15641 ;; of the parsing is done
15642 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15643 (setq iso-year (if (match-end 1)
15644 (org-small-year-to-year
15645 (string-to-number (match-string 1 ans))))
15646 iso-weekday (if (match-end 3)
15647 (string-to-number (match-string 3 ans)))
15648 iso-week (string-to-number (match-string 2 ans)))
15649 (setq ans (replace-match "" t t ans)))
15651 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15652 (when (string-match
15653 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15654 (setq year (if (match-end 2)
15655 (string-to-number (match-string 2 ans))
15656 (progn (setq kill-year t)
15657 (string-to-number (format-time-string "%Y"))))
15658 month (string-to-number (match-string 3 ans))
15659 day (string-to-number (match-string 4 ans)))
15660 (if (< year 100) (setq year (+ 2000 year)))
15661 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15662 t nil ans)))
15664 ;; Help matching dotted european dates
15665 (when (string-match
15666 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15667 (setq year (if (match-end 3)
15668 (string-to-number (match-string 3 ans))
15669 (progn (setq kill-year t)
15670 (string-to-number (format-time-string "%Y"))))
15671 day (string-to-number (match-string 1 ans))
15672 month (string-to-number (match-string 2 ans))
15673 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15674 t nil ans)))
15676 ;; Help matching american dates, like 5/30 or 5/30/7
15677 (when (string-match
15678 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15679 (setq year (if (match-end 4)
15680 (string-to-number (match-string 4 ans))
15681 (progn (setq kill-year t)
15682 (string-to-number (format-time-string "%Y"))))
15683 month (string-to-number (match-string 1 ans))
15684 day (string-to-number (match-string 2 ans)))
15685 (if (< year 100) (setq year (+ 2000 year)))
15686 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15687 t nil ans)))
15688 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15689 ;; If there is a time with am/pm, and *no* time without it, we convert
15690 ;; so that matching will be successful.
15691 (loop for i from 1 to 2 do ; twice, for end time as well
15692 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15693 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15694 (setq hour (string-to-number (match-string 1 ans))
15695 minute (if (match-end 3)
15696 (string-to-number (match-string 3 ans))
15698 pm (equal ?p
15699 (string-to-char (downcase (match-string 4 ans)))))
15700 (if (and (= hour 12) (not pm))
15701 (setq hour 0)
15702 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15703 (setq ans (replace-match (format "%02d:%02d" hour minute)
15704 t t ans))))
15706 ;; Check if a time range is given as a duration
15707 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15708 (setq hour (string-to-number (match-string 1 ans))
15709 h2 (+ hour (string-to-number (match-string 3 ans)))
15710 minute (string-to-number (match-string 2 ans))
15711 m2 (+ minute (if (match-end 5) (string-to-number
15712 (match-string 5 ans))0)))
15713 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15714 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15715 t t ans)))
15717 ;; Check if there is a time range
15718 (when (boundp 'org-end-time-was-given)
15719 (setq org-time-was-given nil)
15720 (when (and (string-match org-plain-time-of-day-regexp ans)
15721 (match-end 8))
15722 (setq org-end-time-was-given (match-string 8 ans))
15723 (setq ans (concat (substring ans 0 (match-beginning 7))
15724 (substring ans (match-end 7))))))
15726 (setq tl (parse-time-string ans)
15727 day (or (nth 3 tl) (nth 3 org-defdecode))
15728 month (or (nth 4 tl)
15729 (if (and org-read-date-prefer-future
15730 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15731 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15732 (nth 4 org-defdecode)))
15733 year (or (and (not kill-year) (nth 5 tl))
15734 (if (and org-read-date-prefer-future
15735 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15736 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15737 (nth 5 org-defdecode)))
15738 hour (or (nth 2 tl) (nth 2 org-defdecode))
15739 minute (or (nth 1 tl) (nth 1 org-defdecode))
15740 second (or (nth 0 tl) 0)
15741 wday (nth 6 tl))
15743 (when (and (eq org-read-date-prefer-future 'time)
15744 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15745 (equal day (nth 3 nowdecode))
15746 (equal month (nth 4 nowdecode))
15747 (equal year (nth 5 nowdecode))
15748 (nth 2 tl)
15749 (or (< (nth 2 tl) (nth 2 nowdecode))
15750 (and (= (nth 2 tl) (nth 2 nowdecode))
15751 (nth 1 tl)
15752 (< (nth 1 tl) (nth 1 nowdecode)))))
15753 (setq day (1+ day)
15754 futurep t))
15756 ;; Special date definitions below
15757 (cond
15758 (iso-week
15759 ;; There was an iso week
15760 (require 'cal-iso)
15761 (setq futurep nil)
15762 (setq year (or iso-year year)
15763 day (or iso-weekday wday 1)
15764 wday nil ; to make sure that the trigger below does not match
15765 iso-date (calendar-gregorian-from-absolute
15766 (calendar-absolute-from-iso
15767 (list iso-week day year))))
15768 ; FIXME: Should we also push ISO weeks into the future?
15769 ; (when (and org-read-date-prefer-future
15770 ; (not iso-year)
15771 ; (< (calendar-absolute-from-gregorian iso-date)
15772 ; (time-to-days (current-time))))
15773 ; (setq year (1+ year)
15774 ; iso-date (calendar-gregorian-from-absolute
15775 ; (calendar-absolute-from-iso
15776 ; (list iso-week day year)))))
15777 (setq month (car iso-date)
15778 year (nth 2 iso-date)
15779 day (nth 1 iso-date)))
15780 (deltan
15781 (setq futurep nil)
15782 (unless deltadef
15783 (let ((now (decode-time (current-time))))
15784 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15785 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15786 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15787 ((equal deltaw "m") (setq month (+ month deltan)))
15788 ((equal deltaw "y") (setq year (+ year deltan)))))
15789 ((and wday (not (nth 3 tl)))
15790 ;; Weekday was given, but no day, so pick that day in the week
15791 ;; on or after the derived date.
15792 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15793 (unless (equal wday wday1)
15794 (setq day (+ day (% (- wday wday1 -7) 7))))))
15795 (if (and (boundp 'org-time-was-given)
15796 (nth 2 tl))
15797 (setq org-time-was-given t))
15798 (if (< year 100) (setq year (+ 2000 year)))
15799 ;; Check of the date is representable
15800 (if org-read-date-force-compatible-dates
15801 (progn
15802 (if (< year 1970)
15803 (setq year 1970 org-read-date-analyze-forced-year t))
15804 (if (> year 2037)
15805 (setq year 2037 org-read-date-analyze-forced-year t)))
15806 (condition-case nil
15807 (ignore (encode-time second minute hour day month year))
15808 (error
15809 (setq year (nth 5 org-defdecode))
15810 (setq org-read-date-analyze-forced-year t))))
15811 (setq org-read-date-analyze-futurep futurep)
15812 (list second minute hour day month year)))
15814 (defvar parse-time-weekdays)
15815 (defun org-read-date-get-relative (s today default)
15816 "Check string S for special relative date string.
15817 TODAY and DEFAULT are internal times, for today and for a default.
15818 Return shift list (N what def-flag)
15819 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15820 N is the number of WHATs to shift.
15821 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15822 the DEFAULT date rather than TODAY."
15823 (require 'parse-time)
15824 (when (and
15825 (string-match
15826 (concat
15827 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15828 "\\([0-9]+\\)?"
15829 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15830 "\\([ \t]\\|$\\)") s)
15831 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15832 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15833 (string-to-char (substring (match-string 1 s) -1))
15834 ?+))
15835 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15836 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15837 (what (if (match-end 3) (match-string 3 s) "d"))
15838 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15839 (date (if rel default today))
15840 (wday (nth 6 (decode-time date)))
15841 delta)
15842 (if wday1
15843 (progn
15844 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15845 (if (= dir ?-) (setq delta (- delta 7)))
15846 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15847 (list delta "d" rel))
15848 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15850 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15851 "Turn a user-specified date into the internal representation.
15852 The internal representation needed by the calendar is (month day year).
15853 This is a wrapper to handle the brain-dead convention in calendar that
15854 user function argument order change dependent on argument order."
15855 (if (boundp 'calendar-date-style)
15856 (cond
15857 ((eq calendar-date-style 'american)
15858 (list arg1 arg2 arg3))
15859 ((eq calendar-date-style 'european)
15860 (list arg2 arg1 arg3))
15861 ((eq calendar-date-style 'iso)
15862 (list arg2 arg3 arg1)))
15863 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15864 (if (org-bound-and-true-p european-calendar-style)
15865 (list arg2 arg1 arg3)
15866 (list arg1 arg2 arg3)))))
15868 (defun org-eval-in-calendar (form &optional keepdate)
15869 "Eval FORM in the calendar window and return to current window.
15870 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15871 otherwise stick to the current value of `org-ans2'."
15872 (let ((sf (selected-frame))
15873 (sw (selected-window)))
15874 (select-window (get-buffer-window "*Calendar*" t))
15875 (eval form)
15876 (when (and (not keepdate) (calendar-cursor-to-date))
15877 (let* ((date (calendar-cursor-to-date))
15878 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15879 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15880 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15881 (select-window sw)
15882 (org-select-frame-set-input-focus sf)))
15884 (defun org-calendar-select ()
15885 "Return to `org-read-date' with the date currently selected.
15886 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15887 (interactive)
15888 (when (calendar-cursor-to-date)
15889 (let* ((date (calendar-cursor-to-date))
15890 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15891 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15892 (if (active-minibuffer-window) (exit-minibuffer))))
15894 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15895 "Insert a date stamp for the date given by the internal TIME.
15896 WITH-HM means use the stamp format that includes the time of the day.
15897 INACTIVE means use square brackets instead of angular ones, so that the
15898 stamp will not contribute to the agenda.
15899 PRE and POST are optional strings to be inserted before and after the
15900 stamp.
15901 The command returns the inserted time stamp."
15902 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15903 stamp)
15904 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15905 (insert-before-markers (or pre ""))
15906 (when (listp extra)
15907 (setq extra (car extra))
15908 (if (and (stringp extra)
15909 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15910 (setq extra (format "-%02d:%02d"
15911 (string-to-number (match-string 1 extra))
15912 (string-to-number (match-string 2 extra))))
15913 (setq extra nil)))
15914 (when extra
15915 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15916 (insert-before-markers (setq stamp (format-time-string fmt time)))
15917 (insert-before-markers (or post ""))
15918 (setq org-last-inserted-timestamp stamp)))
15920 (defun org-toggle-time-stamp-overlays ()
15921 "Toggle the use of custom time stamp formats."
15922 (interactive)
15923 (setq org-display-custom-times (not org-display-custom-times))
15924 (unless org-display-custom-times
15925 (let ((p (point-min)) (bmp (buffer-modified-p)))
15926 (while (setq p (next-single-property-change p 'display))
15927 (if (and (get-text-property p 'display)
15928 (eq (get-text-property p 'face) 'org-date))
15929 (remove-text-properties
15930 p (setq p (next-single-property-change p 'display))
15931 '(display t))))
15932 (set-buffer-modified-p bmp)))
15933 (if (featurep 'xemacs)
15934 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15935 (org-restart-font-lock)
15936 (setq org-table-may-need-update t)
15937 (if org-display-custom-times
15938 (message "Time stamps are overlaid with custom format")
15939 (message "Time stamp overlays removed")))
15941 (defun org-display-custom-time (beg end)
15942 "Overlay modified time stamp format over timestamp between BEG and END."
15943 (let* ((ts (buffer-substring beg end))
15944 t1 w1 with-hm tf time str w2 (off 0))
15945 (save-match-data
15946 (setq t1 (org-parse-time-string ts t))
15947 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15948 (setq off (- (match-end 0) (match-beginning 0)))))
15949 (setq end (- end off))
15950 (setq w1 (- end beg)
15951 with-hm (and (nth 1 t1) (nth 2 t1))
15952 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15953 time (org-fix-decoded-time t1)
15954 str (org-add-props
15955 (format-time-string
15956 (substring tf 1 -1) (apply 'encode-time time))
15957 nil 'mouse-face 'highlight)
15958 w2 (length str))
15959 (if (not (= w2 w1))
15960 (add-text-properties (1+ beg) (+ 2 beg)
15961 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15962 (if (featurep 'xemacs)
15963 (progn
15964 (put-text-property beg end 'invisible t)
15965 (put-text-property beg end 'end-glyph (make-glyph str)))
15966 (put-text-property beg end 'display str))))
15968 (defun org-translate-time (string)
15969 "Translate all timestamps in STRING to custom format.
15970 But do this only if the variable `org-display-custom-times' is set."
15971 (when org-display-custom-times
15972 (save-match-data
15973 (let* ((start 0)
15974 (re org-ts-regexp-both)
15975 t1 with-hm inactive tf time str beg end)
15976 (while (setq start (string-match re string start))
15977 (setq beg (match-beginning 0)
15978 end (match-end 0)
15979 t1 (save-match-data
15980 (org-parse-time-string (substring string beg end) t))
15981 with-hm (and (nth 1 t1) (nth 2 t1))
15982 inactive (equal (substring string beg (1+ beg)) "[")
15983 tf (funcall (if with-hm 'cdr 'car)
15984 org-time-stamp-custom-formats)
15985 time (org-fix-decoded-time t1)
15986 str (format-time-string
15987 (concat
15988 (if inactive "[" "<") (substring tf 1 -1)
15989 (if inactive "]" ">"))
15990 (apply 'encode-time time))
15991 string (replace-match str t t string)
15992 start (+ start (length str)))))))
15993 string)
15995 (defun org-fix-decoded-time (time)
15996 "Set 0 instead of nil for the first 6 elements of time.
15997 Don't touch the rest."
15998 (let ((n 0))
15999 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16001 (defun org-days-to-time (timestamp-string)
16002 "Difference between TIMESTAMP-STRING and now in days."
16003 (- (time-to-days (org-time-string-to-time timestamp-string))
16004 (time-to-days (current-time))))
16006 (defun org-deadline-close (timestamp-string &optional ndays)
16007 "Is the time in TIMESTAMP-STRING close to the current date?"
16008 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16009 (and (< (org-days-to-time timestamp-string) ndays)
16010 (not (org-entry-is-done-p))))
16012 (defun org-get-wdays (ts)
16013 "Get the deadline lead time appropriate for timestring TS."
16014 (cond
16015 ((<= org-deadline-warning-days 0)
16016 ;; 0 or negative, enforce this value no matter what
16017 (- org-deadline-warning-days))
16018 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16019 ;; lead time is specified.
16020 (floor (* (string-to-number (match-string 1 ts))
16021 (cdr (assoc (match-string 2 ts)
16022 '(("d" . 1) ("w" . 7)
16023 ("m" . 30.4) ("y" . 365.25)))))))
16024 ;; go for the default.
16025 (t org-deadline-warning-days)))
16027 (defun org-calendar-select-mouse (ev)
16028 "Return to `org-read-date' with the date currently selected.
16029 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16030 (interactive "e")
16031 (mouse-set-point ev)
16032 (when (calendar-cursor-to-date)
16033 (let* ((date (calendar-cursor-to-date))
16034 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16035 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16036 (if (active-minibuffer-window) (exit-minibuffer))))
16038 (defun org-check-deadlines (ndays)
16039 "Check if there are any deadlines due or past due.
16040 A deadline is considered due if it happens within `org-deadline-warning-days'
16041 days from today's date. If the deadline appears in an entry marked DONE,
16042 it is not shown. The prefix arg NDAYS can be used to test that many
16043 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16044 (interactive "P")
16045 (let* ((org-warn-days
16046 (cond
16047 ((equal ndays '(4)) 100000)
16048 (ndays (prefix-numeric-value ndays))
16049 (t (abs org-deadline-warning-days))))
16050 (case-fold-search nil)
16051 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16052 (callback
16053 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16055 (message "%d deadlines past-due or due within %d days"
16056 (org-occur regexp nil callback)
16057 org-warn-days)))
16059 (defsubst org-re-timestamp (type)
16060 "Return a regexp for timestamp TYPE.
16061 Allowed values for TYPE are:
16063 all: all timestamps
16064 active: only active timestamps (<...>)
16065 inactive: only inactive timestamps ([...])
16066 scheduled: only scheduled timestamps
16067 deadline: only deadline timestamps
16069 When TYPE is nil, fall back on returning a regexp that matches
16070 both scheduled and deadline timestamps."
16071 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16072 ((eq type 'active) org-ts-regexp)
16073 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16074 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16075 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16076 ((eq type 'scheduled-or-deadline)
16077 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16079 (defun org-check-before-date (date)
16080 "Check if there are deadlines or scheduled entries before DATE."
16081 (interactive (list (org-read-date)))
16082 (let ((case-fold-search nil)
16083 (regexp (org-re-timestamp org-ts-type))
16084 (callback
16085 (lambda () (time-less-p
16086 (org-time-string-to-time (match-string 1))
16087 (org-time-string-to-time date)))))
16088 (message "%d entries before %s"
16089 (org-occur regexp nil callback) date)))
16091 (defun org-check-after-date (date)
16092 "Check if there are deadlines or scheduled entries after DATE."
16093 (interactive (list (org-read-date)))
16094 (let ((case-fold-search nil)
16095 (regexp (org-re-timestamp org-ts-type))
16096 (callback
16097 (lambda () (not
16098 (time-less-p
16099 (org-time-string-to-time (match-string 1))
16100 (org-time-string-to-time date))))))
16101 (message "%d entries after %s"
16102 (org-occur regexp nil callback) date)))
16104 (defun org-check-dates-range (start-date end-date)
16105 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16106 (interactive (list (org-read-date nil nil nil "Range starts")
16107 (org-read-date nil nil nil "Range end")))
16108 (let ((case-fold-search nil)
16109 (regexp (org-re-timestamp org-ts-type))
16110 (callback
16111 (lambda ()
16112 (let ((match (match-string 1)))
16113 (and
16114 (not (time-less-p
16115 (org-time-string-to-time match)
16116 (org-time-string-to-time start-date)))
16117 (time-less-p
16118 (org-time-string-to-time match)
16119 (org-time-string-to-time end-date)))))))
16120 (message "%d entries between %s and %s"
16121 (org-occur regexp nil callback) start-date end-date)))
16123 (defun org-evaluate-time-range (&optional to-buffer)
16124 "Evaluate a time range by computing the difference between start and end.
16125 Normally the result is just printed in the echo area, but with prefix arg
16126 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16127 If the time range is actually in a table, the result is inserted into the
16128 next column.
16129 For time difference computation, a year is assumed to be exactly 365
16130 days in order to avoid rounding problems."
16131 (interactive "P")
16133 (org-clock-update-time-maybe)
16134 (save-excursion
16135 (unless (org-at-date-range-p t)
16136 (goto-char (point-at-bol))
16137 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16138 (if (not (org-at-date-range-p t))
16139 (error "Not at a time-stamp range, and none found in current line")))
16140 (let* ((ts1 (match-string 1))
16141 (ts2 (match-string 2))
16142 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16143 (match-end (match-end 0))
16144 (time1 (org-time-string-to-time ts1))
16145 (time2 (org-time-string-to-time ts2))
16146 (t1 (org-float-time time1))
16147 (t2 (org-float-time time2))
16148 (diff (abs (- t2 t1)))
16149 (negative (< (- t2 t1) 0))
16150 ;; (ys (floor (* 365 24 60 60)))
16151 (ds (* 24 60 60))
16152 (hs (* 60 60))
16153 (fy "%dy %dd %02d:%02d")
16154 (fy1 "%dy %dd")
16155 (fd "%dd %02d:%02d")
16156 (fd1 "%dd")
16157 (fh "%02d:%02d")
16158 y d h m align)
16159 (if havetime
16160 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16162 d (floor (/ diff ds)) diff (mod diff ds)
16163 h (floor (/ diff hs)) diff (mod diff hs)
16164 m (floor (/ diff 60)))
16165 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16167 d (floor (+ (/ diff ds) 0.5))
16168 h 0 m 0))
16169 (if (not to-buffer)
16170 (message "%s" (org-make-tdiff-string y d h m))
16171 (if (org-at-table-p)
16172 (progn
16173 (goto-char match-end)
16174 (setq align t)
16175 (and (looking-at " *|") (goto-char (match-end 0))))
16176 (goto-char match-end))
16177 (if (looking-at
16178 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16179 (replace-match ""))
16180 (if negative (insert " -"))
16181 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16182 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16183 (insert " " (format fh h m))))
16184 (if align (org-table-align))
16185 (message "Time difference inserted")))))
16187 (defun org-make-tdiff-string (y d h m)
16188 (let ((fmt "")
16189 (l nil))
16190 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16191 l (push y l)))
16192 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16193 l (push d l)))
16194 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16195 l (push h l)))
16196 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16197 l (push m l)))
16198 (apply 'format fmt (nreverse l))))
16200 (defun org-time-string-to-time (s &optional buffer pos)
16201 (condition-case errdata
16202 (apply 'encode-time (org-parse-time-string s))
16203 (error (error "Bad timestamp `%s'%s\nError was: %s"
16204 s (if (not (and buffer pos))
16206 (format " at %d in buffer `%s'" pos buffer))
16207 (cdr errdata)))))
16209 (defun org-time-string-to-seconds (s)
16210 (org-float-time (org-time-string-to-time s)))
16212 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16213 "Convert a time stamp to an absolute day number.
16214 If there is a specifier for a cyclic time stamp, get the closest date to
16215 DAYNR.
16216 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16217 The variable date is bound by the calendar when this is called."
16218 (cond
16219 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16220 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16221 daynr
16222 (+ daynr 1000)))
16223 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16224 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16225 (time-to-days (current-time))) (match-string 0 s)
16226 prefer show-all))
16227 (t (time-to-days
16228 (condition-case errdata
16229 (apply 'encode-time (org-parse-time-string s))
16230 (error (error "Bad timestamp `%s'%s\nError was: %s"
16231 s (if (not (and buffer pos))
16233 (format " at %d in buffer `%s'" pos buffer))
16234 (cdr errdata))))))))
16236 (defun org-days-to-iso-week (days)
16237 "Return the iso week number."
16238 (require 'cal-iso)
16239 (car (calendar-iso-from-absolute days)))
16241 (defun org-small-year-to-year (year)
16242 "Convert 2-digit years into 4-digit years.
16243 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16244 The year 2000 cannot be abbreviated. Any year larger than 99
16245 is returned unchanged."
16246 (if (< year 38)
16247 (setq year (+ 2000 year))
16248 (if (< year 100)
16249 (setq year (+ 1900 year))))
16250 year)
16252 (defun org-time-from-absolute (d)
16253 "Return the time corresponding to date D.
16254 D may be an absolute day number, or a calendar-type list (month day year)."
16255 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16256 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16258 (defun org-calendar-holiday ()
16259 "List of holidays, for Diary display in Org-mode."
16260 (require 'holidays)
16261 (let ((hl (funcall
16262 (if (fboundp 'calendar-check-holidays)
16263 'calendar-check-holidays 'check-calendar-holidays) date)))
16264 (if hl (mapconcat 'identity hl "; "))))
16266 (defun org-diary-sexp-entry (sexp entry date)
16267 "Process a SEXP diary ENTRY for DATE."
16268 (require 'diary-lib)
16269 (let ((result (if calendar-debug-sexp
16270 (let ((stack-trace-on-error t))
16271 (eval (car (read-from-string sexp))))
16272 (condition-case nil
16273 (eval (car (read-from-string sexp)))
16274 (error
16275 (beep)
16276 (message "Bad sexp at line %d in %s: %s"
16277 (org-current-line)
16278 (buffer-file-name) sexp)
16279 (sleep-for 2))))))
16280 (cond ((stringp result) (split-string result "; "))
16281 ((and (consp result)
16282 (not (consp (cdr result)))
16283 (stringp (cdr result))) (cdr result))
16284 ((and (consp result)
16285 (stringp (car result))) result)
16286 (result entry))))
16288 (defun org-diary-to-ical-string (frombuf)
16289 "Get iCalendar entries from diary entries in buffer FROMBUF.
16290 This uses the icalendar.el library."
16291 (let* ((tmpdir (if (featurep 'xemacs)
16292 (temp-directory)
16293 temporary-file-directory))
16294 (tmpfile (make-temp-name
16295 (expand-file-name "orgics" tmpdir)))
16296 buf rtn b e)
16297 (with-current-buffer frombuf
16298 (icalendar-export-region (point-min) (point-max) tmpfile)
16299 (setq buf (find-buffer-visiting tmpfile))
16300 (set-buffer buf)
16301 (goto-char (point-min))
16302 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16303 (setq b (match-beginning 0)))
16304 (goto-char (point-max))
16305 (if (re-search-backward "^END:VEVENT" nil t)
16306 (setq e (match-end 0)))
16307 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16308 (kill-buffer buf)
16309 (delete-file tmpfile)
16310 rtn))
16312 (defun org-closest-date (start current change prefer show-all)
16313 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16314 When PREFER is `past', return a date that is either CURRENT or past.
16315 When PREFER is `future', return a date that is either CURRENT or future.
16316 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16317 ;; Make the proper lists from the dates
16318 (catch 'exit
16319 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16320 dn dw sday cday n1 n2 n0
16321 d m y y1 y2 date1 date2 nmonths nm ny m2)
16323 (setq start (org-date-to-gregorian start)
16324 current (org-date-to-gregorian
16325 (if show-all
16326 current
16327 (time-to-days (current-time))))
16328 sday (calendar-absolute-from-gregorian start)
16329 cday (calendar-absolute-from-gregorian current))
16331 (if (<= cday sday) (throw 'exit sday))
16333 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16334 (setq dn (string-to-number (match-string 1 change))
16335 dw (cdr (assoc (match-string 2 change) a1)))
16336 (error "Invalid change specifier: %s" change))
16337 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16338 (cond
16339 ((eq dw 'day)
16340 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16341 n2 (+ n1 dn)))
16342 ((eq dw 'year)
16343 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16344 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16345 (setq date1 (list m d y1)
16346 n1 (calendar-absolute-from-gregorian date1)
16347 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16348 n2 (calendar-absolute-from-gregorian date2)))
16349 ((eq dw 'month)
16350 ;; approx number of month between the two dates
16351 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16352 ;; How often does dn fit in there?
16353 (setq d (nth 1 start) m (car start) y (nth 2 start)
16354 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16355 m (+ m nm)
16356 ny (floor (/ m 12))
16357 y (+ y ny)
16358 m (- m (* ny 12)))
16359 (while (> m 12) (setq m (- m 12) y (1+ y)))
16360 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
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 (while (<= n2 cday)
16365 (setq n1 n2 m m2 y y2)
16366 (setq m2 (+ m dn) y2 y)
16367 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16368 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16369 ;; Make sure n1 is the earlier date
16370 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16371 (if show-all
16372 (cond
16373 ((eq prefer 'past) (if (= cday n2) n2 n1))
16374 ((eq prefer 'future) (if (= cday n1) n1 n2))
16375 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16376 (cond
16377 ((eq prefer 'past) (if (= cday n2) n2 n1))
16378 ((eq prefer 'future) (if (= cday n1) n1 n2))
16379 (t (if (= cday n1) n1 n2)))))))
16381 (defun org-date-to-gregorian (date)
16382 "Turn any specification of DATE into a Gregorian date for the calendar."
16383 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16384 ((and (listp date) (= (length date) 3)) date)
16385 ((stringp date)
16386 (setq date (org-parse-time-string date))
16387 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16388 ((listp date)
16389 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16391 (defun org-parse-time-string (s &optional nodefault)
16392 "Parse the standard Org-mode time string.
16393 This should be a lot faster than the normal `parse-time-string'.
16394 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16395 hour and minute fields will be nil if not given."
16396 (if (string-match org-ts-regexp0 s)
16397 (list 0
16398 (if (or (match-beginning 8) (not nodefault))
16399 (string-to-number (or (match-string 8 s) "0")))
16400 (if (or (match-beginning 7) (not nodefault))
16401 (string-to-number (or (match-string 7 s) "0")))
16402 (string-to-number (match-string 4 s))
16403 (string-to-number (match-string 3 s))
16404 (string-to-number (match-string 2 s))
16405 nil nil nil)
16406 (error "Not a standard Org-mode time string: %s" s)))
16408 (defun org-timestamp-up (&optional arg)
16409 "Increase the date item at the cursor by one.
16410 If the cursor is on the year, change the year. If it is on the month,
16411 the day or the time, change that.
16412 With prefix ARG, change by that many units."
16413 (interactive "p")
16414 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16416 (defun org-timestamp-down (&optional arg)
16417 "Decrease the date item at the cursor by one.
16418 If the cursor is on the year, change the year. If it is on the month,
16419 the day or the time, change that.
16420 With prefix ARG, change by that many units."
16421 (interactive "p")
16422 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16424 (defun org-timestamp-up-day (&optional arg)
16425 "Increase the date in the time stamp by one day.
16426 With prefix ARG, change that many days."
16427 (interactive "p")
16428 (if (and (not (org-at-timestamp-p t))
16429 (org-at-heading-p))
16430 (org-todo 'up)
16431 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16433 (defun org-timestamp-down-day (&optional arg)
16434 "Decrease the date in the time stamp by one day.
16435 With prefix ARG, change that many days."
16436 (interactive "p")
16437 (if (and (not (org-at-timestamp-p t))
16438 (org-at-heading-p))
16439 (org-todo 'down)
16440 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16442 (defun org-at-timestamp-p (&optional inactive-ok)
16443 "Determine if the cursor is in or at a timestamp."
16444 (interactive)
16445 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16446 (pos (point))
16447 (ans (or (looking-at tsr)
16448 (save-excursion
16449 (skip-chars-backward "^[<\n\r\t")
16450 (if (> (point) (point-min)) (backward-char 1))
16451 (and (looking-at tsr)
16452 (> (- (match-end 0) pos) -1))))))
16453 (and ans
16454 (boundp 'org-ts-what)
16455 (setq org-ts-what
16456 (cond
16457 ((= pos (match-beginning 0)) 'bracket)
16458 ;; Point is considered to be "on the bracket" whether
16459 ;; it's really on it or right after it.
16460 ((= pos (1- (match-end 0))) 'bracket)
16461 ((= pos (match-end 0)) 'after)
16462 ((org-pos-in-match-range pos 2) 'year)
16463 ((org-pos-in-match-range pos 3) 'month)
16464 ((org-pos-in-match-range pos 7) 'hour)
16465 ((org-pos-in-match-range pos 8) 'minute)
16466 ((or (org-pos-in-match-range pos 4)
16467 (org-pos-in-match-range pos 5)) 'day)
16468 ((and (> pos (or (match-end 8) (match-end 5)))
16469 (< pos (match-end 0)))
16470 (- pos (or (match-end 8) (match-end 5))))
16471 (t 'day))))
16472 ans))
16474 (defun org-toggle-timestamp-type ()
16475 "Toggle the type (<active> or [inactive]) of a time stamp."
16476 (interactive)
16477 (when (org-at-timestamp-p t)
16478 (let ((beg (match-beginning 0)) (end (match-end 0))
16479 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16480 (save-excursion
16481 (goto-char beg)
16482 (while (re-search-forward "[][<>]" end t)
16483 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16484 t t)))
16485 (message "Timestamp is now %sactive"
16486 (if (equal (char-after beg) ?<) "" "in")))))
16488 (defvar org-clock-history) ; defined in org-clock.el
16489 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16490 (defun org-timestamp-change (n &optional what updown)
16491 "Change the date in the time stamp at point.
16492 The date will be changed by N times WHAT. WHAT can be `day', `month',
16493 `year', `minute', `second'. If WHAT is not given, the cursor position
16494 in the timestamp determines what will be changed."
16495 (let ((origin (point)) origin-cat
16496 with-hm inactive
16497 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16498 org-ts-what
16499 extra rem
16500 ts time time0 fixnext clrgx)
16501 (if (not (org-at-timestamp-p t))
16502 (error "Not at a timestamp"))
16503 (if (and (not what) (eq org-ts-what 'bracket))
16504 (org-toggle-timestamp-type)
16505 ;; Point isn't on brackets. Remember the part of the time-stamp
16506 ;; the point was in. Indeed, size of time-stamps may change,
16507 ;; but point must be kept in the same category nonetheless.
16508 (setq origin-cat org-ts-what)
16509 (if (and (not what) (not (eq org-ts-what 'day))
16510 org-display-custom-times
16511 (get-text-property (point) 'display)
16512 (not (get-text-property (1- (point)) 'display)))
16513 (setq org-ts-what 'day))
16514 (setq org-ts-what (or what org-ts-what)
16515 inactive (= (char-after (match-beginning 0)) ?\[)
16516 ts (match-string 0))
16517 (replace-match "")
16518 (if (string-match
16519 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16521 (setq extra (match-string 1 ts)))
16522 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16523 (setq with-hm t))
16524 (setq time0 (org-parse-time-string ts))
16525 (when (and updown
16526 (eq org-ts-what 'minute)
16527 (not current-prefix-arg))
16528 ;; This looks like s-up and s-down. Change by one rounding step.
16529 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16530 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16531 (setcar (cdr time0) (+ (nth 1 time0)
16532 (if (> n 0) (- rem) (- dm rem))))))
16533 (setq time
16534 (encode-time (or (car time0) 0)
16535 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16536 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16537 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16538 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16539 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16540 (nthcdr 6 time0)))
16541 (when (and (member org-ts-what '(hour minute))
16542 extra
16543 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16544 (setq extra (org-modify-ts-extra
16545 extra
16546 (if (eq org-ts-what 'hour) 2 5)
16547 n dm)))
16548 (when (integerp org-ts-what)
16549 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16550 (if (eq what 'calendar)
16551 (let ((cal-date (org-get-date-from-calendar)))
16552 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16553 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16554 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16555 (setcar time0 (or (car time0) 0))
16556 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16557 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16558 (setq time (apply 'encode-time time0))))
16559 ;; Insert the new time-stamp, and ensure point stays in the same
16560 ;; category as before (i.e. not after the last position in that
16561 ;; category).
16562 (let ((pos (point)))
16563 ;; Stay before inserted string. `save-excursion' is of no use.
16564 (setq org-last-changed-timestamp
16565 (org-insert-time-stamp time with-hm inactive nil nil extra))
16566 (goto-char pos))
16567 (save-match-data
16568 (looking-at org-ts-regexp3)
16569 (goto-char (cond
16570 ;; `day' category ends before `hour' if any, or at
16571 ;; the end of the day name.
16572 ((eq origin-cat 'day)
16573 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16574 ((eq origin-cat 'hour) (min (match-end 7) origin))
16575 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16576 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16577 ;; `year' and `month' have both fixed size: point
16578 ;; couldn't have moved into another part.
16579 (t origin))))
16580 ;; Update clock if on a CLOCK line.
16581 (org-clock-update-time-maybe)
16582 ;; Maybe adjust the closest clock in `org-clock-history'
16583 (when org-clock-adjust-closest
16584 (if (not (and (org-at-clock-log-p)
16585 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16586 org-clock-history))))))
16587 (message "No clock to adjust")
16588 (cond ((save-excursion ; fix previous clock?
16589 (re-search-backward org-ts-regexp0 nil t)
16590 (org-looking-back (concat org-clock-string " \\[")))
16591 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16592 ((save-excursion ; fix next clock?
16593 (re-search-backward org-ts-regexp0 nil t)
16594 (looking-at (concat org-ts-regexp0 "\\] =>")))
16595 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16596 (save-window-excursion
16597 ;; Find closest clock to point, adjust the previous/next one in history
16598 (let* ((p (save-excursion (org-back-to-heading t)))
16599 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16600 (clfixnth
16601 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16602 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16603 (if (not clfixpos)
16604 (message "No clock to adjust")
16605 (save-excursion
16606 (org-goto-marker-or-bmk clfixpos)
16607 (org-show-subtree)
16608 (when (re-search-forward clrgx nil t)
16609 (goto-char (match-beginning 1))
16610 (let (org-clock-adjust-closest)
16611 (org-timestamp-change n org-ts-what updown))
16612 (message "Clock adjusted in %s for heading: %s"
16613 (file-name-nondirectory (buffer-file-name))
16614 (org-get-heading t t)))))))))
16615 ;; Try to recenter the calendar window, if any.
16616 (if (and org-calendar-follow-timestamp-change
16617 (get-buffer-window "*Calendar*" t)
16618 (memq org-ts-what '(day month year)))
16619 (org-recenter-calendar (time-to-days time))))))
16621 (defun org-modify-ts-extra (s pos n dm)
16622 "Change the different parts of the lead-time and repeat fields in timestamp."
16623 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16624 ng h m new rem)
16625 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16626 (cond
16627 ((or (org-pos-in-match-range pos 2)
16628 (org-pos-in-match-range pos 3))
16629 (setq m (string-to-number (match-string 3 s))
16630 h (string-to-number (match-string 2 s)))
16631 (if (org-pos-in-match-range pos 2)
16632 (setq h (+ h n))
16633 (setq n (* dm (org-no-warnings (signum n))))
16634 (when (not (= 0 (setq rem (% m dm))))
16635 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16636 (setq m (+ m n)))
16637 (if (< m 0) (setq m (+ m 60) h (1- h)))
16638 (if (> m 59) (setq m (- m 60) h (1+ h)))
16639 (setq h (min 24 (max 0 h)))
16640 (setq ng 1 new (format "-%02d:%02d" h m)))
16641 ((org-pos-in-match-range pos 6)
16642 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16643 ((org-pos-in-match-range pos 5)
16644 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16646 ((org-pos-in-match-range pos 9)
16647 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16648 ((org-pos-in-match-range pos 8)
16649 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16651 (when ng
16652 (setq s (concat
16653 (substring s 0 (match-beginning ng))
16655 (substring s (match-end ng))))))
16658 (defun org-recenter-calendar (date)
16659 "If the calendar is visible, recenter it to DATE."
16660 (let ((cwin (get-buffer-window "*Calendar*" t)))
16661 (when cwin
16662 (let ((calendar-move-hook nil))
16663 (with-selected-window cwin
16664 (calendar-goto-date (if (listp date) date
16665 (calendar-gregorian-from-absolute date))))))))
16667 (defun org-goto-calendar (&optional arg)
16668 "Go to the Emacs calendar at the current date.
16669 If there is a time stamp in the current line, go to that date.
16670 A prefix ARG can be used to force the current date."
16671 (interactive "P")
16672 (let ((tsr org-ts-regexp) diff
16673 (calendar-move-hook nil)
16674 (calendar-view-holidays-initially-flag nil)
16675 (calendar-view-diary-initially-flag nil))
16676 (if (or (org-at-timestamp-p)
16677 (save-excursion
16678 (beginning-of-line 1)
16679 (looking-at (concat ".*" tsr))))
16680 (let ((d1 (time-to-days (current-time)))
16681 (d2 (time-to-days
16682 (org-time-string-to-time (match-string 1)))))
16683 (setq diff (- d2 d1))))
16684 (calendar)
16685 (calendar-goto-today)
16686 (if (and diff (not arg)) (calendar-forward-day diff))))
16688 (defun org-get-date-from-calendar ()
16689 "Return a list (month day year) of date at point in calendar."
16690 (with-current-buffer "*Calendar*"
16691 (save-match-data
16692 (calendar-cursor-to-date))))
16694 (defun org-date-from-calendar ()
16695 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16696 If there is already a time stamp at the cursor position, update it."
16697 (interactive)
16698 (if (org-at-timestamp-p t)
16699 (org-timestamp-change 0 'calendar)
16700 (let ((cal-date (org-get-date-from-calendar)))
16701 (org-insert-time-stamp
16702 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16704 (defun org-minutes-to-hh:mm-string (m)
16705 "Compute H:MM from a number of minutes."
16706 (let ((h (/ m 60)))
16707 (setq m (- m (* 60 h)))
16708 (format org-time-clocksum-format h m)))
16710 (defun org-hh:mm-string-to-minutes (s)
16711 "Convert a string H:MM to a number of minutes.
16712 If the string is just a number, interpret it as minutes.
16713 In fact, the first hh:mm or number in the string will be taken,
16714 there can be extra stuff in the string.
16715 If no number is found, the return value is 0."
16716 (cond
16717 ((integerp s) s)
16718 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16719 (+ (* (string-to-number (match-string 1 s)) 60)
16720 (string-to-number (match-string 2 s))))
16721 ((string-match "\\([0-9]+\\)" s)
16722 (string-to-number (match-string 1 s)))
16723 (t 0)))
16725 (defcustom org-effort-durations
16726 `(("h" . 60)
16727 ("d" . ,(* 60 8))
16728 ("w" . ,(* 60 8 5))
16729 ("m" . ,(* 60 8 5 4))
16730 ("y" . ,(* 60 8 5 40)))
16731 "Conversion factor to minutes for an effort modifier.
16733 Each entry has the form (MODIFIER . MINUTES).
16735 In an effort string, a number followed by MODIFIER is multiplied
16736 by the specified number of MINUTES to obtain an effort in
16737 minutes.
16739 For example, if the value of this variable is ((\"hours\" . 60)), then an
16740 effort string \"2hours\" is equivalent to 120 minutes."
16741 :group 'org-agenda
16742 :version "24.1"
16743 :type '(alist :key-type (string :tag "Modifier")
16744 :value-type (number :tag "Minutes")))
16746 (defcustom org-image-actual-width t
16747 "Should we use the actual width of images when inlining them?
16749 When set to `t', always use the image width.
16751 When set to a number, use imagemagick (when available) to set
16752 the image's width to this value.
16754 When set to a number in a list, try to get the width from the
16755 #+ATTR.* keyword if it matches a width specification like
16756 width=\"[0-9]+\", and fall back on that number if none is found.
16758 When set to nil, try to get the width from an #+ATTR.* keyword
16759 and fall back on the original width if none is found.
16761 This requires Emacs >= 24.1, build with imagemagick support."
16762 :group 'org-appearance
16763 :version "24.3"
16764 :type '(choice
16765 (const :tag "Use the image width" t)
16766 (integer :tag "Use a number of pixels")
16767 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16768 (const :tag "Use #+ATTR* or don't resize" nil)))
16770 (defun org-duration-string-to-minutes (s &optional output-to-string)
16771 "Convert a duration string S to minutes.
16773 A bare number is interpreted as minutes, modifiers can be set by
16774 customizing `org-effort-durations' (which see).
16776 Entries containing a colon are interpreted as H:MM by
16777 `org-hh:mm-string-to-minutes'."
16778 (let ((result 0)
16779 (re (concat "\\([0-9.]+\\) *\\("
16780 (regexp-opt (mapcar 'car org-effort-durations))
16781 "\\)")))
16782 (while (string-match re s)
16783 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16784 (string-to-number (match-string 1 s))))
16785 (setq s (replace-match "" nil t s)))
16786 (setq result (floor result))
16787 (incf result (org-hh:mm-string-to-minutes s))
16788 (if output-to-string (number-to-string result) result)))
16790 ;;;; Files
16792 (defun org-save-all-org-buffers ()
16793 "Save all Org-mode buffers without user confirmation."
16794 (interactive)
16795 (message "Saving all Org-mode buffers...")
16796 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16797 (when (featurep 'org-id) (org-id-locations-save))
16798 (message "Saving all Org-mode buffers... done"))
16800 (defun org-revert-all-org-buffers ()
16801 "Revert all Org-mode buffers.
16802 Prompt for confirmation when there are unsaved changes.
16803 Be sure you know what you are doing before letting this function
16804 overwrite your changes.
16806 This function is useful in a setup where one tracks org files
16807 with a version control system, to revert on one machine after pulling
16808 changes from another. I believe the procedure must be like this:
16810 1. M-x org-save-all-org-buffers
16811 2. Pull changes from the other machine, resolve conflicts
16812 3. M-x org-revert-all-org-buffers"
16813 (interactive)
16814 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16815 (error "Abort"))
16816 (save-excursion
16817 (save-window-excursion
16818 (mapc
16819 (lambda (b)
16820 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16821 (with-current-buffer b buffer-file-name))
16822 (org-pop-to-buffer-same-window b)
16823 (revert-buffer t 'no-confirm)))
16824 (buffer-list))
16825 (when (and (featurep 'org-id) org-id-track-globally)
16826 (org-id-locations-load)))))
16828 ;;;; Agenda files
16830 ;;;###autoload
16831 (defun org-switchb (&optional arg)
16832 "Switch between Org buffers.
16833 With one prefix argument, restrict available buffers to files.
16834 With two prefix arguments, restrict available buffers to agenda files.
16836 Defaults to `iswitchb' for buffer name completion.
16837 Set `org-completion-use-ido' to make it use ido instead."
16838 (interactive "P")
16839 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16840 ((equal arg '(16)) (org-buffer-list 'agenda))
16841 (t (org-buffer-list))))
16842 (org-completion-use-iswitchb org-completion-use-iswitchb)
16843 (org-completion-use-ido org-completion-use-ido))
16844 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16845 (setq org-completion-use-iswitchb t))
16846 (org-pop-to-buffer-same-window
16847 (org-icompleting-read "Org buffer: "
16848 (mapcar 'list (mapcar 'buffer-name blist))
16849 nil t))))
16851 ;;; Define some older names previously used for this functionality
16852 ;;;###autoload
16853 (defalias 'org-ido-switchb 'org-switchb)
16854 ;;;###autoload
16855 (defalias 'org-iswitchb 'org-switchb)
16857 (defun org-buffer-list (&optional predicate exclude-tmp)
16858 "Return a list of Org buffers.
16859 PREDICATE can be `export', `files' or `agenda'.
16861 export restrict the list to Export buffers.
16862 files restrict the list to buffers visiting Org files.
16863 agenda restrict the list to buffers visiting agenda files.
16865 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16866 (let* ((bfn nil)
16867 (agenda-files (and (eq predicate 'agenda)
16868 (mapcar 'file-truename (org-agenda-files t))))
16869 (filter
16870 (cond
16871 ((eq predicate 'files)
16872 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16873 ((eq predicate 'export)
16874 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16875 ((eq predicate 'agenda)
16876 (lambda (b)
16877 (with-current-buffer b
16878 (and (derived-mode-p 'org-mode)
16879 (setq bfn (buffer-file-name b))
16880 (member (file-truename bfn) agenda-files)))))
16881 (t (lambda (b) (with-current-buffer b
16882 (or (derived-mode-p 'org-mode)
16883 (string-match "\*Org .*Export"
16884 (buffer-name b)))))))))
16885 (delq nil
16886 (mapcar
16887 (lambda(b)
16888 (if (and (funcall filter b)
16889 (or (not exclude-tmp)
16890 (not (string-match "tmp" (buffer-name b)))))
16892 nil))
16893 (buffer-list)))))
16895 (defun org-agenda-files (&optional unrestricted archives)
16896 "Get the list of agenda files.
16897 Optional UNRESTRICTED means return the full list even if a restriction
16898 is currently in place.
16899 When ARCHIVES is t, include all archive files that are really being
16900 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16901 `org-agenda-archives-mode' is t."
16902 (let ((files
16903 (cond
16904 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16905 ((stringp org-agenda-files) (org-read-agenda-file-list))
16906 ((listp org-agenda-files) org-agenda-files)
16907 (t (error "Invalid value of `org-agenda-files'")))))
16908 (setq files (apply 'append
16909 (mapcar (lambda (f)
16910 (if (file-directory-p f)
16911 (directory-files
16912 f t org-agenda-file-regexp)
16913 (list f)))
16914 files)))
16915 (when org-agenda-skip-unavailable-files
16916 (setq files (delq nil
16917 (mapcar (function
16918 (lambda (file)
16919 (and (file-readable-p file) file)))
16920 files))))
16921 (when (or (eq archives t)
16922 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16923 (setq files (org-add-archive-files files)))
16924 files))
16926 (defun org-agenda-file-p (&optional file)
16927 "Return non-nil, if FILE is an agenda file.
16928 If FILE is omitted, use the file associated with the current
16929 buffer."
16930 (member (or file (buffer-file-name))
16931 (org-agenda-files t)))
16933 (defun org-edit-agenda-file-list ()
16934 "Edit the list of agenda files.
16935 Depending on setup, this either uses customize to edit the variable
16936 `org-agenda-files', or it visits the file that is holding the list. In the
16937 latter case, the buffer is set up in a way that saving it automatically kills
16938 the buffer and restores the previous window configuration."
16939 (interactive)
16940 (if (stringp org-agenda-files)
16941 (let ((cw (current-window-configuration)))
16942 (find-file org-agenda-files)
16943 (org-set-local 'org-window-configuration cw)
16944 (org-add-hook 'after-save-hook
16945 (lambda ()
16946 (set-window-configuration
16947 (prog1 org-window-configuration
16948 (kill-buffer (current-buffer))))
16949 (org-install-agenda-files-menu)
16950 (message "New agenda file list installed"))
16951 nil 'local)
16952 (message "%s" (substitute-command-keys
16953 "Edit list and finish with \\[save-buffer]")))
16954 (customize-variable 'org-agenda-files)))
16956 (defun org-store-new-agenda-file-list (list)
16957 "Set new value for the agenda file list and save it correctly."
16958 (if (stringp org-agenda-files)
16959 (let ((fe (org-read-agenda-file-list t)) b u)
16960 (while (setq b (find-buffer-visiting org-agenda-files))
16961 (kill-buffer b))
16962 (with-temp-file org-agenda-files
16963 (insert
16964 (mapconcat
16965 (lambda (f) ;; Keep un-expanded entries.
16966 (if (setq u (assoc f fe))
16967 (cdr u)
16969 list "\n")
16970 "\n")))
16971 (let ((org-mode-hook nil) (org-inhibit-startup t)
16972 (org-insert-mode-line-in-empty-file nil))
16973 (setq org-agenda-files list)
16974 (customize-save-variable 'org-agenda-files org-agenda-files))))
16976 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16977 "Read the list of agenda files from a file.
16978 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16979 filenames, used by `org-store-new-agenda-file-list' to write back
16980 un-expanded file names."
16981 (when (file-directory-p org-agenda-files)
16982 (error "`org-agenda-files' cannot be a single directory"))
16983 (when (stringp org-agenda-files)
16984 (with-temp-buffer
16985 (insert-file-contents org-agenda-files)
16986 (mapcar
16987 (lambda (f)
16988 (let ((e (expand-file-name (substitute-in-file-name f)
16989 org-directory)))
16990 (if pair-with-expansion
16991 (cons e f)
16992 e)))
16993 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16995 ;;;###autoload
16996 (defun org-cycle-agenda-files ()
16997 "Cycle through the files in `org-agenda-files'.
16998 If the current buffer visits an agenda file, find the next one in the list.
16999 If the current buffer does not, find the first agenda file."
17000 (interactive)
17001 (let* ((fs (org-agenda-files t))
17002 (files (append fs (list (car fs))))
17003 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17004 file)
17005 (unless files (error "No agenda files"))
17006 (catch 'exit
17007 (while (setq file (pop files))
17008 (if (equal (file-truename file) tcf)
17009 (when (car files)
17010 (find-file (car files))
17011 (throw 'exit t))))
17012 (find-file (car fs)))
17013 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17015 (defun org-agenda-file-to-front (&optional to-end)
17016 "Move/add the current file to the top of the agenda file list.
17017 If the file is not present in the list, it is added to the front. If it is
17018 present, it is moved there. With optional argument TO-END, add/move to the
17019 end of the list."
17020 (interactive "P")
17021 (let ((org-agenda-skip-unavailable-files nil)
17022 (file-alist (mapcar (lambda (x)
17023 (cons (file-truename x) x))
17024 (org-agenda-files t)))
17025 (ctf (file-truename buffer-file-name))
17026 x had)
17027 (setq x (assoc ctf file-alist) had x)
17029 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17030 (if to-end
17031 (setq file-alist (append (delq x file-alist) (list x)))
17032 (setq file-alist (cons x (delq x file-alist))))
17033 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17034 (org-install-agenda-files-menu)
17035 (message "File %s to %s of agenda file list"
17036 (if had "moved" "added") (if to-end "end" "front"))))
17038 (defun org-remove-file (&optional file)
17039 "Remove current file from the list of files in variable `org-agenda-files'.
17040 These are the files which are being checked for agenda entries.
17041 Optional argument FILE means use this file instead of the current."
17042 (interactive)
17043 (let* ((org-agenda-skip-unavailable-files nil)
17044 (file (or file buffer-file-name))
17045 (true-file (file-truename file))
17046 (afile (abbreviate-file-name file))
17047 (files (delq nil (mapcar
17048 (lambda (x)
17049 (if (equal true-file
17050 (file-truename x))
17051 nil x))
17052 (org-agenda-files t)))))
17053 (if (not (= (length files) (length (org-agenda-files t))))
17054 (progn
17055 (org-store-new-agenda-file-list files)
17056 (org-install-agenda-files-menu)
17057 (message "Removed file: %s" afile))
17058 (message "File was not in list: %s (not removed)" afile))))
17060 (defun org-file-menu-entry (file)
17061 (vector file (list 'find-file file) t))
17063 (defun org-check-agenda-file (file)
17064 "Make sure FILE exists. If not, ask user what to do."
17065 (when (not (file-exists-p file))
17066 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17067 (abbreviate-file-name file))
17068 (let ((r (downcase (read-char-exclusive))))
17069 (cond
17070 ((equal r ?r)
17071 (org-remove-file file)
17072 (throw 'nextfile t))
17073 (t (error "Abort"))))))
17075 (defun org-get-agenda-file-buffer (file)
17076 "Get a buffer visiting FILE. If the buffer needs to be created, add
17077 it to the list of buffers which might be released later."
17078 (let ((buf (org-find-base-buffer-visiting file)))
17079 (if buf
17080 buf ; just return it
17081 ;; Make a new buffer and remember it
17082 (setq buf (find-file-noselect file))
17083 (if buf (push buf org-agenda-new-buffers))
17084 buf)))
17086 (defun org-release-buffers (blist)
17087 "Release all buffers in list, asking the user for confirmation when needed.
17088 When a buffer is unmodified, it is just killed. When modified, it is saved
17089 \(if the user agrees) and then killed."
17090 (let (buf file)
17091 (while (setq buf (pop blist))
17092 (setq file (buffer-file-name buf))
17093 (when (and (buffer-modified-p buf)
17094 file
17095 (y-or-n-p (format "Save file %s? " file)))
17096 (with-current-buffer buf (save-buffer)))
17097 (kill-buffer buf))))
17099 (defun org-agenda-prepare-buffers (files)
17100 "Create buffers for all agenda files, protect archived trees and comments."
17101 (interactive)
17102 (let ((pa '(:org-archived t))
17103 (pc '(:org-comment t))
17104 (pall '(:org-archived t :org-comment t))
17105 (inhibit-read-only t)
17106 (rea (concat ":" org-archive-tag ":"))
17107 bmp file re)
17108 (save-excursion
17109 (save-restriction
17110 (while (setq file (pop files))
17111 (catch 'nextfile
17112 (if (bufferp file)
17113 (set-buffer file)
17114 (org-check-agenda-file file)
17115 (set-buffer (org-get-agenda-file-buffer file)))
17116 (widen)
17117 (setq bmp (buffer-modified-p))
17118 (org-refresh-category-properties)
17119 (setq org-todo-keywords-for-agenda
17120 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17121 (setq org-done-keywords-for-agenda
17122 (append org-done-keywords-for-agenda org-done-keywords))
17123 (setq org-todo-keyword-alist-for-agenda
17124 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17125 (setq org-drawers-for-agenda
17126 (append org-drawers-for-agenda org-drawers))
17127 (setq org-tag-alist-for-agenda
17128 (append org-tag-alist-for-agenda org-tag-alist))
17130 (save-excursion
17131 (remove-text-properties (point-min) (point-max) pall)
17132 (when org-agenda-skip-archived-trees
17133 (goto-char (point-min))
17134 (while (re-search-forward rea nil t)
17135 (if (org-at-heading-p t)
17136 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17137 (goto-char (point-min))
17138 (setq re (format org-heading-keyword-regexp-format
17139 org-comment-string))
17140 (while (re-search-forward re nil t)
17141 (add-text-properties
17142 (match-beginning 0) (org-end-of-subtree t) pc)))
17143 (set-buffer-modified-p bmp)))))
17144 (setq org-todo-keywords-for-agenda
17145 (org-uniquify org-todo-keywords-for-agenda))
17146 (setq org-todo-keyword-alist-for-agenda
17147 (org-uniquify org-todo-keyword-alist-for-agenda)
17148 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17150 ;;;; Embedded LaTeX
17152 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17153 "Keymap for the minor `org-cdlatex-mode'.")
17155 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17156 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17157 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17158 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17159 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17161 (defvar org-cdlatex-texmathp-advice-is-done nil
17162 "Flag remembering if we have applied the advice to texmathp already.")
17164 (define-minor-mode org-cdlatex-mode
17165 "Toggle the minor `org-cdlatex-mode'.
17166 This mode supports entering LaTeX environment and math in LaTeX fragments
17167 in Org-mode.
17168 \\{org-cdlatex-mode-map}"
17169 nil " OCDL" nil
17170 (when org-cdlatex-mode
17171 (require 'cdlatex)
17172 (run-hooks 'cdlatex-mode-hook)
17173 (cdlatex-compute-tables))
17174 (unless org-cdlatex-texmathp-advice-is-done
17175 (setq org-cdlatex-texmathp-advice-is-done t)
17176 (defadvice texmathp (around org-math-always-on activate)
17177 "Always return t in org-mode buffers.
17178 This is because we want to insert math symbols without dollars even outside
17179 the LaTeX math segments. If Orgmode thinks that point is actually inside
17180 an embedded LaTeX fragment, let texmathp do its job.
17181 \\[org-cdlatex-mode-map]"
17182 (interactive)
17183 (let (p)
17184 (cond
17185 ((not (derived-mode-p 'org-mode)) ad-do-it)
17186 ((eq this-command 'cdlatex-math-symbol)
17187 (setq ad-return-value t
17188 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17190 (let ((p (org-inside-LaTeX-fragment-p)))
17191 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17192 (setq ad-return-value t
17193 texmathp-why '("Org-mode embedded math" . 0))
17194 (if p ad-do-it)))))))))
17196 (defun turn-on-org-cdlatex ()
17197 "Unconditionally turn on `org-cdlatex-mode'."
17198 (org-cdlatex-mode 1))
17200 (defun org-inside-LaTeX-fragment-p ()
17201 "Test if point is inside a LaTeX fragment.
17202 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17203 sequence appearing also before point.
17204 Even though the matchers for math are configurable, this function assumes
17205 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17206 delimiters are skipped when they have been removed by customization.
17207 The return value is nil, or a cons cell with the delimiter and the
17208 position of this delimiter.
17210 This function does a reasonably good job, but can locally be fooled by
17211 for example currency specifications. For example it will assume being in
17212 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17213 fragments that are properly closed, but during editing, we have to live
17214 with the uncertainty caused by missing closing delimiters. This function
17215 looks only before point, not after."
17216 (catch 'exit
17217 (let ((pos (point))
17218 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17219 (lim (progn
17220 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17221 (point)))
17222 dd-on str (start 0) m re)
17223 (goto-char pos)
17224 (when dodollar
17225 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17226 re (nth 1 (assoc "$" org-latex-regexps)))
17227 (while (string-match re str start)
17228 (cond
17229 ((= (match-end 0) (length str))
17230 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17231 ((= (match-end 0) (- (length str) 5))
17232 (throw 'exit nil))
17233 (t (setq start (match-end 0))))))
17234 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17235 (goto-char pos)
17236 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17237 (and (match-beginning 2) (throw 'exit nil))
17238 ;; count $$
17239 (while (re-search-backward "\\$\\$" lim t)
17240 (setq dd-on (not dd-on)))
17241 (goto-char pos)
17242 (if dd-on (cons "$$" m))))))
17244 (defun org-inside-latex-macro-p ()
17245 "Is point inside a LaTeX macro or its arguments?"
17246 (save-match-data
17247 (org-in-regexp
17248 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17250 (defun org-try-cdlatex-tab ()
17251 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17252 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17253 - inside a LaTeX fragment, or
17254 - after the first word in a line, where an abbreviation expansion could
17255 insert a LaTeX environment."
17256 (when org-cdlatex-mode
17257 (cond
17258 ;; Before any word on the line: No expansion possible.
17259 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17260 ;; Just after first word on the line: Expand it. Make sure it
17261 ;; cannot happen on headlines, though.
17262 ((save-excursion
17263 (skip-chars-backward "a-zA-Z0-9*")
17264 (skip-chars-backward " \t")
17265 (and (bolp) (not (org-at-heading-p))))
17266 (cdlatex-tab) t)
17267 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17269 (defun org-cdlatex-underscore-caret (&optional arg)
17270 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17271 Revert to the normal definition outside of these fragments."
17272 (interactive "P")
17273 (if (org-inside-LaTeX-fragment-p)
17274 (call-interactively 'cdlatex-sub-superscript)
17275 (let (org-cdlatex-mode)
17276 (call-interactively (key-binding (vector last-input-event))))))
17278 (defun org-cdlatex-math-modify (&optional arg)
17279 "Execute `cdlatex-math-modify' in LaTeX fragments.
17280 Revert to the normal definition outside of these fragments."
17281 (interactive "P")
17282 (if (org-inside-LaTeX-fragment-p)
17283 (call-interactively 'cdlatex-math-modify)
17284 (let (org-cdlatex-mode)
17285 (call-interactively (key-binding (vector last-input-event))))))
17287 (defvar org-latex-fragment-image-overlays nil
17288 "List of overlays carrying the images of latex fragments.")
17289 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17291 (defun org-remove-latex-fragment-image-overlays ()
17292 "Remove all overlays with LaTeX fragment images in current buffer."
17293 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17294 (setq org-latex-fragment-image-overlays nil))
17296 (defun org-preview-latex-fragment (&optional subtree)
17297 "Preview the LaTeX fragment at point, or all locally or globally.
17298 If the cursor is in a LaTeX fragment, create the image and overlay
17299 it over the source code. If there is no fragment at point, display
17300 all fragments in the current text, from one headline to the next. With
17301 prefix SUBTREE, display all fragments in the current subtree. With a
17302 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17303 the cursor is before the first headline,
17304 display all fragments in the buffer.
17305 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17306 (interactive "P")
17307 (unless buffer-file-name
17308 (error "Can't preview LaTeX fragment in a non-file buffer"))
17309 (org-remove-latex-fragment-image-overlays)
17310 (save-excursion
17311 (save-restriction
17312 (let (beg end at msg)
17313 (cond
17314 ((or (equal subtree '(16))
17315 (not (save-excursion
17316 (re-search-backward org-outline-regexp-bol nil t))))
17317 (setq beg (point-min) end (point-max)
17318 msg "Creating images for buffer...%s"))
17319 ((equal subtree '(4))
17320 (org-back-to-heading)
17321 (setq beg (point) end (org-end-of-subtree t)
17322 msg "Creating images for subtree...%s"))
17324 (if (setq at (org-inside-LaTeX-fragment-p))
17325 (goto-char (max (point-min) (- (cdr at) 2)))
17326 (org-back-to-heading))
17327 (setq beg (point) end (progn (outline-next-heading) (point))
17328 msg (if at "Creating image...%s"
17329 "Creating images for entry...%s"))))
17330 (message msg "")
17331 (narrow-to-region beg end)
17332 (goto-char beg)
17333 (org-format-latex
17334 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17335 (file-name-nondirectory
17336 buffer-file-name)))
17337 default-directory 'overlays msg at 'forbuffer
17338 org-latex-create-formula-image-program)
17339 (message msg "done. Use `C-c C-c' to remove images.")))))
17341 (defvar org-latex-regexps
17342 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17343 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17344 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17345 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17346 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17347 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17348 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17349 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17350 "Regular expressions for matching embedded LaTeX.")
17352 (defvar org-export-have-math nil) ;; dynamic scoping
17353 (defun org-format-latex (prefix &optional dir overlays msg at
17354 forbuffer processing-type)
17355 "Replace LaTeX fragments with links to an image, and produce images.
17356 Some of the options can be changed using the variable
17357 `org-format-latex-options'."
17358 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17359 (let* ((prefixnodir (file-name-nondirectory prefix))
17360 (absprefix (expand-file-name prefix dir))
17361 (todir (file-name-directory absprefix))
17362 (opt org-format-latex-options)
17363 (matchers (plist-get opt :matchers))
17364 (re-list org-latex-regexps)
17365 (org-format-latex-header-extra
17366 (plist-get (org-infile-export-plist) :latex-header-extra))
17367 (cnt 0) txt hash link beg end re e checkdir
17368 executables-checked string
17369 m n block-type block linkfile movefile ov)
17370 ;; Check the different regular expressions
17371 (while (setq e (pop re-list))
17372 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17373 block (if block-type "\n\n" ""))
17374 (when (member m matchers)
17375 (goto-char (point-min))
17376 (while (re-search-forward re nil t)
17377 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17378 (not (get-text-property (match-beginning n)
17379 'org-protected))
17380 (or (not overlays)
17381 (not (eq (get-char-property (match-beginning n)
17382 'org-overlay-type)
17383 'org-latex-overlay))))
17384 (setq org-export-have-math t)
17385 (cond
17386 ((eq processing-type 'verbatim)
17387 ;; Leave the text verbatim, just protect it
17388 (add-text-properties (match-beginning n) (match-end n)
17389 '(org-protected t)))
17390 ((eq processing-type 'mathjax)
17391 ;; Prepare for MathJax processing
17392 (setq string (match-string n))
17393 (if (member m '("$" "$1"))
17394 (save-excursion
17395 (delete-region (match-beginning n) (match-end n))
17396 (goto-char (match-beginning n))
17397 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17398 "\\)")
17399 '(org-protected t))))
17400 (add-text-properties (match-beginning n) (match-end n)
17401 '(org-protected t))))
17402 ((or (eq processing-type 'dvipng)
17403 (eq processing-type 'imagemagick))
17404 ;; Process to an image
17405 (setq txt (match-string n)
17406 beg (match-beginning n) end (match-end n)
17407 cnt (1+ cnt))
17408 (let (print-length print-level) ; make sure full list is printed
17409 (setq hash (sha1 (prin1-to-string
17410 (list org-format-latex-header
17411 org-format-latex-header-extra
17412 org-export-latex-default-packages-alist
17413 org-export-latex-packages-alist
17414 org-format-latex-options
17415 forbuffer txt)))
17416 linkfile (format "%s_%s.png" prefix hash)
17417 movefile (format "%s_%s.png" absprefix hash)))
17418 (setq link (concat block "[[file:" linkfile "]]" block))
17419 (if msg (message msg cnt))
17420 (goto-char beg)
17421 (unless checkdir ; make sure the directory exists
17422 (setq checkdir t)
17423 (or (file-directory-p todir) (make-directory todir t)))
17424 (cond
17425 ((eq processing-type 'dvipng)
17426 (unless executables-checked
17427 (org-check-external-command
17428 "latex" "needed to convert LaTeX fragments to images")
17429 (org-check-external-command
17430 "dvipng" "needed to convert LaTeX fragments to images")
17431 (setq executables-checked t))
17432 (unless (file-exists-p movefile)
17433 (org-create-formula-image-with-dvipng
17434 txt movefile opt forbuffer)))
17435 ((eq processing-type 'imagemagick)
17436 (unless executables-checked
17437 (org-check-external-command
17438 "convert" "you need to install imagemagick")
17439 (setq executables-checked t))
17440 (unless (file-exists-p movefile)
17441 (org-create-formula-image-with-imagemagick
17442 txt movefile opt forbuffer))))
17443 (if overlays
17444 (progn
17445 (mapc (lambda (o)
17446 (if (eq (overlay-get o 'org-overlay-type)
17447 'org-latex-overlay)
17448 (delete-overlay o)))
17449 (overlays-in beg end))
17450 (setq ov (make-overlay beg end))
17451 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17452 (if (featurep 'xemacs)
17453 (progn
17454 (overlay-put ov 'invisible t)
17455 (overlay-put
17456 ov 'end-glyph
17457 (make-glyph (vector 'png :file movefile))))
17458 (overlay-put
17459 ov 'display
17460 (list 'image :type 'png :file movefile :ascent 'center)))
17461 (push ov org-latex-fragment-image-overlays)
17462 (goto-char end))
17463 (delete-region beg end)
17464 (insert (org-add-props link
17465 (list 'org-latex-src
17466 (replace-regexp-in-string
17467 "\"" "" txt)
17468 'org-latex-src-embed-type
17469 (if block-type 'paragraph 'character))))))
17470 ((eq processing-type 'mathml)
17471 ;; Process to MathML
17472 (unless executables-checked
17473 (unless (save-match-data (org-format-latex-mathml-available-p))
17474 (error "LaTeX to MathML converter not configured"))
17475 (setq executables-checked t))
17476 (setq txt (match-string n)
17477 beg (match-beginning n) end (match-end n)
17478 cnt (1+ cnt))
17479 (if msg (message msg cnt))
17480 (goto-char beg)
17481 (delete-region beg end)
17482 (insert (org-format-latex-as-mathml
17483 txt block-type prefix dir)))
17485 (error "Unknown conversion type %s for latex fragments"
17486 processing-type)))))))))
17488 (defun org-create-math-formula (latex-frag &optional mathml-file)
17489 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17490 Use `org-latex-to-mathml-convert-command'. If the conversion is
17491 sucessful, return the portion between \"<math...> </math>\"
17492 elements otherwise return nil. When MATHML-FILE is specified,
17493 write the results in to that file. When invoked as an
17494 interactive command, prompt for LATEX-FRAG, with initial value
17495 set to the current active region and echo the results for user
17496 inspection."
17497 (interactive (list (let ((frag (when (org-region-active-p)
17498 (buffer-substring-no-properties
17499 (region-beginning) (region-end)))))
17500 (read-string "LaTeX Fragment: " frag nil frag))))
17501 (unless latex-frag (error "Invalid latex-frag"))
17502 (let* ((tmp-in-file (file-relative-name
17503 (make-temp-name (expand-file-name "ltxmathml-in"))))
17504 (ignore (write-region latex-frag nil tmp-in-file))
17505 (tmp-out-file (file-relative-name
17506 (make-temp-name (expand-file-name "ltxmathml-out"))))
17507 (cmd (format-spec
17508 org-latex-to-mathml-convert-command
17509 `((?j . ,(shell-quote-argument
17510 (expand-file-name org-latex-to-mathml-jar-file)))
17511 (?I . ,(shell-quote-argument tmp-in-file))
17512 (?o . ,(shell-quote-argument tmp-out-file)))))
17513 mathml shell-command-output)
17514 (when (org-called-interactively-p 'any)
17515 (unless (org-format-latex-mathml-available-p)
17516 (error "LaTeX to MathML converter not configured")))
17517 (message "Running %s" cmd)
17518 (setq shell-command-output (shell-command-to-string cmd))
17519 (setq mathml
17520 (when (file-readable-p tmp-out-file)
17521 (with-current-buffer (find-file-noselect tmp-out-file t)
17522 (goto-char (point-min))
17523 (when (re-search-forward
17524 (concat
17525 (regexp-quote
17526 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17527 "\\(.\\|\n\\)*"
17528 (regexp-quote "</math>")) nil t)
17529 (prog1 (match-string 0) (kill-buffer))))))
17530 (cond
17531 (mathml
17532 (setq mathml
17533 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17534 (when mathml-file
17535 (write-region mathml nil mathml-file))
17536 (when (org-called-interactively-p 'any)
17537 (message mathml)))
17538 ((message "LaTeX to MathML conversion failed")
17539 (message shell-command-output)))
17540 (delete-file tmp-in-file)
17541 (when (file-exists-p tmp-out-file)
17542 (delete-file tmp-out-file))
17543 mathml))
17545 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17546 prefix &optional dir)
17547 "Use `org-create-math-formula' but check local cache first."
17548 (let* ((absprefix (expand-file-name prefix dir))
17549 (print-length nil) (print-level nil)
17550 (formula-id (concat
17551 "formula-"
17552 (sha1
17553 (prin1-to-string
17554 (list latex-frag
17555 org-latex-to-mathml-convert-command)))))
17556 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17557 (formula-cache-dir (file-name-directory formula-cache)))
17559 (unless (file-directory-p formula-cache-dir)
17560 (make-directory formula-cache-dir t))
17562 (unless (file-exists-p formula-cache)
17563 (org-create-math-formula latex-frag formula-cache))
17565 (if (file-exists-p formula-cache)
17566 ;; Successful conversion. Return the link to MathML file.
17567 (org-add-props
17568 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17569 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17570 'org-latex-src-embed-type (if latex-frag-type
17571 'paragraph 'character)))
17572 ;; Failed conversion. Return the LaTeX fragment verbatim
17573 (add-text-properties
17574 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17575 latex-frag)))
17577 ;; This function borrows from Ganesh Swami's latex2png.el
17578 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17579 "This calls dvipng."
17580 (require 'org-latex)
17581 (let* ((tmpdir (if (featurep 'xemacs)
17582 (temp-directory)
17583 temporary-file-directory))
17584 (texfilebase (make-temp-name
17585 (expand-file-name "orgtex" tmpdir)))
17586 (texfile (concat texfilebase ".tex"))
17587 (dvifile (concat texfilebase ".dvi"))
17588 (pngfile (concat texfilebase ".png"))
17589 (fnh (if (featurep 'xemacs)
17590 (font-height (face-font 'default))
17591 (face-attribute 'default :height nil)))
17592 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17593 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17594 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17595 "Black"))
17596 (bg (or (plist-get options (if buffer :background :html-background))
17597 "Transparent")))
17598 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17599 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17600 (with-temp-file texfile
17601 (insert (org-splice-latex-header
17602 org-format-latex-header
17603 org-export-latex-default-packages-alist
17604 org-export-latex-packages-alist t
17605 org-format-latex-header-extra))
17606 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17607 (require 'org-latex)
17608 (org-export-latex-fix-inputenc))
17609 (let ((dir default-directory))
17610 (condition-case nil
17611 (progn
17612 (cd tmpdir)
17613 (call-process "latex" nil nil nil texfile))
17614 (error nil))
17615 (cd dir))
17616 (if (not (file-exists-p dvifile))
17617 (progn (message "Failed to create dvi file from %s" texfile) nil)
17618 (condition-case nil
17619 (if (featurep 'xemacs)
17620 (call-process "dvipng" nil nil nil
17621 "-fg" fg "-bg" bg
17622 "-T" "tight"
17623 "-o" pngfile
17624 dvifile)
17625 (call-process "dvipng" nil nil nil
17626 "-fg" fg "-bg" bg
17627 "-D" dpi
17628 ;;"-x" scale "-y" scale
17629 "-T" "tight"
17630 "-o" pngfile
17631 dvifile))
17632 (error nil))
17633 (if (not (file-exists-p pngfile))
17634 (if org-format-latex-signal-error
17635 (error "Failed to create png file from %s" texfile)
17636 (message "Failed to create png file from %s" texfile)
17637 nil)
17638 ;; Use the requested file name and clean up
17639 (copy-file pngfile tofile 'replace)
17640 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17641 (if (file-exists-p (concat texfilebase e))
17642 (delete-file (concat texfilebase e))))
17643 pngfile))))
17645 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17646 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17647 "This calls convert, which is included into imagemagick."
17648 (require 'org-latex)
17649 (let* ((tmpdir (if (featurep 'xemacs)
17650 (temp-directory)
17651 temporary-file-directory))
17652 (texfilebase (make-temp-name
17653 (expand-file-name "orgtex" tmpdir)))
17654 (texfile (concat texfilebase ".tex"))
17655 (pdffile (concat texfilebase ".pdf"))
17656 (pngfile (concat texfilebase ".png"))
17657 (fnh (if (featurep 'xemacs)
17658 (font-height (face-font 'default))
17659 (face-attribute 'default :height nil)))
17660 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17661 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17662 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17663 "black"))
17664 (bg (or (plist-get options (if buffer :background :html-background))
17665 "white")))
17666 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17667 (setq fg (org-latex-color-format fg)))
17668 (if (eq bg 'default) (setq bg (org-latex-color :background))
17669 (setq bg (org-latex-color-format
17670 (if (string= bg "Transparent")(setq bg "white")))))
17671 (with-temp-file texfile
17672 (insert (org-splice-latex-header
17673 org-format-latex-header
17674 org-export-latex-default-packages-alist
17675 org-export-latex-packages-alist t
17676 org-format-latex-header-extra))
17677 (insert "\n\\begin{document}\n"
17678 "\\definecolor{fg}{rgb}{" fg "}\n"
17679 "\\definecolor{bg}{rgb}{" bg "}\n"
17680 "\n\\pagecolor{bg}\n"
17681 "\n{\\color{fg}\n"
17682 string
17683 "\n}\n"
17684 "\n\\end{document}\n" )
17685 (require 'org-latex)
17686 (org-export-latex-fix-inputenc))
17687 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17688 (condition-case nil
17689 (progn
17690 (cd tmpdir)
17691 (setq cmds org-latex-to-pdf-process)
17692 (while cmds
17693 (setq latex-frags-cmds (pop cmds))
17694 (if (listp latex-frags-cmds)
17695 (setq cmds nil)
17696 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17697 (while latex-frags-cmds
17698 (setq cmd (pop latex-frags-cmds))
17699 (while (string-match "%b" cmd)
17700 (setq cmd (replace-match
17701 (save-match-data
17702 (shell-quote-argument texfile))
17703 t t cmd)))
17704 (while (string-match "%f" cmd)
17705 (setq cmd (replace-match
17706 (save-match-data
17707 (shell-quote-argument (file-name-nondirectory texfile)))
17708 t t cmd)))
17709 (while (string-match "%o" cmd)
17710 (setq cmd (replace-match
17711 (save-match-data
17712 (shell-quote-argument (file-name-directory texfile)))
17713 t t cmd)))
17714 (setq cmd (split-string cmd))
17715 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17716 (error nil))
17717 (cd dir))
17718 (if (not (file-exists-p pdffile))
17719 (progn (message "Failed to create pdf file from %s" texfile) nil)
17720 (condition-case nil
17721 (if (featurep 'xemacs)
17722 (call-process "convert" nil nil nil
17723 "-density" "96"
17724 "-trim"
17725 "-antialias"
17726 pdffile
17727 "-quality" "100"
17728 ;; "-sharpen" "0x1.0"
17729 pngfile)
17730 (call-process "convert" nil nil nil
17731 "-density" dpi
17732 "-trim"
17733 "-antialias"
17734 pdffile
17735 "-quality" "100"
17736 ; "-sharpen" "0x1.0"
17737 pngfile))
17738 (error nil))
17739 (if (not (file-exists-p pngfile))
17740 (if org-format-latex-signal-error
17741 (error "Failed to create png file from %s" texfile)
17742 (message "Failed to create png file from %s" texfile)
17743 nil)
17744 ;; Use the requested file name and clean up
17745 (copy-file pngfile tofile 'replace)
17746 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17747 (if (file-exists-p (concat texfilebase e))
17748 (delete-file (concat texfilebase e))))
17749 pngfile))))
17751 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17752 "Fill a LaTeX header template TPL.
17753 In the template, the following place holders will be recognized:
17755 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17756 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17757 [PACKAGES] \\usepackage statements for PKG
17758 [NO-PACKAGES] do not include PKG
17759 [EXTRA] the string EXTRA
17760 [NO-EXTRA] do not include EXTRA
17762 For backward compatibility, if both the positive and the negative place
17763 holder is missing, the positive one (without the \"NO-\") will be
17764 assumed to be present at the end of the template.
17765 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17766 EXTRA is a string.
17767 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17768 (let (rpl (end ""))
17769 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17770 (setq rpl (if (or (match-end 1) (not def-pkg))
17771 "" (org-latex-packages-to-string def-pkg snippets-p t))
17772 tpl (replace-match rpl t t tpl))
17773 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17775 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17776 (setq rpl (if (or (match-end 1) (not pkg))
17777 "" (org-latex-packages-to-string pkg snippets-p t))
17778 tpl (replace-match rpl t t tpl))
17779 (if pkg (setq end
17780 (concat end "\n"
17781 (org-latex-packages-to-string pkg snippets-p)))))
17783 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17784 (setq rpl (if (or (match-end 1) (not extra))
17785 "" (concat extra "\n"))
17786 tpl (replace-match rpl t t tpl))
17787 (if (and extra (string-match "\\S-" extra))
17788 (setq end (concat end "\n" extra))))
17790 (if (string-match "\\S-" end)
17791 (concat tpl "\n" end)
17792 tpl)))
17794 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17795 "Turn an alist of packages into a string with the \\usepackage macros."
17796 (setq pkg (mapconcat (lambda(p)
17797 (cond
17798 ((stringp p) p)
17799 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17800 (format "%% Package %s omitted" (cadr p)))
17801 ((equal "" (car p))
17802 (format "\\usepackage{%s}" (cadr p)))
17804 (format "\\usepackage[%s]{%s}"
17805 (car p) (cadr p)))))
17807 "\n"))
17808 (if newline (concat pkg "\n") pkg))
17810 (defun org-dvipng-color (attr)
17811 "Return a RGB color specification for dvipng."
17812 (apply 'format "rgb %s %s %s"
17813 (mapcar 'org-normalize-color
17814 (if (featurep 'xemacs)
17815 (color-rgb-components
17816 (face-property 'default
17817 (cond ((eq attr :foreground) 'foreground)
17818 ((eq attr :background) 'background))))
17819 (color-values (face-attribute 'default attr nil))))))
17821 (defun org-latex-color (attr)
17822 "Return a RGB color for the LaTeX color package."
17823 (apply 'format "%s,%s,%s"
17824 (mapcar 'org-normalize-color
17825 (if (featurep 'xemacs)
17826 (color-rgb-components
17827 (face-property 'default
17828 (cond ((eq attr :foreground) 'foreground)
17829 ((eq attr :background) 'background))))
17830 (color-values (face-attribute 'default attr nil))))))
17832 (defun org-latex-color-format (color-name)
17833 "Convert COLOR-NAME to a RGB color value."
17834 (apply 'format "%s,%s,%s"
17835 (mapcar 'org-normalize-color
17836 (color-values color-name))))
17838 (defun org-normalize-color (value)
17839 "Return string to be used as color value for an RGB component."
17840 (format "%g" (/ value 65535.0)))
17842 ;; Image display
17845 (defvar org-inline-image-overlays nil)
17846 (make-variable-buffer-local 'org-inline-image-overlays)
17848 (defun org-toggle-inline-images (&optional include-linked)
17849 "Toggle the display of inline images.
17850 INCLUDE-LINKED is passed to `org-display-inline-images'."
17851 (interactive "P")
17852 (if org-inline-image-overlays
17853 (progn
17854 (org-remove-inline-images)
17855 (message "Inline image display turned off"))
17856 (org-display-inline-images include-linked)
17857 (if org-inline-image-overlays
17858 (message "%d images displayed inline"
17859 (length org-inline-image-overlays))
17860 (message "No images to display inline"))))
17862 (defun org-redisplay-inline-images ()
17863 "Refresh the display of inline images."
17864 (interactive)
17865 (if (not org-inline-image-overlays)
17866 (org-toggle-inline-images)
17867 (org-toggle-inline-images)
17868 (org-toggle-inline-images)))
17870 (defun org-display-inline-images (&optional include-linked refresh beg end)
17871 "Display inline images.
17872 Normally only links without a description part are inlined, because this
17873 is how it will work for export. When INCLUDE-LINKED is set, also links
17874 with a description part will be inlined. This can be nice for a quick
17875 look at those images, but it does not reflect what exported files will look
17876 like.
17877 When REFRESH is set, refresh existing images between BEG and END.
17878 This will create new image displays only if necessary.
17879 BEG and END default to the buffer boundaries."
17880 (interactive "P")
17881 (unless refresh
17882 (org-remove-inline-images)
17883 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17884 (save-excursion
17885 (save-restriction
17886 (widen)
17887 (setq beg (or beg (point-min)) end (or end (point-max)))
17888 (goto-char beg)
17889 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17890 (substring (org-image-file-name-regexp) 0 -2)
17891 "\\)\\]" (if include-linked "" "\\]")))
17892 old file ov img type attrwidth width)
17893 (while (re-search-forward re end t)
17894 (setq old (get-char-property-and-overlay (match-beginning 1)
17895 'org-image-overlay)
17896 file (expand-file-name
17897 (concat (or (match-string 3) "") (match-string 4))))
17898 (when (image-type-available-p 'imagemagick)
17899 (setq attrwidth (if (or (listp org-image-actual-width)
17900 (null org-image-actual-width))
17901 (save-excursion
17902 (save-match-data
17903 (move-beginning-of-line 0)
17904 (if (looking-at "#\\+ATTR.*width=\"\\([^\"]+\\)\"")
17905 (string-to-number (match-string 1))))))
17906 width (cond ((eq org-image-actual-width t) nil)
17907 ((null org-image-actual-width) attrwidth)
17908 ((numberp org-image-actual-width)
17909 org-image-actual-width)
17910 ((listp org-image-actual-width)
17911 (or attrwidth (car org-image-actual-width))))
17912 type (if width 'imagemagick)))
17913 (when (file-exists-p file)
17914 (if (and (car-safe old) refresh)
17915 (image-refresh (overlay-get (cdr old) 'display))
17916 (setq img (save-match-data (create-image file type nil :width width)))
17917 (when img
17918 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17919 (overlay-put ov 'display img)
17920 (overlay-put ov 'face 'default)
17921 (overlay-put ov 'org-image-overlay t)
17922 (overlay-put ov 'modification-hooks
17923 (list 'org-display-inline-modification-hook))
17924 (push ov org-inline-image-overlays)))))))))
17926 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17927 "Remove inline-display overlay if a corresponding region is modified."
17928 (let ((inhibit-modification-hooks t))
17929 (when (and ov after)
17930 (delete ov org-inline-image-overlays)
17931 (delete-overlay ov))))
17933 (defun org-remove-inline-images ()
17934 "Remove inline display of images."
17935 (interactive)
17936 (mapc 'delete-overlay org-inline-image-overlays)
17937 (setq org-inline-image-overlays nil))
17939 ;;;; Key bindings
17941 ;; Outline functions from `outline-mode-prefix-map'
17942 ;; that can be remapped in Org:
17943 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17944 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17945 (define-key org-mode-map [remap outline-forward-same-level]
17946 'org-forward-heading-same-level)
17947 (define-key org-mode-map [remap outline-backward-same-level]
17948 'org-backward-heading-same-level)
17949 (define-key org-mode-map [remap show-branches]
17950 'org-kill-note-or-show-branches)
17951 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17952 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17953 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17955 ;; Outline functions from `outline-mode-prefix-map' that can not
17956 ;; be remapped in Org:
17958 ;; - the column "key binding" shows whether the Outline function is still
17959 ;; available in Org mode on the same key that it has been bound to in
17960 ;; Outline mode:
17961 ;; - "overridden": key used for a different functionality in Org mode
17962 ;; - else: key still bound to the same Outline function in Org mode
17964 ;; | Outline function | key binding | Org replacement |
17965 ;; |------------------------------------+-------------+-----------------------|
17966 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17967 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17968 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17969 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17970 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17971 ;; | `show-entry' | overridden | no replacement |
17972 ;; | `show-children' | `C-c C-i' | visibility cycling |
17973 ;; | `show-branches' | `C-c C-k' | still same function |
17974 ;; | `show-subtree' | overridden | visibility cycling |
17975 ;; | `show-all' | overridden | no replacement |
17976 ;; | `hide-subtree' | overridden | visibility cycling |
17977 ;; | `hide-body' | overridden | no replacement |
17978 ;; | `hide-entry' | overridden | visibility cycling |
17979 ;; | `hide-leaves' | overridden | no replacement |
17980 ;; | `hide-sublevels' | overridden | no replacement |
17981 ;; | `hide-other' | overridden | no replacement |
17983 ;; Make `C-c C-x' a prefix key
17984 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17986 ;; TAB key with modifiers
17987 (org-defkey org-mode-map "\C-i" 'org-cycle)
17988 (org-defkey org-mode-map [(tab)] 'org-cycle)
17989 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17990 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17991 ;; The following line is necessary under Suse GNU/Linux
17992 (unless (featurep 'xemacs)
17993 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17994 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17995 (define-key org-mode-map [backtab] 'org-shifttab)
17997 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17998 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17999 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18001 ;; Cursor keys with modifiers
18002 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18003 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18004 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18005 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18007 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18008 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18009 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18010 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18012 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18013 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18014 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18015 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18017 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18018 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18019 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18020 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18022 ;; Babel keys
18023 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18024 (mapc (lambda (pair)
18025 (define-key org-babel-map (car pair) (cdr pair)))
18026 org-babel-key-bindings)
18028 ;;; Extra keys for tty access.
18029 ;; We only set them when really needed because otherwise the
18030 ;; menus don't show the simple keys
18032 (when (or org-use-extra-keys
18033 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18034 (not window-system))
18035 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18036 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18037 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18038 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18039 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18040 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18041 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18042 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18043 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18044 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18045 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18046 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18047 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18048 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18049 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18050 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18051 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18052 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18053 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18054 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18055 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18056 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18057 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18058 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18059 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18060 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18061 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18062 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18064 ;; All the other keys
18066 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18067 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18068 (if (boundp 'narrow-map)
18069 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18070 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18071 (if (boundp 'narrow-map)
18072 (org-defkey narrow-map "b" 'org-narrow-to-block)
18073 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18074 (if (boundp 'narrow-map)
18075 (org-defkey narrow-map "e" 'org-narrow-to-element)
18076 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18077 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18078 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18079 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18080 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18081 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18082 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18083 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18084 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18085 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18086 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18087 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18088 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18089 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18090 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18091 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18092 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18093 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18094 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18095 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18096 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18097 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18098 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18099 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18100 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18101 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18102 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18103 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18104 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18105 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18106 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18107 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18108 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18109 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18110 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18111 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18112 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18113 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18114 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18115 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18116 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18117 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18118 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18119 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18120 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18121 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18122 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18123 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18124 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18125 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18126 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18127 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18128 (org-defkey org-mode-map "\C-c^" 'org-sort)
18129 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18130 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18131 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18132 (org-defkey org-mode-map "\C-m" 'org-return)
18133 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18134 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18135 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18136 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18137 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18138 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18139 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18140 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18141 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18142 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18143 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18144 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18145 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18146 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18147 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18148 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18149 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18150 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18151 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18152 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18153 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18154 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18155 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18157 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18158 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18159 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18160 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18162 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18163 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18164 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18165 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18166 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18167 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18168 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18169 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18170 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18171 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18172 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18173 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18174 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18175 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18176 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18177 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18178 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18179 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18180 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18181 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18182 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18183 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18185 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18186 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18187 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18188 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18189 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18191 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18193 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18195 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18196 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18198 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18201 (when (featurep 'xemacs)
18202 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18205 (defconst org-speed-commands-default
18207 ("Outline Navigation")
18208 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18209 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18210 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18211 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18212 ("u" . (org-speed-move-safe 'outline-up-heading))
18213 ("j" . org-goto)
18214 ("g" . (org-refile t))
18215 ("Outline Visibility")
18216 ("c" . org-cycle)
18217 ("C" . org-shifttab)
18218 (" " . org-display-outline-path)
18219 (":" . org-columns)
18220 ("Outline Structure Editing")
18221 ("U" . org-shiftmetaup)
18222 ("D" . org-shiftmetadown)
18223 ("r" . org-metaright)
18224 ("l" . org-metaleft)
18225 ("R" . org-shiftmetaright)
18226 ("L" . org-shiftmetaleft)
18227 ("i" . (progn (forward-char 1) (call-interactively
18228 'org-insert-heading-respect-content)))
18229 ("^" . org-sort)
18230 ("w" . org-refile)
18231 ("a" . org-archive-subtree-default-with-confirmation)
18232 ("." . org-mark-subtree)
18233 ("#" . org-toggle-comment)
18234 ("Clock Commands")
18235 ("I" . org-clock-in)
18236 ("O" . org-clock-out)
18237 ("Meta Data Editing")
18238 ("t" . org-todo)
18239 ("0" . (org-priority ?\ ))
18240 ("1" . (org-priority ?A))
18241 ("2" . (org-priority ?B))
18242 ("3" . (org-priority ?C))
18243 (";" . org-set-tags-command)
18244 ("e" . org-set-effort)
18245 ("E" . org-inc-effort)
18246 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18247 (org-entry-put (point) "APPT_WARNTIME" m)))
18248 ("Agenda Views etc")
18249 ("v" . org-agenda)
18250 ("/" . org-sparse-tree)
18251 ("Misc")
18252 ("o" . org-open-at-point)
18253 ("?" . org-speed-command-help)
18254 ("<" . (org-agenda-set-restriction-lock 'subtree))
18255 (">" . (org-agenda-remove-restriction-lock))
18257 "The default speed commands.")
18259 (defun org-print-speed-command (e)
18260 (if (> (length (car e)) 1)
18261 (progn
18262 (princ "\n")
18263 (princ (car e))
18264 (princ "\n")
18265 (princ (make-string (length (car e)) ?-))
18266 (princ "\n"))
18267 (princ (car e))
18268 (princ " ")
18269 (if (symbolp (cdr e))
18270 (princ (symbol-name (cdr e)))
18271 (prin1 (cdr e)))
18272 (princ "\n")))
18274 (defun org-speed-command-help ()
18275 "Show the available speed commands."
18276 (interactive)
18277 (if (not org-use-speed-commands)
18278 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18279 (with-output-to-temp-buffer "*Help*"
18280 (princ "User-defined Speed commands\n===========================\n")
18281 (mapc 'org-print-speed-command org-speed-commands-user)
18282 (princ "\n")
18283 (princ "Built-in Speed commands\n=======================\n")
18284 (mapc 'org-print-speed-command org-speed-commands-default))
18285 (with-current-buffer "*Help*"
18286 (setq truncate-lines t))))
18288 (defun org-speed-move-safe (cmd)
18289 "Execute CMD, but make sure that the cursor always ends up in a headline.
18290 If not, return to the original position and throw an error."
18291 (interactive)
18292 (let ((pos (point)))
18293 (call-interactively cmd)
18294 (unless (and (bolp) (org-at-heading-p))
18295 (goto-char pos)
18296 (error "Boundary reached while executing %s" cmd))))
18298 (defvar org-self-insert-command-undo-counter 0)
18300 (defvar org-table-auto-blank-field) ; defined in org-table.el
18301 (defvar org-speed-command nil)
18303 (defun org-speed-command-default-hook (keys)
18304 "Hook for activating single-letter speed commands.
18305 `org-speed-commands-default' specifies a minimal command set.
18306 Use `org-speed-commands-user' for further customization."
18307 (when (or (and (bolp) (looking-at org-outline-regexp))
18308 (and (functionp org-use-speed-commands)
18309 (funcall org-use-speed-commands)))
18310 (cdr (assoc keys (append org-speed-commands-user
18311 org-speed-commands-default)))))
18313 (defun org-babel-speed-command-hook (keys)
18314 "Hook for activating single-letter code block commands."
18315 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18316 (cdr (assoc keys org-babel-key-bindings))))
18318 (defcustom org-speed-command-hook
18319 '(org-speed-command-default-hook org-babel-speed-command-hook)
18320 "Hook for activating speed commands at strategic locations.
18321 Hook functions are called in sequence until a valid handler is
18322 found.
18324 Each hook takes a single argument, a user-pressed command key
18325 which is also a `self-insert-command' from the global map.
18327 Within the hook, examine the cursor position and the command key
18328 and return nil or a valid handler as appropriate. Handler could
18329 be one of an interactive command, a function, or a form.
18331 Set `org-use-speed-commands' to non-nil value to enable this
18332 hook. The default setting is `org-speed-command-default-hook'."
18333 :group 'org-structure
18334 :version "24.1"
18335 :type 'hook)
18337 (defun org-self-insert-command (N)
18338 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18339 If the cursor is in a table looking at whitespace, the whitespace is
18340 overwritten, and the table is not marked as requiring realignment."
18341 (interactive "p")
18342 (org-check-before-invisible-edit 'insert)
18343 (cond
18344 ((and org-use-speed-commands
18345 (setq org-speed-command
18346 (run-hook-with-args-until-success
18347 'org-speed-command-hook (this-command-keys))))
18348 (cond
18349 ((commandp org-speed-command)
18350 (setq this-command org-speed-command)
18351 (call-interactively org-speed-command))
18352 ((functionp org-speed-command)
18353 (funcall org-speed-command))
18354 ((and org-speed-command (listp org-speed-command))
18355 (eval org-speed-command))
18356 (t (let (org-use-speed-commands)
18357 (call-interactively 'org-self-insert-command)))))
18358 ((and
18359 (org-table-p)
18360 (progn
18361 ;; check if we blank the field, and if that triggers align
18362 (and (featurep 'org-table) org-table-auto-blank-field
18363 (member last-command
18364 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18365 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18366 ;; got extra space, this field does not determine column width
18367 (let (org-table-may-need-update) (org-table-blank-field))
18368 ;; no extra space, this field may determine column width
18369 (org-table-blank-field)))
18371 (eq N 1)
18372 (looking-at "[^|\n]* |"))
18373 (let (org-table-may-need-update)
18374 (goto-char (1- (match-end 0)))
18375 (backward-delete-char 1)
18376 (goto-char (match-beginning 0))
18377 (self-insert-command N)))
18379 (setq org-table-may-need-update t)
18380 (self-insert-command N)
18381 (org-fix-tags-on-the-fly)
18382 (if org-self-insert-cluster-for-undo
18383 (if (not (eq last-command 'org-self-insert-command))
18384 (setq org-self-insert-command-undo-counter 1)
18385 (if (>= org-self-insert-command-undo-counter 20)
18386 (setq org-self-insert-command-undo-counter 1)
18387 (and (> org-self-insert-command-undo-counter 0)
18388 buffer-undo-list (listp buffer-undo-list)
18389 (not (cadr buffer-undo-list)) ; remove nil entry
18390 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18391 (setq org-self-insert-command-undo-counter
18392 (1+ org-self-insert-command-undo-counter))))))))
18394 (defun org-check-before-invisible-edit (kind)
18395 "Check is editing if kind KIND would be dangerous with invisible text around.
18396 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18397 ;; First, try to get out of here as quickly as possible, to reduce overhead
18398 (if (and org-catch-invisible-edits
18399 (or (not (boundp 'visible-mode)) (not visible-mode))
18400 (or (get-char-property (point) 'invisible)
18401 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18402 ;; OK, we need to take a closer look
18403 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18404 (invisible-before-point (if (bobp) nil (get-char-property
18405 (1- (point)) 'invisible)))
18406 (border-and-ok-direction
18408 ;; Check if we are acting predictably before invisible text
18409 (and invisible-at-point (not invisible-before-point)
18410 (memq kind '(insert delete-backward)))
18411 ;; Check if we are acting predictably after invisible text
18412 ;; This works not well, and I have turned it off. It seems
18413 ;; better to always show and stop after invisible text.
18414 ;; (and (not invisible-at-point) invisible-before-point
18415 ;; (memq kind '(insert delete)))
18417 (when (or (memq invisible-at-point '(outline org-hide-block t))
18418 (memq invisible-before-point '(outline org-hide-block t)))
18419 (if (eq org-catch-invisible-edits 'error)
18420 (error "Editing in invisible areas is prohibited - make visible first"))
18421 (if (and org-custom-properties-overlays
18422 (y-or-n-p "Display invisible properties in this buffer? "))
18423 (org-toggle-custom-properties-visibility)
18424 ;; Make the area visible
18425 (save-excursion
18426 (if invisible-before-point
18427 (goto-char (previous-single-char-property-change
18428 (point) 'invisible)))
18429 (org-cycle))
18430 (cond
18431 ((eq org-catch-invisible-edits 'show)
18432 ;; That's it, we do the edit after showing
18433 (message
18434 "Unfolding invisible region around point before editing")
18435 (sit-for 1))
18436 ((and (eq org-catch-invisible-edits 'smart)
18437 border-and-ok-direction)
18438 (message "Unfolding invisible region around point before editing"))
18440 ;; Don't do the edit, make the user repeat it in full visibility
18441 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18443 (defun org-fix-tags-on-the-fly ()
18444 (when (and (equal (char-after (point-at-bol)) ?*)
18445 (org-at-heading-p))
18446 (org-align-tags-here org-tags-column)))
18448 (defun org-delete-backward-char (N)
18449 "Like `delete-backward-char', insert whitespace at field end in tables.
18450 When deleting backwards, in tables this function will insert whitespace in
18451 front of the next \"|\" separator, to keep the table aligned. The table will
18452 still be marked for re-alignment if the field did fill the entire column,
18453 because, in this case the deletion might narrow the column."
18454 (interactive "p")
18455 (org-check-before-invisible-edit 'delete-backward)
18456 (if (and (org-table-p)
18457 (eq N 1)
18458 (string-match "|" (buffer-substring (point-at-bol) (point)))
18459 (looking-at ".*?|"))
18460 (let ((pos (point))
18461 (noalign (looking-at "[^|\n\r]* |"))
18462 (c org-table-may-need-update))
18463 (backward-delete-char N)
18464 (if (not overwrite-mode)
18465 (progn
18466 (skip-chars-forward "^|")
18467 (insert " ")
18468 (goto-char (1- pos))))
18469 ;; noalign: if there were two spaces at the end, this field
18470 ;; does not determine the width of the column.
18471 (if noalign (setq org-table-may-need-update c)))
18472 (backward-delete-char N)
18473 (org-fix-tags-on-the-fly)))
18475 (defun org-delete-char (N)
18476 "Like `delete-char', but insert whitespace at field end in tables.
18477 When deleting characters, in tables this function will insert whitespace in
18478 front of the next \"|\" separator, to keep the table aligned. The table will
18479 still be marked for re-alignment if the field did fill the entire column,
18480 because, in this case the deletion might narrow the column."
18481 (interactive "p")
18482 (org-check-before-invisible-edit 'delete)
18483 (if (and (org-table-p)
18484 (not (bolp))
18485 (not (= (char-after) ?|))
18486 (eq N 1))
18487 (if (looking-at ".*?|")
18488 (let ((pos (point))
18489 (noalign (looking-at "[^|\n\r]* |"))
18490 (c org-table-may-need-update))
18491 (replace-match (concat
18492 (substring (match-string 0) 1 -1)
18493 " |"))
18494 (goto-char pos)
18495 ;; noalign: if there were two spaces at the end, this field
18496 ;; does not determine the width of the column.
18497 (if noalign (setq org-table-may-need-update c)))
18498 (delete-char N))
18499 (delete-char N)
18500 (org-fix-tags-on-the-fly)))
18502 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18503 (put 'org-self-insert-command 'delete-selection t)
18504 (put 'orgtbl-self-insert-command 'delete-selection t)
18505 (put 'org-delete-char 'delete-selection 'supersede)
18506 (put 'org-delete-backward-char 'delete-selection 'supersede)
18507 (put 'org-yank 'delete-selection 'yank)
18509 ;; Make `flyspell-mode' delay after some commands
18510 (put 'org-self-insert-command 'flyspell-delayed t)
18511 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18512 (put 'org-delete-char 'flyspell-delayed t)
18513 (put 'org-delete-backward-char 'flyspell-delayed t)
18515 ;; Make pabbrev-mode expand after org-mode commands
18516 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18517 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18519 ;; How to do this: Measure non-white length of current string
18520 ;; If equal to column width, we should realign.
18522 (defun org-remap (map &rest commands)
18523 "In MAP, remap the functions given in COMMANDS.
18524 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18525 (let (new old)
18526 (while commands
18527 (setq old (pop commands) new (pop commands))
18528 (if (fboundp 'command-remapping)
18529 (org-defkey map (vector 'remap old) new)
18530 (substitute-key-definition old new map global-map)))))
18532 (when (eq org-enable-table-editor 'optimized)
18533 ;; If the user wants maximum table support, we need to hijack
18534 ;; some standard editing functions
18535 (org-remap org-mode-map
18536 'self-insert-command 'org-self-insert-command
18537 'delete-char 'org-delete-char
18538 'delete-backward-char 'org-delete-backward-char)
18539 (org-defkey org-mode-map "|" 'org-force-self-insert))
18541 (defvar org-ctrl-c-ctrl-c-hook nil
18542 "Hook for functions attaching themselves to `C-c C-c'.
18544 This can be used to add additional functionality to the C-c C-c
18545 key which executes context-dependent commands. This hook is run
18546 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18547 run after the last test.
18549 Each function will be called with no arguments. The function
18550 must check if the context is appropriate for it to act. If yes,
18551 it should do its thing and then return a non-nil value. If the
18552 context is wrong, just do nothing and return nil.")
18554 (defvar org-ctrl-c-ctrl-c-final-hook nil
18555 "Hook for functions attaching themselves to `C-c C-c'.
18557 This can be used to add additional functionality to the C-c C-c
18558 key which executes context-dependent commands. This hook is run
18559 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18560 before the first test.
18562 Each function will be called with no arguments. The function
18563 must check if the context is appropriate for it to act. If yes,
18564 it should do its thing and then return a non-nil value. If the
18565 context is wrong, just do nothing and return nil.")
18567 (defvar org-tab-first-hook nil
18568 "Hook for functions to attach themselves to TAB.
18569 See `org-ctrl-c-ctrl-c-hook' for more information.
18570 This hook runs as the first action when TAB is pressed, even before
18571 `org-cycle' messes around with the `outline-regexp' to cater for
18572 inline tasks and plain list item folding.
18573 If any function in this hook returns t, any other actions that
18574 would have been caused by TAB (such as table field motion or visibility
18575 cycling) will not occur.")
18577 (defvar org-tab-after-check-for-table-hook nil
18578 "Hook for functions to attach themselves to TAB.
18579 See `org-ctrl-c-ctrl-c-hook' for more information.
18580 This hook runs after it has been established that the cursor is not in a
18581 table, but before checking if the cursor is in a headline or if global cycling
18582 should be done.
18583 If any function in this hook returns t, not other actions like visibility
18584 cycling will be done.")
18586 (defvar org-tab-after-check-for-cycling-hook nil
18587 "Hook for functions to attach themselves to TAB.
18588 See `org-ctrl-c-ctrl-c-hook' for more information.
18589 This hook runs after it has been established that not table field motion and
18590 not visibility should be done because of current context. This is probably
18591 the place where a package like yasnippets can hook in.")
18593 (defvar org-tab-before-tab-emulation-hook nil
18594 "Hook for functions to attach themselves to TAB.
18595 See `org-ctrl-c-ctrl-c-hook' for more information.
18596 This hook runs after every other options for TAB have been exhausted, but
18597 before indentation and \t insertion takes place.")
18599 (defvar org-metaleft-hook nil
18600 "Hook for functions attaching themselves to `M-left'.
18601 See `org-ctrl-c-ctrl-c-hook' for more information.")
18602 (defvar org-metaright-hook nil
18603 "Hook for functions attaching themselves to `M-right'.
18604 See `org-ctrl-c-ctrl-c-hook' for more information.")
18605 (defvar org-metaup-hook nil
18606 "Hook for functions attaching themselves to `M-up'.
18607 See `org-ctrl-c-ctrl-c-hook' for more information.")
18608 (defvar org-metadown-hook nil
18609 "Hook for functions attaching themselves to `M-down'.
18610 See `org-ctrl-c-ctrl-c-hook' for more information.")
18611 (defvar org-shiftmetaleft-hook nil
18612 "Hook for functions attaching themselves to `M-S-left'.
18613 See `org-ctrl-c-ctrl-c-hook' for more information.")
18614 (defvar org-shiftmetaright-hook nil
18615 "Hook for functions attaching themselves to `M-S-right'.
18616 See `org-ctrl-c-ctrl-c-hook' for more information.")
18617 (defvar org-shiftmetaup-hook nil
18618 "Hook for functions attaching themselves to `M-S-up'.
18619 See `org-ctrl-c-ctrl-c-hook' for more information.")
18620 (defvar org-shiftmetadown-hook nil
18621 "Hook for functions attaching themselves to `M-S-down'.
18622 See `org-ctrl-c-ctrl-c-hook' for more information.")
18623 (defvar org-metareturn-hook nil
18624 "Hook for functions attaching themselves to `M-RET'.
18625 See `org-ctrl-c-ctrl-c-hook' for more information.")
18626 (defvar org-shiftup-hook nil
18627 "Hook for functions attaching themselves to `S-up'.
18628 See `org-ctrl-c-ctrl-c-hook' for more information.")
18629 (defvar org-shiftup-final-hook nil
18630 "Hook for functions attaching themselves to `S-up'.
18631 This one runs after all other options except shift-select have been excluded.
18632 See `org-ctrl-c-ctrl-c-hook' for more information.")
18633 (defvar org-shiftdown-hook nil
18634 "Hook for functions attaching themselves to `S-down'.
18635 See `org-ctrl-c-ctrl-c-hook' for more information.")
18636 (defvar org-shiftdown-final-hook nil
18637 "Hook for functions attaching themselves to `S-down'.
18638 This one runs after all other options except shift-select have been excluded.
18639 See `org-ctrl-c-ctrl-c-hook' for more information.")
18640 (defvar org-shiftleft-hook nil
18641 "Hook for functions attaching themselves to `S-left'.
18642 See `org-ctrl-c-ctrl-c-hook' for more information.")
18643 (defvar org-shiftleft-final-hook nil
18644 "Hook for functions attaching themselves to `S-left'.
18645 This one runs after all other options except shift-select have been excluded.
18646 See `org-ctrl-c-ctrl-c-hook' for more information.")
18647 (defvar org-shiftright-hook nil
18648 "Hook for functions attaching themselves to `S-right'.
18649 See `org-ctrl-c-ctrl-c-hook' for more information.")
18650 (defvar org-shiftright-final-hook nil
18651 "Hook for functions attaching themselves to `S-right'.
18652 This one runs after all other options except shift-select have been excluded.
18653 See `org-ctrl-c-ctrl-c-hook' for more information.")
18655 (defun org-modifier-cursor-error ()
18656 "Throw an error, a modified cursor command was applied in wrong context."
18657 (error "This command is active in special context like tables, headlines or items"))
18659 (defun org-shiftselect-error ()
18660 "Throw an error because Shift-Cursor command was applied in wrong context."
18661 (if (and (boundp 'shift-select-mode) shift-select-mode)
18662 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18663 (error "This command works only in special context like headlines or timestamps")))
18665 (defun org-call-for-shift-select (cmd)
18666 (let ((this-command-keys-shift-translated t))
18667 (call-interactively cmd)))
18669 (defun org-shifttab (&optional arg)
18670 "Global visibility cycling or move to previous table field.
18671 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18672 on context.
18673 See the individual commands for more information."
18674 (interactive "P")
18675 (cond
18676 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18677 ((integerp arg)
18678 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18679 (message "Content view to level: %d" arg)
18680 (org-content (prefix-numeric-value arg2))
18681 (setq org-cycle-global-status 'overview)))
18682 (t (call-interactively 'org-global-cycle))))
18684 (defun org-shiftmetaleft ()
18685 "Promote subtree or delete table column.
18686 Calls `org-promote-subtree', `org-outdent-item-tree', or
18687 `org-table-delete-column', depending on context. See the
18688 individual commands for more information."
18689 (interactive)
18690 (cond
18691 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18692 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18693 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18694 ((if (not (org-region-active-p)) (org-at-item-p)
18695 (save-excursion (goto-char (region-beginning))
18696 (org-at-item-p)))
18697 (call-interactively 'org-outdent-item-tree))
18698 (t (org-modifier-cursor-error))))
18700 (defun org-shiftmetaright ()
18701 "Demote subtree or insert table column.
18702 Calls `org-demote-subtree', `org-indent-item-tree', or
18703 `org-table-insert-column', depending on context. See the
18704 individual commands for more information."
18705 (interactive)
18706 (cond
18707 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18708 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18709 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18710 ((if (not (org-region-active-p)) (org-at-item-p)
18711 (save-excursion (goto-char (region-beginning))
18712 (org-at-item-p)))
18713 (call-interactively 'org-indent-item-tree))
18714 (t (org-modifier-cursor-error))))
18716 (defun org-shiftmetaup (&optional arg)
18717 "Move subtree up or kill table row.
18718 Calls `org-move-subtree-up' or `org-table-kill-row' or
18719 `org-move-item-up' or `org-timestamp-up', depending on context.
18720 See the individual commands for more information."
18721 (interactive "P")
18722 (cond
18723 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18724 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18725 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18726 ((org-at-item-p) (call-interactively 'org-move-item-up))
18727 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18728 (call-interactively 'org-timestamp-up)))
18729 (t (org-modifier-cursor-error))))
18731 (defun org-shiftmetadown (&optional arg)
18732 "Move subtree down or insert table row.
18733 Calls `org-move-subtree-down' or `org-table-insert-row' or
18734 `org-move-item-down' or `org-timestamp-up', depending on context.
18735 See the individual commands for more information."
18736 (interactive "P")
18737 (cond
18738 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18739 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18740 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18741 ((org-at-item-p) (call-interactively 'org-move-item-down))
18742 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18743 (call-interactively 'org-timestamp-down)))
18744 (t (org-modifier-cursor-error))))
18746 (defsubst org-hidden-tree-error ()
18747 (error
18748 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18750 (defun org-metaleft (&optional arg)
18751 "Promote heading or move table column to left.
18752 Calls `org-do-promote' or `org-table-move-column', depending on context.
18753 With no specific context, calls the Emacs default `backward-word'.
18754 See the individual commands for more information."
18755 (interactive "P")
18756 (cond
18757 ((run-hook-with-args-until-success 'org-metaleft-hook))
18758 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18759 ((org-with-limited-levels
18760 (or (org-at-heading-p)
18761 (and (org-region-active-p)
18762 (save-excursion
18763 (goto-char (region-beginning))
18764 (org-at-heading-p)))))
18765 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18766 (call-interactively 'org-do-promote))
18767 ;; At an inline task.
18768 ((org-at-heading-p)
18769 (call-interactively 'org-inlinetask-promote))
18770 ((or (org-at-item-p)
18771 (and (org-region-active-p)
18772 (save-excursion
18773 (goto-char (region-beginning))
18774 (org-at-item-p))))
18775 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18776 (call-interactively 'org-outdent-item))
18777 (t (call-interactively 'backward-word))))
18779 (defun org-metaright (&optional arg)
18780 "Demote a subtree, a list item or move table column to right.
18781 In front of a drawer or a block keyword, indent it correctly.
18782 With no specific context, calls the Emacs default `forward-word'.
18783 See the individual commands for more information."
18784 (interactive "P")
18785 (cond
18786 ((run-hook-with-args-until-success 'org-metaright-hook))
18787 ((org-at-table-p) (call-interactively 'org-table-move-column))
18788 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18789 ((org-at-block-p) (call-interactively 'org-indent-block))
18790 ((org-with-limited-levels
18791 (or (org-at-heading-p)
18792 (and (org-region-active-p)
18793 (save-excursion
18794 (goto-char (region-beginning))
18795 (org-at-heading-p)))))
18796 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18797 (call-interactively 'org-do-demote))
18798 ;; At an inline task.
18799 ((org-at-heading-p)
18800 (call-interactively 'org-inlinetask-demote))
18801 ((or (org-at-item-p)
18802 (and (org-region-active-p)
18803 (save-excursion
18804 (goto-char (region-beginning))
18805 (org-at-item-p))))
18806 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18807 (call-interactively 'org-indent-item))
18808 (t (call-interactively 'forward-word))))
18810 (defun org-check-for-hidden (what)
18811 "Check if there are hidden headlines/items in the current visual line.
18812 WHAT can be either `headlines' or `items'. If the current line is
18813 an outline or item heading and it has a folded subtree below it,
18814 this function returns t, nil otherwise."
18815 (let ((re (cond
18816 ((eq what 'headlines) org-outline-regexp-bol)
18817 ((eq what 'items) (org-item-beginning-re))
18818 (t (error "This should not happen"))))
18819 beg end)
18820 (save-excursion
18821 (catch 'exit
18822 (unless (org-region-active-p)
18823 (setq beg (point-at-bol))
18824 (beginning-of-line 2)
18825 (while (and (not (eobp)) ;; this is like `next-line'
18826 (get-char-property (1- (point)) 'invisible))
18827 (beginning-of-line 2))
18828 (setq end (point))
18829 (goto-char beg)
18830 (goto-char (point-at-eol))
18831 (setq end (max end (point)))
18832 (while (re-search-forward re end t)
18833 (if (get-char-property (match-beginning 0) 'invisible)
18834 (throw 'exit t))))
18835 nil))))
18837 (autoload 'org-element-at-point "org-element")
18839 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18840 (declare-function org-element-type "org-element" (element))
18841 (declare-function org-element-contents "org-element" (element))
18842 (declare-function org-element-property "org-element" (property element))
18843 (declare-function org-element-paragraph-parser "org-element" (limit))
18844 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18845 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18846 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18847 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18848 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18850 (defun org-metaup (&optional arg)
18851 "Move subtree up or move table row up.
18852 Calls `org-move-subtree-up' or `org-table-move-row' or
18853 `org-move-item-up', depending on context. See the individual commands
18854 for more information."
18855 (interactive "P")
18856 (cond
18857 ((run-hook-with-args-until-success 'org-metaup-hook))
18858 ((org-region-active-p)
18859 (let* ((a (min (region-beginning) (region-end)))
18860 (b (1- (max (region-beginning) (region-end))))
18861 (c (save-excursion (goto-char a)
18862 (move-beginning-of-line 0)))
18863 (d (save-excursion (goto-char a)
18864 (move-end-of-line 0) (point))))
18865 (transpose-regions a b c d)
18866 (goto-char c)))
18867 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18868 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18869 ((org-at-item-p) (call-interactively 'org-move-item-up))
18870 (t (org-drag-element-backward))))
18872 (defun org-metadown (&optional arg)
18873 "Move subtree down or move table row down.
18874 Calls `org-move-subtree-down' or `org-table-move-row' or
18875 `org-move-item-down', depending on context. See the individual
18876 commands for more information."
18877 (interactive "P")
18878 (cond
18879 ((run-hook-with-args-until-success 'org-metadown-hook))
18880 ((org-region-active-p)
18881 (let* ((a (min (region-beginning) (region-end)))
18882 (b (max (region-beginning) (region-end)))
18883 (c (save-excursion (goto-char b)
18884 (move-beginning-of-line 1)))
18885 (d (save-excursion (goto-char b)
18886 (move-end-of-line 1) (1+ (point)))))
18887 (transpose-regions a b c d)
18888 (goto-char d)))
18889 ((org-at-table-p) (call-interactively 'org-table-move-row))
18890 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18891 ((org-at-item-p) (call-interactively 'org-move-item-down))
18892 (t (org-drag-element-forward))))
18894 (defun org-shiftup (&optional arg)
18895 "Increase item in timestamp or increase priority of current headline.
18896 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18897 depending on context. See the individual commands for more information."
18898 (interactive "P")
18899 (cond
18900 ((run-hook-with-args-until-success 'org-shiftup-hook))
18901 ((and org-support-shift-select (org-region-active-p))
18902 (org-call-for-shift-select 'previous-line))
18903 ((org-at-timestamp-p t)
18904 (call-interactively (if org-edit-timestamp-down-means-later
18905 'org-timestamp-down 'org-timestamp-up)))
18906 ((and (not (eq org-support-shift-select 'always))
18907 org-enable-priority-commands
18908 (org-at-heading-p))
18909 (call-interactively 'org-priority-up))
18910 ((and (not org-support-shift-select) (org-at-item-p))
18911 (call-interactively 'org-previous-item))
18912 ((org-clocktable-try-shift 'up arg))
18913 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18914 (org-support-shift-select
18915 (org-call-for-shift-select 'previous-line))
18916 (t (org-shiftselect-error))))
18918 (defun org-shiftdown (&optional arg)
18919 "Decrease item in timestamp or decrease priority of current headline.
18920 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18921 depending on context. See the individual commands for more information."
18922 (interactive "P")
18923 (cond
18924 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18925 ((and org-support-shift-select (org-region-active-p))
18926 (org-call-for-shift-select 'next-line))
18927 ((org-at-timestamp-p t)
18928 (call-interactively (if org-edit-timestamp-down-means-later
18929 'org-timestamp-up 'org-timestamp-down)))
18930 ((and (not (eq org-support-shift-select 'always))
18931 org-enable-priority-commands
18932 (org-at-heading-p))
18933 (call-interactively 'org-priority-down))
18934 ((and (not org-support-shift-select) (org-at-item-p))
18935 (call-interactively 'org-next-item))
18936 ((org-clocktable-try-shift 'down arg))
18937 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18938 (org-support-shift-select
18939 (org-call-for-shift-select 'next-line))
18940 (t (org-shiftselect-error))))
18942 (defun org-shiftright (&optional arg)
18943 "Cycle the thing at point or in the current line, depending on context.
18944 Depending on context, this does one of the following:
18946 - switch a timestamp at point one day into the future
18947 - on a headline, switch to the next TODO keyword.
18948 - on an item, switch entire list to the next bullet type
18949 - on a property line, switch to the next allowed value
18950 - on a clocktable definition line, move time block into the future"
18951 (interactive "P")
18952 (cond
18953 ((run-hook-with-args-until-success 'org-shiftright-hook))
18954 ((and org-support-shift-select (org-region-active-p))
18955 (org-call-for-shift-select 'forward-char))
18956 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18957 ((and (not (eq org-support-shift-select 'always))
18958 (org-at-heading-p))
18959 (let ((org-inhibit-logging
18960 (not org-treat-S-cursor-todo-selection-as-state-change))
18961 (org-inhibit-blocking
18962 (not org-treat-S-cursor-todo-selection-as-state-change)))
18963 (org-call-with-arg 'org-todo 'right)))
18964 ((or (and org-support-shift-select
18965 (not (eq org-support-shift-select 'always))
18966 (org-at-item-bullet-p))
18967 (and (not org-support-shift-select) (org-at-item-p)))
18968 (org-call-with-arg 'org-cycle-list-bullet nil))
18969 ((and (not (eq org-support-shift-select 'always))
18970 (org-at-property-p))
18971 (call-interactively 'org-property-next-allowed-value))
18972 ((org-clocktable-try-shift 'right arg))
18973 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18974 (org-support-shift-select
18975 (org-call-for-shift-select 'forward-char))
18976 (t (org-shiftselect-error))))
18978 (defun org-shiftleft (&optional arg)
18979 "Cycle the thing at point or in the current line, depending on context.
18980 Depending on context, this does one of the following:
18982 - switch a timestamp at point one day into the past
18983 - on a headline, switch to the previous TODO keyword.
18984 - on an item, switch entire list to the previous bullet type
18985 - on a property line, switch to the previous allowed value
18986 - on a clocktable definition line, move time block into the past"
18987 (interactive "P")
18988 (cond
18989 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18990 ((and org-support-shift-select (org-region-active-p))
18991 (org-call-for-shift-select 'backward-char))
18992 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18993 ((and (not (eq org-support-shift-select 'always))
18994 (org-at-heading-p))
18995 (let ((org-inhibit-logging
18996 (not org-treat-S-cursor-todo-selection-as-state-change))
18997 (org-inhibit-blocking
18998 (not org-treat-S-cursor-todo-selection-as-state-change)))
18999 (org-call-with-arg 'org-todo 'left)))
19000 ((or (and org-support-shift-select
19001 (not (eq org-support-shift-select 'always))
19002 (org-at-item-bullet-p))
19003 (and (not org-support-shift-select) (org-at-item-p)))
19004 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19005 ((and (not (eq org-support-shift-select 'always))
19006 (org-at-property-p))
19007 (call-interactively 'org-property-previous-allowed-value))
19008 ((org-clocktable-try-shift 'left arg))
19009 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19010 (org-support-shift-select
19011 (org-call-for-shift-select 'backward-char))
19012 (t (org-shiftselect-error))))
19014 (defun org-shiftcontrolright ()
19015 "Switch to next TODO set."
19016 (interactive)
19017 (cond
19018 ((and org-support-shift-select (org-region-active-p))
19019 (org-call-for-shift-select 'forward-word))
19020 ((and (not (eq org-support-shift-select 'always))
19021 (org-at-heading-p))
19022 (org-call-with-arg 'org-todo 'nextset))
19023 (org-support-shift-select
19024 (org-call-for-shift-select 'forward-word))
19025 (t (org-shiftselect-error))))
19027 (defun org-shiftcontrolleft ()
19028 "Switch to previous TODO set."
19029 (interactive)
19030 (cond
19031 ((and org-support-shift-select (org-region-active-p))
19032 (org-call-for-shift-select 'backward-word))
19033 ((and (not (eq org-support-shift-select 'always))
19034 (org-at-heading-p))
19035 (org-call-with-arg 'org-todo 'previousset))
19036 (org-support-shift-select
19037 (org-call-for-shift-select 'backward-word))
19038 (t (org-shiftselect-error))))
19040 (defun org-shiftcontrolup ()
19041 "Change timestamps synchronously up in CLOCK log lines."
19042 (interactive)
19043 (cond ((and (not org-support-shift-select)
19044 (org-at-clock-log-p)
19045 (org-at-timestamp-p t))
19046 (org-clock-timestamps-up))
19047 (t (org-shiftselect-error))))
19049 (defun org-shiftcontroldown ()
19050 "Change timestamps synchronously down in CLOCK log lines."
19051 (interactive)
19052 (cond ((and (not org-support-shift-select)
19053 (org-at-clock-log-p)
19054 (org-at-timestamp-p t))
19055 (org-clock-timestamps-down))
19056 (t (org-shiftselect-error))))
19058 (defun org-ctrl-c-ret ()
19059 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19060 (interactive)
19061 (cond
19062 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19063 (t (call-interactively 'org-insert-heading))))
19065 (defun org-find-visible ()
19066 (let ((s (point)))
19067 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19068 (get-char-property s 'invisible)))
19070 (defun org-find-invisible ()
19071 (let ((s (point)))
19072 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19073 (not (get-char-property s 'invisible))))
19076 (defun org-copy-visible (beg end)
19077 "Copy the visible parts of the region."
19078 (interactive "r")
19079 (let (snippets s)
19080 (save-excursion
19081 (save-restriction
19082 (narrow-to-region beg end)
19083 (setq s (goto-char (point-min)))
19084 (while (not (= (point) (point-max)))
19085 (goto-char (org-find-invisible))
19086 (push (buffer-substring s (point)) snippets)
19087 (setq s (goto-char (org-find-visible))))))
19088 (kill-new (apply 'concat (nreverse snippets)))))
19090 (defun org-copy-special ()
19091 "Copy region in table or copy current subtree.
19092 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19093 See the individual commands for more information."
19094 (interactive)
19095 (call-interactively
19096 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19098 (defun org-cut-special ()
19099 "Cut region in table or cut current subtree.
19100 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19101 See the individual commands for more information."
19102 (interactive)
19103 (call-interactively
19104 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19106 (defun org-paste-special (arg)
19107 "Paste rectangular region into table, or past subtree relative to level.
19108 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19109 See the individual commands for more information."
19110 (interactive "P")
19111 (if (org-at-table-p)
19112 (org-table-paste-rectangle)
19113 (org-paste-subtree arg)))
19115 (defun org-edit-special (&optional arg)
19116 "Call a special editor for the stuff at point.
19117 When at a table, call the formula editor with `org-table-edit-formulas'.
19118 When at the first line of an src example, call `org-edit-src-code'.
19119 When in an #+include line, visit the include file. Otherwise call
19120 `ffap' to visit the file at point."
19121 (interactive)
19122 ;; possibly prep session before editing source
19123 (when arg
19124 (let* ((info (org-babel-get-src-block-info))
19125 (lang (nth 0 info))
19126 (params (nth 2 info))
19127 (session (cdr (assoc :session params))))
19128 (when (and info session) ;; we are in a source-code block with a session
19129 (funcall
19130 (intern (concat "org-babel-prep-session:" lang)) session params))))
19131 (cond ;; proceed with `org-edit-special'
19132 ((save-excursion
19133 (beginning-of-line 1)
19134 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19135 (find-file (org-trim (match-string 1))))
19136 ((org-edit-src-code))
19137 ((org-edit-fixed-width-region))
19138 ((org-at-table.el-p)
19139 (org-edit-src-code))
19140 ((or (org-at-table-p)
19141 (save-excursion
19142 (beginning-of-line 1)
19143 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19144 (call-interactively 'org-table-edit-formulas))
19145 (t (call-interactively 'ffap))))
19147 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19148 (defun org-ctrl-c-ctrl-c (&optional arg)
19149 "Set tags in headline, or update according to changed information at point.
19151 This command does many different things, depending on context:
19153 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19154 this is what we do.
19156 - If the cursor is on a statistics cookie, update it.
19158 - If the cursor is in a headline, prompt for tags and insert them
19159 into the current line, aligned to `org-tags-column'. When called
19160 with prefix arg, realign all tags in the current buffer.
19162 - If the cursor is in one of the special #+KEYWORD lines, this
19163 triggers scanning the buffer for these lines and updating the
19164 information.
19166 - If the cursor is inside a table, realign the table. This command
19167 works even if the automatic table editor has been turned off.
19169 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19170 the entire table.
19172 - If the cursor is at a footnote reference or definition, jump to
19173 the corresponding definition or references, respectively.
19175 - If the cursor is a the beginning of a dynamic block, update it.
19177 - If the current buffer is a capture buffer, close note and file it.
19179 - If the cursor is on a <<<target>>>, update radio targets and
19180 corresponding links in this buffer.
19182 - If the cursor is on a numbered item in a plain list, renumber the
19183 ordered list.
19185 - If the cursor is on a checkbox, toggle it.
19187 - If the cursor is on a code block, evaluate it. The variable
19188 `org-confirm-babel-evaluate' can be used to control prompting
19189 before code block evaluation, by default every code block
19190 evaluation requires confirmation. Code block evaluation can be
19191 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19192 (interactive "P")
19193 (let ((org-enable-table-editor t))
19194 (cond
19195 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19196 org-occur-highlights
19197 org-latex-fragment-image-overlays)
19198 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19199 (org-remove-occur-highlights)
19200 (org-remove-latex-fragment-image-overlays)
19201 (message "Temporary highlights/overlays removed from current buffer"))
19202 ((and (local-variable-p 'org-finish-function (current-buffer))
19203 (fboundp org-finish-function))
19204 (funcall org-finish-function))
19205 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19206 ((org-in-regexp org-ts-regexp-both)
19207 (org-timestamp-change 0 'day))
19208 ((or (looking-at org-property-start-re)
19209 (org-at-property-p))
19210 (call-interactively 'org-property-action))
19211 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19212 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19213 (or (org-at-heading-p) (org-at-item-p)))
19214 (call-interactively 'org-update-statistics-cookies))
19215 ((org-at-heading-p) (call-interactively 'org-set-tags))
19216 ((org-at-table.el-p)
19217 (message "Use C-c ' to edit table.el tables"))
19218 ((org-at-table-p)
19219 (org-table-maybe-eval-formula)
19220 (if arg
19221 (call-interactively 'org-table-recalculate)
19222 (org-table-maybe-recalculate-line))
19223 (call-interactively 'org-table-align)
19224 (orgtbl-send-table 'maybe))
19225 ((or (org-footnote-at-reference-p)
19226 (org-footnote-at-definition-p))
19227 (call-interactively 'org-footnote-action))
19228 ((org-at-item-checkbox-p)
19229 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19230 ;; list only if at top item.
19231 (let* ((cbox (match-string 1))
19232 (struct (org-list-struct))
19233 (old-struct (copy-tree struct))
19234 (parents (org-list-parents-alist struct))
19235 (orderedp (org-entry-get nil "ORDERED"))
19236 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19237 block-item)
19238 ;; Use a light version of `org-toggle-checkbox' to avoid
19239 ;; computing list structure twice.
19240 (let ((new-box (cond
19241 ((equal arg '(16)) "[-]")
19242 ((equal arg '(4)) nil)
19243 ((equal "[X]" cbox) "[ ]")
19244 (t "[X]"))))
19245 (if (and firstp arg)
19246 ;; If at first item of sub-list, remove check-box from
19247 ;; every item at the same level.
19248 (mapc
19249 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19250 (org-list-get-all-items
19251 (point-at-bol) struct (org-list-prevs-alist struct)))
19252 (org-list-set-checkbox (point-at-bol) struct new-box)))
19253 ;; Replicate `org-list-write-struct', while grabbing a return
19254 ;; value from `org-list-struct-fix-box'.
19255 (org-list-struct-fix-ind struct parents 2)
19256 (org-list-struct-fix-item-end struct)
19257 (let ((prevs (org-list-prevs-alist struct)))
19258 (org-list-struct-fix-bul struct prevs)
19259 (org-list-struct-fix-ind struct parents)
19260 (setq block-item
19261 (org-list-struct-fix-box struct parents prevs orderedp)))
19262 (org-list-struct-apply-struct struct old-struct)
19263 (org-update-checkbox-count-maybe)
19264 (when block-item
19265 (message
19266 "Checkboxes were removed due to unchecked box at line %d"
19267 (org-current-line block-item)))
19268 (when firstp (org-list-send-list 'maybe))))
19269 ((org-at-item-p)
19270 ;; Cursor at an item: repair list. Do checkbox related actions
19271 ;; only if function was called with an argument. Send list only
19272 ;; if at top item.
19273 (let* ((struct (org-list-struct))
19274 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19275 old-struct)
19276 (when arg
19277 (setq old-struct (copy-tree struct))
19278 (if firstp
19279 ;; If at first item of sub-list, add check-box to every
19280 ;; item at the same level.
19281 (mapc
19282 (lambda (pos)
19283 (unless (org-list-get-checkbox pos struct)
19284 (org-list-set-checkbox pos struct "[ ]")))
19285 (org-list-get-all-items
19286 (point-at-bol) struct (org-list-prevs-alist struct)))
19287 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19288 (org-list-write-struct
19289 struct (org-list-parents-alist struct) old-struct)
19290 (when arg (org-update-checkbox-count-maybe))
19291 (when firstp (org-list-send-list 'maybe))))
19292 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19293 ;; Dynamic block
19294 (beginning-of-line 1)
19295 (save-excursion (org-update-dblock)))
19296 ((save-excursion
19297 (let ((case-fold-search t))
19298 (beginning-of-line 1)
19299 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19300 (cond
19301 ((or (equal (match-string 1) "TBLFM")
19302 (equal (match-string 1) "tblfm"))
19303 ;; Recalculate the table before this line
19304 (save-excursion
19305 (beginning-of-line 1)
19306 (skip-chars-backward " \r\n\t")
19307 (if (org-at-table-p)
19308 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19310 (let ((org-inhibit-startup-visibility-stuff t)
19311 (org-startup-align-all-tables nil))
19312 (when (boundp 'org-table-coordinate-overlays)
19313 (mapc 'delete-overlay org-table-coordinate-overlays)
19314 (setq org-table-coordinate-overlays nil))
19315 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19316 (message "Local setup has been refreshed"))))
19317 ((org-clock-update-time-maybe))
19319 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19320 (error "C-c C-c can do nothing useful at this location"))))))
19322 (defun org-mode-restart ()
19323 "Restart Org-mode, to scan again for special lines.
19324 Also updates the keyword regular expressions."
19325 (interactive)
19326 (org-mode)
19327 (message "Org-mode restarted"))
19329 (defun org-kill-note-or-show-branches ()
19330 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19331 (interactive)
19332 (if (not org-finish-function)
19333 (progn
19334 (hide-subtree)
19335 (call-interactively 'show-branches))
19336 (let ((org-note-abort t))
19337 (funcall org-finish-function))))
19339 (defun org-return (&optional indent)
19340 "Goto next table row or insert a newline.
19341 Calls `org-table-next-row' or `newline', depending on context.
19342 See the individual commands for more information."
19343 (interactive)
19344 (let (org-ts-what)
19345 (cond
19346 ((or (bobp) (org-in-src-block-p))
19347 (if indent (newline-and-indent) (newline)))
19348 ((org-at-table-p)
19349 (org-table-justify-field-maybe)
19350 (call-interactively 'org-table-next-row))
19351 ;; when `newline-and-indent' is called within a list, make sure
19352 ;; text moved stays inside the item.
19353 ((and (org-in-item-p) indent)
19354 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19355 (progn
19356 (save-match-data (newline))
19357 (org-indent-line-to (length (match-string 0))))
19358 (let ((ind (org-get-indentation)))
19359 (newline)
19360 (if (org-looking-back org-list-end-re)
19361 (org-indent-line)
19362 (org-indent-line-to ind)))))
19363 ((and org-return-follows-link
19364 (org-at-timestamp-p t)
19365 (not (eq org-ts-what 'after)))
19366 (org-follow-timestamp-link))
19367 ((and org-return-follows-link
19368 (let ((tprop (get-text-property (point) 'face)))
19369 (or (eq tprop 'org-link)
19370 (and (listp tprop) (memq 'org-link tprop)))))
19371 (call-interactively 'org-open-at-point))
19372 ((and (org-at-heading-p)
19373 (looking-at
19374 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19375 (org-show-entry)
19376 (end-of-line 1)
19377 (newline))
19378 (t (if indent (newline-and-indent) (newline))))))
19380 (defun org-return-indent ()
19381 "Goto next table row or insert a newline and indent.
19382 Calls `org-table-next-row' or `newline-and-indent', depending on
19383 context. See the individual commands for more information."
19384 (interactive)
19385 (org-return t))
19387 (defun org-ctrl-c-star ()
19388 "Compute table, or change heading status of lines.
19389 Calls `org-table-recalculate' or `org-toggle-heading',
19390 depending on context."
19391 (interactive)
19392 (cond
19393 ((org-at-table-p)
19394 (call-interactively 'org-table-recalculate))
19396 ;; Convert all lines in region to list items
19397 (call-interactively 'org-toggle-heading))))
19399 (defun org-ctrl-c-minus ()
19400 "Insert separator line in table or modify bullet status of line.
19401 Also turns a plain line or a region of lines into list items.
19402 Calls `org-table-insert-hline', `org-toggle-item', or
19403 `org-cycle-list-bullet', depending on context."
19404 (interactive)
19405 (cond
19406 ((org-at-table-p)
19407 (call-interactively 'org-table-insert-hline))
19408 ((org-region-active-p)
19409 (call-interactively 'org-toggle-item))
19410 ((org-in-item-p)
19411 (call-interactively 'org-cycle-list-bullet))
19413 (call-interactively 'org-toggle-item))))
19415 (defun org-toggle-item (arg)
19416 "Convert headings or normal lines to items, items to normal lines.
19417 If there is no active region, only the current line is considered.
19419 If the first non blank line in the region is an headline, convert
19420 all headlines to items, shifting text accordingly.
19422 If it is an item, convert all items to normal lines.
19424 If it is normal text, change region into an item. With a prefix
19425 argument ARG, change each line in region into an item."
19426 (interactive "P")
19427 (let ((shift-text
19428 (function
19429 ;; Shift text in current section to IND, from point to END.
19430 ;; The function leaves point to END line.
19431 (lambda (ind end)
19432 (let ((min-i 1000) (end (copy-marker end)))
19433 ;; First determine the minimum indentation (MIN-I) of
19434 ;; the text.
19435 (save-excursion
19436 (catch 'exit
19437 (while (< (point) end)
19438 (let ((i (org-get-indentation)))
19439 (cond
19440 ;; Skip blank lines and inline tasks.
19441 ((looking-at "^[ \t]*$"))
19442 ((looking-at org-outline-regexp-bol))
19443 ;; We can't find less than 0 indentation.
19444 ((zerop i) (throw 'exit (setq min-i 0)))
19445 ((< i min-i) (setq min-i i))))
19446 (forward-line))))
19447 ;; Then indent each line so that a line indented to
19448 ;; MIN-I becomes indented to IND. Ignore blank lines
19449 ;; and inline tasks in the process.
19450 (let ((delta (- ind min-i)))
19451 (while (< (point) end)
19452 (unless (or (looking-at "^[ \t]*$")
19453 (looking-at org-outline-regexp-bol))
19454 (org-indent-line-to (+ (org-get-indentation) delta)))
19455 (forward-line)))))))
19456 (skip-blanks
19457 (function
19458 ;; Return beginning of first non-blank line, starting from
19459 ;; line at POS.
19460 (lambda (pos)
19461 (save-excursion
19462 (goto-char pos)
19463 (skip-chars-forward " \r\t\n")
19464 (point-at-bol)))))
19465 beg end)
19466 ;; Determine boundaries of changes.
19467 (if (org-region-active-p)
19468 (setq beg (funcall skip-blanks (region-beginning))
19469 end (copy-marker (region-end)))
19470 (setq beg (funcall skip-blanks (point-at-bol))
19471 end (copy-marker (point-at-eol))))
19472 ;; Depending on the starting line, choose an action on the text
19473 ;; between BEG and END.
19474 (org-with-limited-levels
19475 (save-excursion
19476 (goto-char beg)
19477 (cond
19478 ;; Case 1. Start at an item: de-itemize. Note that it only
19479 ;; happens when a region is active: `org-ctrl-c-minus'
19480 ;; would call `org-cycle-list-bullet' otherwise.
19481 ((org-at-item-p)
19482 (while (< (point) end)
19483 (when (org-at-item-p)
19484 (skip-chars-forward " \t")
19485 (delete-region (point) (match-end 0)))
19486 (forward-line)))
19487 ;; Case 2. Start at an heading: convert to items.
19488 ((org-at-heading-p)
19489 (let* ((bul (org-list-bullet-string "-"))
19490 (bul-len (length bul))
19491 ;; Indentation of the first heading. It should be
19492 ;; relative to the indentation of its parent, if any.
19493 (start-ind (save-excursion
19494 (cond
19495 ((not org-adapt-indentation) 0)
19496 ((not (outline-previous-heading)) 0)
19497 (t (length (match-string 0))))))
19498 ;; Level of first heading. Further headings will be
19499 ;; compared to it to determine hierarchy in the list.
19500 (ref-level (org-reduced-level (org-outline-level))))
19501 (while (< (point) end)
19502 (let* ((level (org-reduced-level (org-outline-level)))
19503 (delta (max 0 (- level ref-level))))
19504 ;; If current headline is less indented than the first
19505 ;; one, set it as reference, in order to preserve
19506 ;; subtrees.
19507 (when (< level ref-level) (setq ref-level level))
19508 (replace-match bul t t)
19509 (org-indent-line-to (+ start-ind (* delta bul-len)))
19510 ;; Ensure all text down to END (or SECTION-END) belongs
19511 ;; to the newly created item.
19512 (let ((section-end (save-excursion
19513 (or (outline-next-heading) (point)))))
19514 (forward-line)
19515 (funcall shift-text
19516 (+ start-ind (* (1+ delta) bul-len))
19517 (min end section-end)))))))
19518 ;; Case 3. Normal line with ARG: turn each non-item line into
19519 ;; an item.
19520 (arg
19521 (while (< (point) end)
19522 (unless (or (org-at-heading-p) (org-at-item-p))
19523 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19524 (replace-match
19525 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19526 (forward-line)))
19527 ;; Case 4. Normal line without ARG: make the first line of
19528 ;; region an item, and shift indentation of others
19529 ;; lines to set them as item's body.
19530 (t (let* ((bul (org-list-bullet-string "-"))
19531 (bul-len (length bul))
19532 (ref-ind (org-get-indentation)))
19533 (skip-chars-forward " \t")
19534 (insert bul)
19535 (forward-line)
19536 (while (< (point) end)
19537 ;; Ensure that lines less indented than first one
19538 ;; still get included in item body.
19539 (funcall shift-text
19540 (+ ref-ind bul-len)
19541 (min end (save-excursion (or (outline-next-heading)
19542 (point)))))
19543 (forward-line)))))))))
19545 (defun org-toggle-heading (&optional nstars)
19546 "Convert headings to normal text, or items or text to headings.
19547 If there is no active region, only the current line is considered.
19549 With a \\[universal-argument] prefix, convert the whole list at
19550 point into heading.
19552 In a region:
19554 - If the first non blank line is an headline, remove the stars
19555 from all headlines in the region.
19557 - If it is a normal line turn each and every normal line (i.e. not an
19558 heading or an item) in the region into a heading.
19560 - If it is a plain list item, turn all plain list items into headings.
19562 When converting a line into a heading, the number of stars is chosen
19563 such that the lines become children of the current entry. However,
19564 when a prefix argument is given, its value determines the number of
19565 stars to add."
19566 (interactive "P")
19567 (let ((skip-blanks
19568 (function
19569 ;; Return beginning of first non-blank line, starting from
19570 ;; line at POS.
19571 (lambda (pos)
19572 (save-excursion
19573 (goto-char pos)
19574 (while (org-at-comment-p) (forward-line))
19575 (skip-chars-forward " \r\t\n")
19576 (point-at-bol)))))
19577 beg end toggled)
19578 ;; Determine boundaries of changes. If a universal prefix has
19579 ;; been given, put the list in a region. If region ends at a bol,
19580 ;; do not consider the last line to be in the region.
19582 (when (and current-prefix-arg (org-at-item-p))
19583 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19584 (org-mark-element))
19586 (if (org-region-active-p)
19587 (setq beg (funcall skip-blanks (region-beginning))
19588 end (copy-marker (save-excursion
19589 (goto-char (region-end))
19590 (if (bolp) (point) (point-at-eol)))))
19591 (setq beg (funcall skip-blanks (point-at-bol))
19592 end (copy-marker (point-at-eol))))
19593 ;; Ensure inline tasks don't count as headings.
19594 (org-with-limited-levels
19595 (save-excursion
19596 (goto-char beg)
19597 (cond
19598 ;; Case 1. Started at an heading: de-star headings.
19599 ((org-at-heading-p)
19600 (while (< (point) end)
19601 (when (org-at-heading-p t)
19602 (looking-at org-outline-regexp) (replace-match "")
19603 (setq toggled t))
19604 (forward-line)))
19605 ;; Case 2. Started at an item: change items into headlines.
19606 ;; One star will be added by `org-list-to-subtree'.
19607 ((org-at-item-p)
19608 (let* ((stars (make-string
19609 (if nstars
19610 ;; subtract the star that will be added again by
19611 ;; `org-list-to-subtree'
19612 (1- (prefix-numeric-value current-prefix-arg))
19613 (or (org-current-level) 0))
19614 ?*))
19615 (add-stars
19616 (cond (nstars "") ; stars from prefix only
19617 ((equal stars "") "") ; before first heading
19618 (org-odd-levels-only "*") ; inside heading, odd
19619 (t "")))) ; inside heading, oddeven
19620 (while (< (point) end)
19621 (when (org-at-item-p)
19622 ;; Pay attention to cases when region ends before list.
19623 (let* ((struct (org-list-struct))
19624 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19625 (save-restriction
19626 (narrow-to-region (point) list-end)
19627 (insert
19628 (org-list-to-subtree
19629 (org-list-parse-list t)
19630 '(:istart (concat stars add-stars (funcall get-stars depth))
19631 :icount (concat stars add-stars (funcall get-stars depth)))))))
19632 (setq toggled t))
19633 (forward-line))))
19634 ;; Case 3. Started at normal text: make every line an heading,
19635 ;; skipping headlines and items.
19636 (t (let* ((stars (make-string
19637 (if nstars
19638 (prefix-numeric-value current-prefix-arg)
19639 (or (org-current-level) 0))
19640 ?*))
19641 (add-stars
19642 (cond (nstars "") ; stars from prefix only
19643 ((equal stars "") "*") ; before first heading
19644 (org-odd-levels-only "**") ; inside heading, odd
19645 (t "*"))) ; inside heading, oddeven
19646 (rpl (concat stars add-stars " ")))
19647 (while (< (point) end)
19648 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19649 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19650 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19651 (forward-line)))))))
19652 (unless toggled (message "Cannot toggle heading from here"))))
19654 (defun org-meta-return (&optional arg)
19655 "Insert a new heading or wrap a region in a table.
19656 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19657 See the individual commands for more information."
19658 (interactive "P")
19659 (cond
19660 ((run-hook-with-args-until-success 'org-metareturn-hook))
19661 ((or (org-at-drawer-p) (org-at-property-p))
19662 (newline-and-indent))
19663 ((org-at-table-p)
19664 (call-interactively 'org-table-wrap-region))
19665 (t (call-interactively 'org-insert-heading))))
19667 ;;; Menu entries
19669 ;; Define the Org-mode menus
19670 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19671 '("Tbl"
19672 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19673 ["Next Field" org-cycle (org-at-table-p)]
19674 ["Previous Field" org-shifttab (org-at-table-p)]
19675 ["Next Row" org-return (org-at-table-p)]
19676 "--"
19677 ["Blank Field" org-table-blank-field (org-at-table-p)]
19678 ["Edit Field" org-table-edit-field (org-at-table-p)]
19679 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19680 "--"
19681 ("Column"
19682 ["Move Column Left" org-metaleft (org-at-table-p)]
19683 ["Move Column Right" org-metaright (org-at-table-p)]
19684 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19685 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19686 ("Row"
19687 ["Move Row Up" org-metaup (org-at-table-p)]
19688 ["Move Row Down" org-metadown (org-at-table-p)]
19689 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19690 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19691 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19692 "--"
19693 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19694 ("Rectangle"
19695 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19696 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19697 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19698 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19699 "--"
19700 ("Calculate"
19701 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19702 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19703 ["Edit Formulas" org-edit-special (org-at-table-p)]
19704 "--"
19705 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19706 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19707 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19708 "--"
19709 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19710 "--"
19711 ["Sum Column/Rectangle" org-table-sum
19712 (or (org-at-table-p) (org-region-active-p))]
19713 ["Which Column?" org-table-current-column (org-at-table-p)])
19714 ["Debug Formulas"
19715 org-table-toggle-formula-debugger
19716 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19717 ["Show Col/Row Numbers"
19718 org-table-toggle-coordinate-overlays
19719 :style toggle
19720 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19721 "--"
19722 ["Create" org-table-create (and (not (org-at-table-p))
19723 org-enable-table-editor)]
19724 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19725 ["Import from File" org-table-import (not (org-at-table-p))]
19726 ["Export to File" org-table-export (org-at-table-p)]
19727 "--"
19728 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19730 (easy-menu-define org-org-menu org-mode-map "Org menu"
19731 '("Org"
19732 ("Show/Hide"
19733 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19734 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19735 ["Sparse Tree..." org-sparse-tree t]
19736 ["Reveal Context" org-reveal t]
19737 ["Show All" show-all t]
19738 "--"
19739 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19740 "--"
19741 ["New Heading" org-insert-heading t]
19742 ("Navigate Headings"
19743 ["Up" outline-up-heading t]
19744 ["Next" outline-next-visible-heading t]
19745 ["Previous" outline-previous-visible-heading t]
19746 ["Next Same Level" outline-forward-same-level t]
19747 ["Previous Same Level" outline-backward-same-level t]
19748 "--"
19749 ["Jump" org-goto t])
19750 ("Edit Structure"
19751 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19752 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19753 "--"
19754 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19755 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19756 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19757 "--"
19758 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19759 "--"
19760 ["Copy visible text" org-copy-visible t]
19761 "--"
19762 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19763 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19764 ["Demote Heading" org-metaright (not (org-at-table-p))]
19765 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19766 "--"
19767 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19768 "--"
19769 ["Convert to odd levels" org-convert-to-odd-levels t]
19770 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19771 ("Editing"
19772 ["Emphasis..." org-emphasize t]
19773 ["Edit Source Example" org-edit-special t]
19774 "--"
19775 ["Footnote new/jump" org-footnote-action t]
19776 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19777 ("Archive"
19778 ["Archive (default method)" org-archive-subtree-default t]
19779 "--"
19780 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19781 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19782 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19784 "--"
19785 ("Hyperlinks"
19786 ["Store Link (Global)" org-store-link t]
19787 ["Find existing link to here" org-occur-link-in-agenda-files t]
19788 ["Insert Link" org-insert-link t]
19789 ["Follow Link" org-open-at-point t]
19790 "--"
19791 ["Next link" org-next-link t]
19792 ["Previous link" org-previous-link t]
19793 "--"
19794 ["Descriptive Links"
19795 org-toggle-link-display
19796 :style radio
19797 :selected org-descriptive-links
19799 ["Literal Links"
19800 org-toggle-link-display
19801 :style radio
19802 :selected (not org-descriptive-links)])
19803 "--"
19804 ("TODO Lists"
19805 ["TODO/DONE/-" org-todo t]
19806 ("Select keyword"
19807 ["Next keyword" org-shiftright (org-at-heading-p)]
19808 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19809 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19810 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19811 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19812 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19813 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19814 "--"
19815 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19816 :selected org-enforce-todo-dependencies :style toggle :active t]
19817 "Settings for tree at point"
19818 ["Do Children sequentially" org-toggle-ordered-property :style radio
19819 :selected (org-entry-get nil "ORDERED")
19820 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19821 ["Do Children parallel" org-toggle-ordered-property :style radio
19822 :selected (not (org-entry-get nil "ORDERED"))
19823 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19824 "--"
19825 ["Set Priority" org-priority t]
19826 ["Priority Up" org-shiftup t]
19827 ["Priority Down" org-shiftdown t]
19828 "--"
19829 ["Get news from all feeds" org-feed-update-all t]
19830 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19831 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19832 ("TAGS and Properties"
19833 ["Set Tags" org-set-tags-command t]
19834 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19835 "--"
19836 ["Set property" org-set-property t]
19837 ["Column view of properties" org-columns t]
19838 ["Insert Column View DBlock" org-insert-columns-dblock t])
19839 ("Dates and Scheduling"
19840 ["Timestamp" org-time-stamp t]
19841 ["Timestamp (inactive)" org-time-stamp-inactive t]
19842 ("Change Date"
19843 ["1 Day Later" org-shiftright t]
19844 ["1 Day Earlier" org-shiftleft t]
19845 ["1 ... Later" org-shiftup t]
19846 ["1 ... Earlier" org-shiftdown t])
19847 ["Compute Time Range" org-evaluate-time-range t]
19848 ["Schedule Item" org-schedule t]
19849 ["Deadline" org-deadline t]
19850 "--"
19851 ["Custom time format" org-toggle-time-stamp-overlays
19852 :style radio :selected org-display-custom-times]
19853 "--"
19854 ["Goto Calendar" org-goto-calendar t]
19855 ["Date from Calendar" org-date-from-calendar t]
19856 "--"
19857 ["Start/Restart Timer" org-timer-start t]
19858 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19859 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19860 ["Insert Timer String" org-timer t]
19861 ["Insert Timer Item" org-timer-item t])
19862 ("Logging work"
19863 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19864 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19865 ["Clock out" org-clock-out t]
19866 ["Clock cancel" org-clock-cancel t]
19867 "--"
19868 ["Mark as default task" org-clock-mark-default-task t]
19869 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19870 ["Goto running clock" org-clock-goto t]
19871 "--"
19872 ["Display times" org-clock-display t]
19873 ["Create clock table" org-clock-report t]
19874 "--"
19875 ["Record DONE time"
19876 (progn (setq org-log-done (not org-log-done))
19877 (message "Switching to %s will %s record a timestamp"
19878 (car org-done-keywords)
19879 (if org-log-done "automatically" "not")))
19880 :style toggle :selected org-log-done])
19881 "--"
19882 ["Agenda Command..." org-agenda t]
19883 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19884 ("File List for Agenda")
19885 ("Special views current file"
19886 ["TODO Tree" org-show-todo-tree t]
19887 ["Check Deadlines" org-check-deadlines t]
19888 ["Timeline" org-timeline t]
19889 ["Tags/Property tree" org-match-sparse-tree t])
19890 "--"
19891 ["Export/Publish..." org-export t]
19892 ("LaTeX"
19893 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19894 :selected org-cdlatex-mode]
19895 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19896 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19897 ["Modify math symbol" org-cdlatex-math-modify
19898 (org-inside-LaTeX-fragment-p)]
19899 ["Insert citation" org-reftex-citation t]
19900 "--"
19901 ["Template for BEAMER" (progn (require 'org-beamer)
19902 (org-insert-beamer-options-template)) t])
19903 "--"
19904 ("MobileOrg"
19905 ["Push Files and Views" org-mobile-push t]
19906 ["Get Captured and Flagged" org-mobile-pull t]
19907 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19908 "--"
19909 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19910 "--"
19911 ("Documentation"
19912 ["Show Version" org-version t]
19913 ["Info Documentation" org-info t])
19914 ("Customize"
19915 ["Browse Org Group" org-customize t]
19916 "--"
19917 ["Expand This Menu" org-create-customize-menu
19918 (fboundp 'customize-menu-create)])
19919 ["Send bug report" org-submit-bug-report t]
19920 "--"
19921 ("Refresh/Reload"
19922 ["Refresh setup current buffer" org-mode-restart t]
19923 ["Reload Org (after update)" org-reload t]
19924 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19927 (defun org-info (&optional node)
19928 "Read documentation for Org-mode in the info system.
19929 With optional NODE, go directly to that node."
19930 (interactive)
19931 (info (format "(org)%s" (or node ""))))
19933 ;;;###autoload
19934 (defun org-submit-bug-report ()
19935 "Submit a bug report on Org-mode via mail.
19937 Don't hesitate to report any problems or inaccurate documentation.
19939 If you don't have setup sending mail from (X)Emacs, please copy the
19940 output buffer into your mail program, as it gives us important
19941 information about your Org-mode version and configuration."
19942 (interactive)
19943 (require 'reporter)
19944 (org-load-modules-maybe)
19945 (org-require-autoloaded-modules)
19946 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19947 (reporter-submit-bug-report
19948 "emacs-orgmode@gnu.org"
19949 (org-version nil 'full)
19950 (let (list)
19951 (save-window-excursion
19952 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19953 (delete-other-windows)
19954 (erase-buffer)
19955 (insert "You are about to submit a bug report to the Org-mode mailing list.
19957 We would like to add your full Org-mode and Outline configuration to the
19958 bug report. This greatly simplifies the work of the maintainer and
19959 other experts on the mailing list.
19961 HOWEVER, some variables you have customized may contain private
19962 information. The names of customers, colleagues, or friends, might
19963 appear in the form of file names, tags, todo states, or search strings.
19964 If you answer yes to the prompt, you might want to check and remove
19965 such private information before sending the email.")
19966 (add-text-properties (point-min) (point-max) '(face org-warning))
19967 (when (yes-or-no-p "Include your Org-mode configuration ")
19968 (mapatoms
19969 (lambda (v)
19970 (and (boundp v)
19971 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19972 (or (and (symbol-value v)
19973 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19974 (and
19975 (get v 'custom-type) (get v 'standard-value)
19976 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19977 (push v list)))))
19978 (kill-buffer (get-buffer "*Warn about privacy*"))
19979 list))
19980 nil nil
19981 "Remember to cover the basics, that is, what you expected to happen and
19982 what in fact did happen. You don't know how to make a good report? See
19984 http://orgmode.org/manual/Feedback.html#Feedback
19986 Your bug report will be posted to the Org-mode mailing list.
19987 ------------------------------------------------------------------------")
19988 (save-excursion
19989 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19990 (replace-match "\\1Bug: \\3 [\\2]")))))
19993 (defun org-install-agenda-files-menu ()
19994 (let ((bl (buffer-list)))
19995 (save-excursion
19996 (while bl
19997 (set-buffer (pop bl))
19998 (if (derived-mode-p 'org-mode) (setq bl nil)))
19999 (when (derived-mode-p 'org-mode)
20000 (easy-menu-change
20001 '("Org") "File List for Agenda"
20002 (append
20003 (list
20004 ["Edit File List" (org-edit-agenda-file-list) t]
20005 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20006 ["Remove Current File from List" org-remove-file t]
20007 ["Cycle through agenda files" org-cycle-agenda-files t]
20008 ["Occur in all agenda files" org-occur-in-agenda-files t]
20009 "--")
20010 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20012 ;;;; Documentation
20014 ;;;###autoload
20015 (defun org-require-autoloaded-modules ()
20016 (interactive)
20017 (mapc 'require
20018 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20019 org-docbook org-exp org-html org-icalendar
20020 org-id org-latex
20021 org-publish org-remember org-table
20022 org-timer org-xoxo)))
20024 ;;;###autoload
20025 (defun org-reload (&optional uncompiled)
20026 "Reload all org lisp files.
20027 With prefix arg UNCOMPILED, load the uncompiled versions."
20028 (interactive "P")
20029 (require 'find-func)
20030 (let* ((file-re "^org\\(-.*\\)?\\.el")
20031 (dir-org (file-name-directory (org-find-library-dir "org")))
20032 (dir-org-contrib (ignore-errors
20033 (file-name-directory
20034 (org-find-library-dir "org-contribdir"))))
20035 (babel-files
20036 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20037 (append (list nil "comint" "eval" "exp" "keys"
20038 "lob" "ref" "table" "tangle")
20039 (delq nil
20040 (mapcar
20041 (lambda (lang)
20042 (when (cdr lang) (symbol-name (car lang))))
20043 org-babel-load-languages)))))
20044 (files
20045 (append babel-files
20046 (and dir-org-contrib
20047 (directory-files dir-org-contrib t file-re))
20048 (directory-files dir-org t file-re)))
20049 (remove-re (concat (if (featurep 'xemacs)
20050 "org-colview" "org-colview-xemacs")
20051 "\\'")))
20052 (setq files (mapcar 'file-name-sans-extension files))
20053 (setq files (mapcar
20054 (lambda (x) (if (string-match remove-re x) nil x))
20055 files))
20056 (setq files (delq nil files))
20057 (mapc
20058 (lambda (f)
20059 (when (featurep (intern (file-name-nondirectory f)))
20060 (if (and (not uncompiled)
20061 (file-exists-p (concat f ".elc")))
20062 (load (concat f ".elc") nil nil 'nosuffix)
20063 (load (concat f ".el") nil nil 'nosuffix))))
20064 files)
20065 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20066 (org-version nil 'full 'message))
20068 ;;;###autoload
20069 (defun org-customize ()
20070 "Call the customize function with org as argument."
20071 (interactive)
20072 (org-load-modules-maybe)
20073 (org-require-autoloaded-modules)
20074 (customize-browse 'org))
20076 (defun org-create-customize-menu ()
20077 "Create a full customization menu for Org-mode, insert it into the menu."
20078 (interactive)
20079 (org-load-modules-maybe)
20080 (org-require-autoloaded-modules)
20081 (if (fboundp 'customize-menu-create)
20082 (progn
20083 (easy-menu-change
20084 '("Org") "Customize"
20085 `(["Browse Org group" org-customize t]
20086 "--"
20087 ,(customize-menu-create 'org)
20088 ["Set" Custom-set t]
20089 ["Save" Custom-save t]
20090 ["Reset to Current" Custom-reset-current t]
20091 ["Reset to Saved" Custom-reset-saved t]
20092 ["Reset to Standard Settings" Custom-reset-standard t]))
20093 (message "\"Org\"-menu now contains full customization menu"))
20094 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20096 ;;;; Miscellaneous stuff
20098 ;;; Generally useful functions
20100 (defun org-get-at-bol (property)
20101 "Get text property PROPERTY at beginning of line."
20102 (get-text-property (point-at-bol) property))
20104 (defun org-find-text-property-in-string (prop s)
20105 "Return the first non-nil value of property PROP in string S."
20106 (or (get-text-property 0 prop s)
20107 (get-text-property (or (next-single-property-change 0 prop s) 0)
20108 prop s)))
20110 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20111 "Display the given MESSAGE as a warning."
20112 (if (fboundp 'display-warning)
20113 (display-warning 'org message
20114 (if (featurep 'xemacs) 'warning :warning))
20115 (let ((buf (get-buffer-create "*Org warnings*")))
20116 (with-current-buffer buf
20117 (goto-char (point-max))
20118 (insert "Warning (Org): " message)
20119 (unless (bolp)
20120 (newline)))
20121 (display-buffer buf)
20122 (sit-for 0))))
20124 (defun org-eval (form)
20125 "Eval FORM and return result."
20126 (condition-case error
20127 (eval form)
20128 (error (format "%%![Error: %s]" error))))
20130 (defun org-in-clocktable-p ()
20131 "Check if the cursor is in a clocktable."
20132 (let ((pos (point)) start)
20133 (save-excursion
20134 (end-of-line 1)
20135 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20136 (setq start (match-beginning 0))
20137 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20138 (>= (match-end 0) pos)
20139 start))))
20141 (defun org-in-commented-line ()
20142 "Is point in a line starting with `#'?"
20143 (equal (char-after (point-at-bol)) ?#))
20145 (defun org-in-indented-comment-line ()
20146 "Is point in a line starting with `#' after some white space?"
20147 (save-excursion
20148 (save-match-data
20149 (goto-char (point-at-bol))
20150 (looking-at "[ \t]*#"))))
20152 (defun org-in-verbatim-emphasis ()
20153 (save-match-data
20154 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20156 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20157 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20158 (if (and marker (marker-buffer marker)
20159 (buffer-live-p (marker-buffer marker)))
20160 (progn
20161 (org-pop-to-buffer-same-window (marker-buffer marker))
20162 (if (or (> marker (point-max)) (< marker (point-min)))
20163 (widen))
20164 (goto-char marker)
20165 (org-show-context 'org-goto))
20166 (if bookmark
20167 (bookmark-jump bookmark)
20168 (error "Cannot find location"))))
20170 (defun org-quote-csv-field (s)
20171 "Quote field for inclusion in CSV material."
20172 (if (string-match "[\",]" s)
20173 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20176 (defun org-force-self-insert (N)
20177 "Needed to enforce self-insert under remapping."
20178 (interactive "p")
20179 (self-insert-command N))
20181 (defun org-string-width (s)
20182 "Compute width of string, ignoring invisible characters.
20183 This ignores character with invisibility property `org-link', and also
20184 characters with property `org-cwidth', because these will become invisible
20185 upon the next fontification round."
20186 (let (b l)
20187 (when (or (eq t buffer-invisibility-spec)
20188 (assq 'org-link buffer-invisibility-spec))
20189 (while (setq b (text-property-any 0 (length s)
20190 'invisible 'org-link s))
20191 (setq s (concat (substring s 0 b)
20192 (substring s (or (next-single-property-change
20193 b 'invisible s) (length s)))))))
20194 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20195 (setq s (concat (substring s 0 b)
20196 (substring s (or (next-single-property-change
20197 b 'org-cwidth s) (length s))))))
20198 (setq l (string-width s) b -1)
20199 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20200 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20203 (defun org-shorten-string (s maxlength)
20204 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20205 If the string is shorter or has length MAXLENGTH, just return the
20206 original string. If it is longer, the functions finds a space in the
20207 string, breaks this string off at that locations and adds three dots
20208 as ellipsis. Including the ellipsis, the string will not be longer
20209 than MAXLENGTH. If finding a good breaking point in the string does
20210 not work, the string is just chopped off in the middle of a word
20211 if necessary."
20212 (if (<= (length s) maxlength)
20214 (let* ((n (max (- maxlength 4) 1))
20215 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20216 (if (string-match re s)
20217 (concat (match-string 1 s) "...")
20218 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20220 (defun org-get-indentation (&optional line)
20221 "Get the indentation of the current line, interpreting tabs.
20222 When LINE is given, assume it represents a line and compute its indentation."
20223 (if line
20224 (if (string-match "^ *" (org-remove-tabs line))
20225 (match-end 0))
20226 (save-excursion
20227 (beginning-of-line 1)
20228 (skip-chars-forward " \t")
20229 (current-column))))
20231 (defun org-get-string-indentation (s)
20232 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20233 (let ((n -1) (i 0) (w tab-width) c)
20234 (catch 'exit
20235 (while (< (setq n (1+ n)) (length s))
20236 (setq c (aref s n))
20237 (cond ((= c ?\ ) (setq i (1+ i)))
20238 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20239 (t (throw 'exit t)))))
20242 (defun org-remove-tabs (s &optional width)
20243 "Replace tabulators in S with spaces.
20244 Assumes that s is a single line, starting in column 0."
20245 (setq width (or width tab-width))
20246 (while (string-match "\t" s)
20247 (setq s (replace-match
20248 (make-string
20249 (- (* width (/ (+ (match-beginning 0) width) width))
20250 (match-beginning 0)) ?\ )
20251 t t s)))
20254 (defun org-fix-indentation (line ind)
20255 "Fix indentation in LINE.
20256 IND is a cons cell with target and minimum indentation.
20257 If the current indentation in LINE is smaller than the minimum,
20258 leave it alone. If it is larger than ind, set it to the target."
20259 (let* ((l (org-remove-tabs line))
20260 (i (org-get-indentation l))
20261 (i1 (car ind)) (i2 (cdr ind)))
20262 (if (>= i i2) (setq l (substring line i2)))
20263 (if (> i1 0)
20264 (concat (make-string i1 ?\ ) l)
20265 l)))
20267 (defun org-remove-indentation (code &optional n)
20268 "Remove the maximum common indentation from the lines in CODE.
20269 N may optionally be the number of spaces to remove."
20270 (with-temp-buffer
20271 (insert code)
20272 (org-do-remove-indentation n)
20273 (buffer-string)))
20275 (defun org-do-remove-indentation (&optional n)
20276 "Remove the maximum common indentation from the buffer."
20277 (untabify (point-min) (point-max))
20278 (let ((min 10000) re)
20279 (if n
20280 (setq min n)
20281 (goto-char (point-min))
20282 (while (re-search-forward "^ *[^ \n]" nil t)
20283 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20284 (unless (or (= min 0) (= min 10000))
20285 (setq re (format "^ \\{%d\\}" min))
20286 (goto-char (point-min))
20287 (while (re-search-forward re nil t)
20288 (replace-match "")
20289 (end-of-line 1))
20290 min)))
20292 (defun org-fill-template (template alist)
20293 "Find each %key of ALIST in TEMPLATE and replace it."
20294 (let ((case-fold-search nil)
20295 entry key value)
20296 (setq alist (sort (copy-sequence alist)
20297 (lambda (a b) (< (length (car a)) (length (car b))))))
20298 (while (setq entry (pop alist))
20299 (setq template
20300 (replace-regexp-in-string
20301 (concat "%" (regexp-quote (car entry)))
20302 (or (cdr entry) "") template t t)))
20303 template))
20305 (defun org-base-buffer (buffer)
20306 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20307 (if (not buffer)
20308 buffer
20309 (or (buffer-base-buffer buffer)
20310 buffer)))
20312 (defun org-trim (s)
20313 "Remove whitespace at beginning and end of string."
20314 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20315 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20318 (defun org-wrap (string &optional width lines)
20319 "Wrap string to either a number of lines, or a width in characters.
20320 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20321 that costs. If there is a word longer than WIDTH, the text is actually
20322 wrapped to the length of that word.
20323 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20324 many lines, whatever width that takes.
20325 The return value is a list of lines, without newlines at the end."
20326 (let* ((words (org-split-string string "[ \t\n]+"))
20327 (maxword (apply 'max (mapcar 'org-string-width words)))
20328 w ll)
20329 (cond (width
20330 (org-do-wrap words (max maxword width)))
20331 (lines
20332 (setq w maxword)
20333 (setq ll (org-do-wrap words maxword))
20334 (if (<= (length ll) lines)
20336 (setq ll words)
20337 (while (> (length ll) lines)
20338 (setq w (1+ w))
20339 (setq ll (org-do-wrap words w)))
20340 ll))
20341 (t (error "Cannot wrap this")))))
20343 (defun org-do-wrap (words width)
20344 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20345 (let (lines line)
20346 (while words
20347 (setq line (pop words))
20348 (while (and words (< (+ (length line) (length (car words))) width))
20349 (setq line (concat line " " (pop words))))
20350 (setq lines (push line lines)))
20351 (nreverse lines)))
20353 (defun org-split-string (string &optional separators)
20354 "Splits STRING into substrings at SEPARATORS.
20355 No empty strings are returned if there are matches at the beginning
20356 and end of string."
20357 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20358 (start 0)
20359 notfirst
20360 (list nil))
20361 (while (and (string-match rexp string
20362 (if (and notfirst
20363 (= start (match-beginning 0))
20364 (< start (length string)))
20365 (1+ start) start))
20366 (< (match-beginning 0) (length string)))
20367 (setq notfirst t)
20368 (or (eq (match-beginning 0) 0)
20369 (and (eq (match-beginning 0) (match-end 0))
20370 (eq (match-beginning 0) start))
20371 (setq list
20372 (cons (substring string start (match-beginning 0))
20373 list)))
20374 (setq start (match-end 0)))
20375 (or (eq start (length string))
20376 (setq list
20377 (cons (substring string start)
20378 list)))
20379 (nreverse list)))
20381 (defun org-quote-vert (s)
20382 "Replace \"|\" with \"\\vert\"."
20383 (while (string-match "|" s)
20384 (setq s (replace-match "\\vert" t t s)))
20387 (defun org-uuidgen-p (s)
20388 "Is S an ID created by UUIDGEN?"
20389 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20391 (defun org-in-src-block-p nil
20392 "Whether point is in a code source block."
20393 (let (ov)
20394 (when (setq ov (overlays-at (point)))
20395 (memq 'org-block-background
20396 (overlay-properties
20397 (car ov))))))
20399 (defun org-context ()
20400 "Return a list of contexts of the current cursor position.
20401 If several contexts apply, all are returned.
20402 Each context entry is a list with a symbol naming the context, and
20403 two positions indicating start and end of the context. Possible
20404 contexts are:
20406 :headline anywhere in a headline
20407 :headline-stars on the leading stars in a headline
20408 :todo-keyword on a TODO keyword (including DONE) in a headline
20409 :tags on the TAGS in a headline
20410 :priority on the priority cookie in a headline
20411 :item on the first line of a plain list item
20412 :item-bullet on the bullet/number of a plain list item
20413 :checkbox on the checkbox in a plain list item
20414 :table in an org-mode table
20415 :table-special on a special filed in a table
20416 :table-table in a table.el table
20417 :clocktable in a clocktable
20418 :src-block in a source block
20419 :link on a hyperlink
20420 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20421 :target on a <<target>>
20422 :radio-target on a <<<radio-target>>>
20423 :latex-fragment on a LaTeX fragment
20424 :latex-preview on a LaTeX fragment with overlaid preview image
20426 This function expects the position to be visible because it uses font-lock
20427 faces as a help to recognize the following contexts: :table-special, :link,
20428 and :keyword."
20429 (let* ((f (get-text-property (point) 'face))
20430 (faces (if (listp f) f (list f)))
20431 (case-fold-search t)
20432 (p (point)) clist o)
20433 ;; First the large context
20434 (cond
20435 ((org-at-heading-p t)
20436 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20437 (when (progn
20438 (beginning-of-line 1)
20439 (looking-at org-todo-line-tags-regexp))
20440 (push (org-point-in-group p 1 :headline-stars) clist)
20441 (push (org-point-in-group p 2 :todo-keyword) clist)
20442 (push (org-point-in-group p 4 :tags) clist))
20443 (goto-char p)
20444 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20445 (if (looking-at "\\[#[A-Z0-9]\\]")
20446 (push (org-point-in-group p 0 :priority) clist)))
20448 ((org-at-item-p)
20449 (push (org-point-in-group p 2 :item-bullet) clist)
20450 (push (list :item (point-at-bol)
20451 (save-excursion (org-end-of-item) (point)))
20452 clist)
20453 (and (org-at-item-checkbox-p)
20454 (push (org-point-in-group p 0 :checkbox) clist)))
20456 ((org-at-table-p)
20457 (push (list :table (org-table-begin) (org-table-end)) clist)
20458 (if (memq 'org-formula faces)
20459 (push (list :table-special
20460 (previous-single-property-change p 'face)
20461 (next-single-property-change p 'face)) clist)))
20462 ((org-at-table-p 'any)
20463 (push (list :table-table) clist)))
20464 (goto-char p)
20466 (let ((case-fold-search t))
20467 ;; New the "medium" contexts: clocktables, source blocks
20468 (cond ((org-in-clocktable-p)
20469 (push (list :clocktable
20470 (and (or (looking-at "#\\+BEGIN: clocktable")
20471 (search-backward "#+BEGIN: clocktable" nil t))
20472 (match-beginning 0))
20473 (and (re-search-forward "#\\+END:?" nil t)
20474 (match-end 0))) clist))
20475 ((org-in-src-block-p)
20476 (push (list :src-block
20477 (and (or (looking-at "#\\+BEGIN_SRC")
20478 (search-backward "#+BEGIN_SRC" nil t))
20479 (match-beginning 0))
20480 (and (search-forward "#+END_SRC" nil t)
20481 (match-beginning 0))) clist))))
20482 (goto-char p)
20484 ;; Now the small context
20485 (cond
20486 ((org-at-timestamp-p)
20487 (push (org-point-in-group p 0 :timestamp) clist))
20488 ((memq 'org-link faces)
20489 (push (list :link
20490 (previous-single-property-change p 'face)
20491 (next-single-property-change p 'face)) clist))
20492 ((memq 'org-special-keyword faces)
20493 (push (list :keyword
20494 (previous-single-property-change p 'face)
20495 (next-single-property-change p 'face)) clist))
20496 ((org-at-target-p)
20497 (push (org-point-in-group p 0 :target) clist)
20498 (goto-char (1- (match-beginning 0)))
20499 (if (looking-at org-radio-target-regexp)
20500 (push (org-point-in-group p 0 :radio-target) clist))
20501 (goto-char p))
20502 ((setq o (car (delq nil
20503 (mapcar
20504 (lambda (x)
20505 (if (memq x org-latex-fragment-image-overlays) x))
20506 (overlays-at (point))))))
20507 (push (list :latex-fragment
20508 (overlay-start o) (overlay-end o)) clist)
20509 (push (list :latex-preview
20510 (overlay-start o) (overlay-end o)) clist))
20511 ((org-inside-LaTeX-fragment-p)
20512 ;; FIXME: positions wrong.
20513 (push (list :latex-fragment (point) (point)) clist)))
20515 (setq clist (nreverse (delq nil clist)))
20516 clist))
20518 ;; FIXME: Compare with at-regexp-p Do we need both?
20519 (defun org-in-regexp (re &optional nlines visually)
20520 "Check if point is inside a match of regexp.
20521 Normally only the current line is checked, but you can include NLINES extra
20522 lines both before and after point into the search.
20523 If VISUALLY is set, require that the cursor is not after the match but
20524 really on, so that the block visually is on the match."
20525 (catch 'exit
20526 (let ((pos (point))
20527 (eol (point-at-eol (+ 1 (or nlines 0))))
20528 (inc (if visually 1 0)))
20529 (save-excursion
20530 (beginning-of-line (- 1 (or nlines 0)))
20531 (while (re-search-forward re eol t)
20532 (if (and (<= (match-beginning 0) pos)
20533 (>= (+ inc (match-end 0)) pos))
20534 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20536 (defun org-at-regexp-p (regexp)
20537 "Is point inside a match of REGEXP in the current line?"
20538 (catch 'exit
20539 (save-excursion
20540 (let ((pos (point)) (end (point-at-eol)))
20541 (beginning-of-line 1)
20542 (while (re-search-forward regexp end t)
20543 (if (and (<= (match-beginning 0) pos)
20544 (>= (match-end 0) pos))
20545 (throw 'exit t)))
20546 nil))))
20548 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20549 "Non-nil when point is between matches of START-RE and END-RE.
20551 Also return a non-nil value when point is on one of the matches.
20553 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20554 buffer positions. Default values are the positions of headlines
20555 surrounding the point.
20557 The functions returns a cons cell whose car (resp. cdr) is the
20558 position before START-RE (resp. after END-RE)."
20559 (save-match-data
20560 (let ((pos (point))
20561 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20562 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20563 beg end)
20564 (save-excursion
20565 ;; Point is on a block when on START-RE or if START-RE can be
20566 ;; found before it...
20567 (and (or (org-at-regexp-p start-re)
20568 (re-search-backward start-re limit-up t))
20569 (setq beg (match-beginning 0))
20570 ;; ... and END-RE after it...
20571 (goto-char (match-end 0))
20572 (re-search-forward end-re limit-down t)
20573 (> (setq end (match-end 0)) pos)
20574 ;; ... without another START-RE in-between.
20575 (goto-char (match-beginning 0))
20576 (not (re-search-backward start-re (1+ beg) t))
20577 ;; Return value.
20578 (cons beg end))))))
20580 (defun org-in-block-p (names)
20581 "Non-nil when point belongs to a block whose name belongs to NAMES.
20583 NAMES is a list of strings containing names of blocks.
20585 Return first block name matched, or nil. Beware that in case of
20586 nested blocks, the returned name may not belong to the closest
20587 block from point."
20588 (save-match-data
20589 (catch 'exit
20590 (let ((case-fold-search t)
20591 (lim-up (save-excursion (outline-previous-heading)))
20592 (lim-down (save-excursion (outline-next-heading))))
20593 (mapc (lambda (name)
20594 (let ((n (regexp-quote name)))
20595 (when (org-between-regexps-p
20596 (concat "^[ \t]*#\\+begin_" n)
20597 (concat "^[ \t]*#\\+end_" n)
20598 lim-up lim-down)
20599 (throw 'exit n))))
20600 names))
20601 nil)))
20603 (defun org-occur-in-agenda-files (regexp &optional nlines)
20604 "Call `multi-occur' with buffers for all agenda files."
20605 (interactive "sOrg-files matching: \np")
20606 (let* ((files (org-agenda-files))
20607 (tnames (mapcar 'file-truename files))
20608 (extra org-agenda-text-search-extra-files)
20610 (when (eq (car extra) 'agenda-archives)
20611 (setq extra (cdr extra))
20612 (setq files (org-add-archive-files files)))
20613 (while (setq f (pop extra))
20614 (unless (member (file-truename f) tnames)
20615 (add-to-list 'files f 'append)
20616 (add-to-list 'tnames (file-truename f) 'append)))
20617 (multi-occur
20618 (mapcar (lambda (x)
20619 (with-current-buffer
20620 (or (get-file-buffer x) (find-file-noselect x))
20621 (widen)
20622 (current-buffer)))
20623 files)
20624 regexp)))
20626 (if (boundp 'occur-mode-find-occurrence-hook)
20627 ;; Emacs 23
20628 (add-hook 'occur-mode-find-occurrence-hook
20629 (lambda ()
20630 (when (derived-mode-p 'org-mode)
20631 (org-reveal))))
20632 ;; Emacs 22
20633 (defadvice occur-mode-goto-occurrence
20634 (after org-occur-reveal activate)
20635 (and (derived-mode-p 'org-mode) (org-reveal)))
20636 (defadvice occur-mode-goto-occurrence-other-window
20637 (after org-occur-reveal activate)
20638 (and (derived-mode-p 'org-mode) (org-reveal)))
20639 (defadvice occur-mode-display-occurrence
20640 (after org-occur-reveal activate)
20641 (when (derived-mode-p 'org-mode)
20642 (let ((pos (occur-mode-find-occurrence)))
20643 (with-current-buffer (marker-buffer pos)
20644 (save-excursion
20645 (goto-char pos)
20646 (org-reveal)))))))
20648 (defun org-occur-link-in-agenda-files ()
20649 "Create a link and search for it in the agendas.
20650 The link is not stored in `org-stored-links', it is just created
20651 for the search purpose."
20652 (interactive)
20653 (let ((link (condition-case nil
20654 (org-store-link nil)
20655 (error "Unable to create a link to here"))))
20656 (org-occur-in-agenda-files (regexp-quote link))))
20658 (defun org-uniquify (list)
20659 "Remove duplicate elements from LIST."
20660 (let (res)
20661 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20662 res))
20664 (defun org-delete-all (elts list)
20665 "Remove all elements in ELTS from LIST."
20666 (while elts
20667 (setq list (delete (pop elts) list)))
20668 list)
20670 (defun org-count (cl-item cl-seq)
20671 "Count the number of occurrences of ITEM in SEQ.
20672 Taken from `count' in cl-seq.el with all keyword arguments removed."
20673 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20674 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20675 (while (< cl-start cl-end)
20676 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20677 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20678 (setq cl-start (1+ cl-start)))
20679 cl-count))
20681 (defun org-remove-if (predicate seq)
20682 "Remove everything from SEQ that fulfills PREDICATE."
20683 (let (res e)
20684 (while seq
20685 (setq e (pop seq))
20686 (if (not (funcall predicate e)) (push e res)))
20687 (nreverse res)))
20689 (defun org-remove-if-not (predicate seq)
20690 "Remove everything from SEQ that does not fulfill PREDICATE."
20691 (let (res e)
20692 (while seq
20693 (setq e (pop seq))
20694 (if (funcall predicate e) (push e res)))
20695 (nreverse res)))
20697 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20698 "Reduce two-argument FUNCTION across SEQ.
20699 Taken from `reduce' in cl-seq.el with all keyword arguments but
20700 \":initial-value\" removed."
20701 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20702 (cadr (memq :initial-value cl-keys)))
20703 (cl-seq (pop cl-seq))
20704 (t (funcall cl-func)))))
20705 (while cl-seq
20706 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20707 cl-accum))
20709 (defun org-back-over-empty-lines ()
20710 "Move backwards over whitespace, to the beginning of the first empty line.
20711 Returns the number of empty lines passed."
20712 (let ((pos (point)))
20713 (if (cdr (assoc 'heading org-blank-before-new-entry))
20714 (skip-chars-backward " \t\n\r")
20715 (unless (eobp)
20716 (forward-line -1)))
20717 (beginning-of-line 2)
20718 (goto-char (min (point) pos))
20719 (count-lines (point) pos)))
20721 (defun org-skip-whitespace ()
20722 (skip-chars-forward " \t\n\r"))
20724 (defun org-point-in-group (point group &optional context)
20725 "Check if POINT is in match-group GROUP.
20726 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20727 match. If the match group does not exist or point is not inside it,
20728 return nil."
20729 (and (match-beginning group)
20730 (>= point (match-beginning group))
20731 (<= point (match-end group))
20732 (if context
20733 (list context (match-beginning group) (match-end group))
20734 t)))
20736 (defun org-switch-to-buffer-other-window (&rest args)
20737 "Switch to buffer in a second window on the current frame.
20738 In particular, do not allow pop-up frames.
20739 Returns the newly created buffer."
20740 (let (pop-up-frames special-display-buffer-names special-display-regexps
20741 special-display-function)
20742 (apply 'switch-to-buffer-other-window args)))
20744 (defun org-combine-plists (&rest plists)
20745 "Create a single property list from all plists in PLISTS.
20746 The process starts by copying the first list, and then setting properties
20747 from the other lists. Settings in the last list are the most significant
20748 ones and overrule settings in the other lists."
20749 (let ((rtn (copy-sequence (pop plists)))
20750 p v ls)
20751 (while plists
20752 (setq ls (pop plists))
20753 (while ls
20754 (setq p (pop ls) v (pop ls))
20755 (setq rtn (plist-put rtn p v))))
20756 rtn))
20758 (defun org-replace-escapes (string table)
20759 "Replace %-escapes in STRING with values in TABLE.
20760 TABLE is an association list with keys like \"%a\" and string values.
20761 The sequences in STRING may contain normal field width and padding information,
20762 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20763 so values can contain further %-escapes if they are define later in TABLE."
20764 (let ((tbl (copy-alist table))
20765 (case-fold-search nil)
20766 (pchg 0)
20767 e re rpl)
20768 (while (setq e (pop tbl))
20769 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20770 (when (and (cdr e) (string-match re (cdr e)))
20771 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20772 (safe "SREF"))
20773 (add-text-properties 0 3 (list 'sref sref) safe)
20774 (setcdr e (replace-match safe t t (cdr e)))))
20775 (while (string-match re string)
20776 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20777 (cdr e)))
20778 (setq string (replace-match rpl t t string))))
20779 (while (setq pchg (next-property-change pchg string))
20780 (let ((sref (get-text-property pchg 'sref string)))
20781 (when (and sref (string-match "SREF" string pchg))
20782 (setq string (replace-match sref t t string)))))
20783 string))
20785 (defun org-sublist (list start end)
20786 "Return a section of LIST, from START to END.
20787 Counting starts at 1."
20788 (let (rtn (c start))
20789 (setq list (nthcdr (1- start) list))
20790 (while (and list (<= c end))
20791 (push (pop list) rtn)
20792 (setq c (1+ c)))
20793 (nreverse rtn)))
20795 (defun org-find-base-buffer-visiting (file)
20796 "Like `find-buffer-visiting' but always return the base buffer and
20797 not an indirect buffer."
20798 (let ((buf (or (get-file-buffer file)
20799 (find-buffer-visiting file))))
20800 (if buf
20801 (or (buffer-base-buffer buf) buf)
20802 nil)))
20804 (defun org-image-file-name-regexp (&optional extensions)
20805 "Return regexp matching the file names of images.
20806 If EXTENSIONS is given, only match these."
20807 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20808 (image-file-name-regexp)
20809 (let ((image-file-name-extensions
20810 (or extensions
20811 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20812 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20813 (concat "\\."
20814 (regexp-opt (nconc (mapcar 'upcase
20815 image-file-name-extensions)
20816 image-file-name-extensions)
20818 "\\'"))))
20820 (defun org-file-image-p (file &optional extensions)
20821 "Return non-nil if FILE is an image."
20822 (save-match-data
20823 (string-match (org-image-file-name-regexp extensions) file)))
20825 (defun org-get-cursor-date ()
20826 "Return the date at cursor in as a time.
20827 This works in the calendar and in the agenda, anywhere else it just
20828 returns the current time."
20829 (let (date day defd)
20830 (cond
20831 ((eq major-mode 'calendar-mode)
20832 (setq date (calendar-cursor-to-date)
20833 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20834 ((eq major-mode 'org-agenda-mode)
20835 (setq day (get-text-property (point) 'day))
20836 (if day
20837 (setq date (calendar-gregorian-from-absolute day)
20838 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20839 (nth 2 date))))))
20840 (or defd (current-time))))
20842 (defvar org-agenda-action-marker (make-marker)
20843 "Marker pointing to the entry for the next agenda action.")
20845 (defun org-mark-entry-for-agenda-action ()
20846 "Mark the current entry as target of an agenda action.
20847 Agenda actions are actions executed from the agenda with the key `k',
20848 which make use of the date at the cursor."
20849 (interactive)
20850 (move-marker org-agenda-action-marker
20851 (save-excursion (org-back-to-heading t) (point))
20852 (current-buffer))
20853 (message
20854 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20856 (defun org-mark-subtree (&optional up)
20857 "Mark the current subtree.
20858 This puts point at the start of the current subtree, and mark at
20859 the end. If a numeric prefix UP is given, move up into the
20860 hierarchy of headlines by UP levels before marking the subtree."
20861 (interactive "P")
20862 (org-with-limited-levels
20863 (cond ((org-at-heading-p) (beginning-of-line))
20864 ((org-before-first-heading-p) (error "Not in a subtree"))
20865 (t (outline-previous-visible-heading 1))))
20866 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20867 (if (org-called-interactively-p 'any)
20868 (call-interactively 'org-mark-element)
20869 (org-mark-element)))
20872 ;;; Macros
20874 ;; Macros are expanded with `org-macro-replace-all', which relies
20875 ;; internally on `org-macro-expand'.
20877 ;; Templates for expansion are stored in the buffer-local variable
20878 ;; `org-macro-templates'. This variable is updated by
20879 ;; `org-macro-initialize-templates'.
20882 (defvar org-macro-templates nil
20883 "Alist containing all macro templates in current buffer.
20884 Associations are in the shape of (NAME . TEMPLATE) where NAME
20885 stands for macro's name and template for its replacement value,
20886 both as strings. This is an internal variable. Do not set it
20887 directly, use instead:
20889 #+MACRO: name template")
20890 (make-variable-buffer-local 'org-macro-templates)
20892 (defun org-macro-expand (macro)
20893 "Return expanded MACRO, as a string.
20894 MACRO is an object, obtained, for example, with
20895 `org-element-context'. Return nil if no template was found."
20896 (let ((template
20897 (cdr (assoc-string (org-element-property :key macro)
20898 org-macro-templates
20899 ;; Macro names are case-insensitive.
20900 t))))
20901 (when template
20902 (let ((value (replace-regexp-in-string
20903 "\\$[0-9]+"
20904 (lambda (arg)
20905 (or (nth (1- (string-to-number (substring arg 1)))
20906 (org-element-property :args macro))
20907 ;; No argument provided: remove
20908 ;; place-holder.
20909 ""))
20910 template)))
20911 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20912 (when (string-match "\\`(eval\\>" value)
20913 (setq value (eval (read value))))
20914 ;; Return string.
20915 (format "%s" (or value ""))))))
20917 (defun org-macro-replace-all ()
20918 "Replace all macros in current buffer by their expansion."
20919 (save-excursion
20920 (goto-char (point-min))
20921 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20922 (let ((object (org-element-context)))
20923 (when (eq (org-element-type object) 'macro)
20924 (let ((value (org-macro-expand object)))
20925 (when value
20926 (delete-region
20927 (org-element-property :begin object)
20928 ;; Preserve white spaces after the macro.
20929 (progn (goto-char (org-element-property :end object))
20930 (skip-chars-backward " \t")
20931 (point)))
20932 ;; Leave point before replacement in case of recursive
20933 ;; expansions.
20934 (save-excursion (insert value)))))))))
20936 (defun org-macro-initialize-templates ()
20937 "Collect macro templates defined in current buffer.
20938 Templates are stored in buffer-local variable
20939 `org-macro-templates'. In addition to buffer-defined macros, the
20940 function installs the following ones: \"property\", \"date\",
20941 \"time\". and, if appropriate, \"input-file\" and
20942 \"modification-time\"."
20943 (let ((case-fold-search t)
20944 (set-template
20945 (lambda (cell)
20946 ;; Add CELL to `org-macro-templates' if there's no
20947 ;; association matching its name already. Otherwise,
20948 ;; replace old association with the new one in that
20949 ;; variable.
20950 (let ((old-template (assoc (car cell) org-macro-templates)))
20951 (if old-template (setcdr old-template (cdr cell))
20952 (push cell org-macro-templates))))))
20953 ;; Install buffer-local macros.
20954 (org-with-wide-buffer
20955 (goto-char (point-min))
20956 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
20957 (let ((element (org-element-at-point)))
20958 (when (eq (org-element-type element) 'keyword)
20959 (let ((value (org-element-property :value element)))
20960 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
20961 (funcall set-template
20962 (cons (match-string 1 value)
20963 (or (match-string 2 value) "")))))))))
20964 ;; Install hard-coded macros.
20965 (mapc (lambda (cell) (funcall set-template cell))
20966 (list
20967 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
20968 (cons "date" "(eval (format-time-string \"$1\"))")
20969 (cons "time" "(eval (format-time-string \"$1\"))")))
20970 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
20971 (when (and visited-file (file-exists-p visited-file))
20972 (mapc (lambda (cell) (funcall set-template cell))
20973 (list
20974 (cons "input-file" (file-name-nondirectory visited-file))
20975 (cons "modification-time"
20976 (format "(eval (format-time-string \"$1\" '%s))"
20977 (prin1-to-string
20978 (nth 5 (file-attributes visited-file)))))))))))
20981 ;;; Indentation
20983 (defun org-indent-line ()
20984 "Indent line depending on context."
20985 (interactive)
20986 (let* ((pos (point))
20987 (itemp (org-at-item-p))
20988 (case-fold-search t)
20989 (org-drawer-regexp (or org-drawer-regexp "\000"))
20990 (inline-task-p (and (featurep 'org-inlinetask)
20991 (org-inlinetask-in-task-p)))
20992 (inline-re (and inline-task-p
20993 (org-inlinetask-outline-regexp)))
20994 column)
20995 (if (and orgstruct-is-++ (eq pos (point)))
20996 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20997 (indent-according-to-mode))
20998 (beginning-of-line 1)
20999 (cond
21000 ;; Headings
21001 ((looking-at org-outline-regexp) (setq column 0))
21002 ;; Included files
21003 ((looking-at "#\\+include:") (setq column 0))
21004 ;; Footnote definition
21005 ((looking-at org-footnote-definition-re) (setq column 0))
21006 ;; Literal examples
21007 ((looking-at "[ \t]*:\\( \\|$\\)")
21008 (setq column (org-get-indentation))) ; do nothing
21009 ;; Lists
21010 ((ignore-errors (goto-char (org-in-item-p)))
21011 (setq column (if itemp
21012 (org-get-indentation)
21013 (org-list-item-body-column (point))))
21014 (goto-char pos))
21015 ;; Drawers
21016 ((and (looking-at "[ \t]*:END:")
21017 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21018 (save-excursion
21019 (goto-char (1- (match-beginning 1)))
21020 (setq column (current-column))))
21021 ;; Special blocks
21022 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21023 (save-excursion
21024 (re-search-backward
21025 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21026 (setq column (org-get-indentation (match-string 0))))
21027 ((and (not (looking-at "[ \t]*#\\+begin_"))
21028 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21029 (save-excursion
21030 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21031 (setq column
21032 (cond ((equal (downcase (match-string 1)) "src")
21033 ;; src blocks: let `org-edit-src-exit' handle them
21034 (org-get-indentation))
21035 ((equal (downcase (match-string 1)) "example")
21036 (max (org-get-indentation)
21037 (org-get-indentation (match-string 0))))
21039 (org-get-indentation (match-string 0))))))
21040 ;; This line has nothing special, look at the previous relevant
21041 ;; line to compute indentation
21043 (beginning-of-line 0)
21044 (while (and (not (bobp))
21045 (not (looking-at org-drawer-regexp))
21046 ;; When point started in an inline task, do not move
21047 ;; above task starting line.
21048 (not (and inline-task-p (looking-at inline-re)))
21049 ;; Skip drawers, blocks, empty lines, verbatim,
21050 ;; comments, tables, footnotes definitions, lists,
21051 ;; inline tasks.
21052 (or (and (looking-at "[ \t]*:END:")
21053 (re-search-backward org-drawer-regexp nil t))
21054 (and (looking-at "[ \t]*#\\+end_")
21055 (re-search-backward "[ \t]*#\\+begin_"nil t))
21056 (looking-at "[ \t]*[\n:#|]")
21057 (looking-at org-footnote-definition-re)
21058 (and (ignore-errors (goto-char (org-in-item-p)))
21059 (goto-char
21060 (org-list-get-top-point (org-list-struct))))
21061 (and (not inline-task-p)
21062 (featurep 'org-inlinetask)
21063 (org-inlinetask-in-task-p)
21064 (or (org-inlinetask-goto-beginning) t))))
21065 (beginning-of-line 0))
21066 (cond
21067 ;; There was an heading above.
21068 ((looking-at "\\*+[ \t]+")
21069 (if (not org-adapt-indentation)
21070 (setq column 0)
21071 (goto-char (match-end 0))
21072 (setq column (current-column))))
21073 ;; A drawer had started and is unfinished
21074 ((looking-at org-drawer-regexp)
21075 (goto-char (1- (match-beginning 1)))
21076 (setq column (current-column)))
21077 ;; Else, nothing noticeable found: get indentation and go on.
21078 (t (setq column (org-get-indentation))))))
21079 ;; Now apply indentation and move cursor accordingly
21080 (goto-char pos)
21081 (if (<= (current-column) (current-indentation))
21082 (org-indent-line-to column)
21083 (save-excursion (org-indent-line-to column)))
21084 ;; Special polishing for properties, see `org-property-format'
21085 (setq column (current-column))
21086 (beginning-of-line 1)
21087 (if (looking-at
21088 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21089 (replace-match (concat (match-string 1)
21090 (format org-property-format
21091 (match-string 2) (match-string 3)))
21092 t t))
21093 (org-move-to-column column))))
21095 (defun org-indent-drawer ()
21096 "Indent the drawer at point."
21097 (interactive)
21098 (let ((p (point))
21099 (e (and (save-excursion (re-search-forward ":END:" nil t))
21100 (match-end 0)))
21101 (folded
21102 (save-excursion
21103 (end-of-line)
21104 (when (overlays-at (point))
21105 (member 'invisible (overlay-properties
21106 (car (overlays-at (point)))))))))
21107 (when folded (org-cycle))
21108 (indent-for-tab-command)
21109 (while (and (move-beginning-of-line 2) (< (point) e))
21110 (indent-for-tab-command))
21111 (goto-char p)
21112 (when folded (org-cycle)))
21113 (message "Drawer at point indented"))
21115 (defun org-indent-block ()
21116 "Indent the block at point."
21117 (interactive)
21118 (let ((p (point))
21119 (case-fold-search t)
21120 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21121 (match-end 0)))
21122 (folded
21123 (save-excursion
21124 (end-of-line)
21125 (when (overlays-at (point))
21126 (member 'invisible (overlay-properties
21127 (car (overlays-at (point)))))))))
21128 (when folded (org-cycle))
21129 (indent-for-tab-command)
21130 (while (and (move-beginning-of-line 2) (< (point) e))
21131 (indent-for-tab-command))
21132 (goto-char p)
21133 (when folded (org-cycle)))
21134 (message "Block at point indented"))
21136 (defun org-indent-region (start end)
21137 "Indent region."
21138 (interactive "r")
21139 (save-excursion
21140 (let ((line-end (org-current-line end)))
21141 (goto-char start)
21142 (while (< (org-current-line) line-end)
21143 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21144 (t (call-interactively 'org-indent-line)))
21145 (move-beginning-of-line 2)))))
21148 ;;; Filling
21150 ;; We use our own fill-paragraph and auto-fill functions.
21152 ;; `org-fill-paragraph' relies on adaptive filling and context
21153 ;; checking. Appropriate `fill-prefix' is computed with
21154 ;; `org-adaptive-fill-function'.
21156 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21157 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21158 ;; `org-adaptive-fill-function' value. Internally,
21159 ;; `org-comment-line-break-function' breaks the line.
21161 ;; `org-setup-filling' installs filling and auto-filling related
21162 ;; variables during `org-mode' initialization.
21164 (defun org-setup-filling ()
21165 (interactive)
21166 ;; Prevent auto-fill from inserting unwanted new items.
21167 (when (boundp 'fill-nobreak-predicate)
21168 (org-set-local
21169 'fill-nobreak-predicate
21170 (org-uniquify
21171 (append fill-nobreak-predicate
21172 '(org-fill-paragraph-separate-nobreak-p
21173 org-fill-line-break-nobreak-p)))))
21174 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21175 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21176 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21177 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21179 (defvar org-element-paragraph-separate) ; org-element.el
21180 (defun org-fill-paragraph-separate-nobreak-p ()
21181 "Non-nil when a line break at point would insert a new item."
21182 (looking-at (substring org-element-paragraph-separate 1)))
21184 (defun org-fill-line-break-nobreak-p ()
21185 "Non-nil when a line break at point would create an Org line break."
21186 (save-excursion
21187 (skip-chars-backward "[ \t]")
21188 (skip-chars-backward "\\\\")
21189 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21191 (declare-function message-in-body-p "message" ())
21192 (defvar org-element--affiliated-re) ; From org-element.el
21193 (defun org-adaptive-fill-function ()
21194 "Compute a fill prefix for the current line.
21195 Return fill prefix, as a string, or nil if current line isn't
21196 meant to be filled."
21197 (org-with-wide-buffer
21198 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21199 ;; FIXME: This is really the job of orgstruct++-mode
21200 (let* ((p (line-beginning-position))
21201 (element (save-excursion (beginning-of-line)
21202 (org-element-at-point)))
21203 (type (org-element-type element))
21204 (post-affiliated
21205 (save-excursion
21206 (goto-char (org-element-property :begin element))
21207 (while (looking-at org-element--affiliated-re) (forward-line))
21208 (point))))
21209 (unless (< p post-affiliated)
21210 (case type
21211 (comment (looking-at "[ \t]*# ?") (match-string 0))
21212 (footnote-definition "")
21213 ((item plain-list)
21214 (make-string (org-list-item-body-column post-affiliated) ? ))
21215 (paragraph
21216 ;; Fill prefix is usually the same as the current line,
21217 ;; except if the paragraph is at the beginning of an item.
21218 (let ((parent (org-element-property :parent element)))
21219 (cond ((eq (org-element-type parent) 'item)
21220 (make-string (org-list-item-body-column
21221 (org-element-property :begin parent))
21222 ? ))
21223 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21224 (match-string 0))
21225 (t ""))))
21226 (comment-block
21227 ;; Only fill contents if P is within block boundaries.
21228 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21229 (forward-line)
21230 (point)))
21231 (cend (save-excursion
21232 (goto-char (org-element-property :end element))
21233 (skip-chars-backward " \r\t\n")
21234 (line-beginning-position))))
21235 (when (and (>= p cbeg) (< p cend))
21236 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21237 (match-string 0)
21238 ""))))))))))
21240 (declare-function message-goto-body "message" ())
21241 (defvar message-cite-prefix-regexp) ; From message.el
21242 (defvar org-element-all-objects) ; From org-element.el
21243 (defun org-fill-paragraph (&optional justify)
21244 "Fill element at point, when applicable.
21246 This function only applies to comment blocks, comments, example
21247 blocks and paragraphs. Also, as a special case, re-align table
21248 when point is at one.
21250 If JUSTIFY is non-nil (interactively, with prefix argument),
21251 justify as well. If `sentence-end-double-space' is non-nil, then
21252 period followed by one space does not end a sentence, so don't
21253 break a line there. The variable `fill-column' controls the
21254 width for filling.
21256 For convenience, when point is at a plain list, an item or
21257 a footnote definition, try to fill the first paragraph within."
21258 ;; Falls back on message-fill-paragraph when necessary
21259 (interactive)
21260 (if (and (derived-mode-p 'message-mode)
21261 (or (not (message-in-body-p))
21262 (save-excursion (move-beginning-of-line 1)
21263 (looking-at message-cite-prefix-regexp))))
21264 (let ((fill-paragraph-function
21265 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21266 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21267 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21268 (paragraph-separate
21269 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21270 (fill-paragraph nil))
21271 (save-excursion
21272 ;; Move to end of line in order to get the first paragraph
21273 ;; within a plain list or a footnote definition.
21274 (end-of-line)
21275 (let ((element (org-element-at-point)))
21276 ;; First check if point is in a blank line at the beginning of
21277 ;; the buffer. In that case, ignore filling.
21278 (if (< (point) (org-element-property :begin element)) t
21279 (case (org-element-type element)
21280 ;; Align Org tables, leave table.el tables as-is.
21281 (table-row (org-table-align) t)
21282 (table
21283 (when (eq (org-element-property :type element) 'org)
21284 (org-table-align))
21286 (paragraph
21287 ;; Paragraphs may contain `line-break' type objects.
21288 (let ((beg (max (point-min)
21289 (org-element-property :contents-begin element)))
21290 (end (min (point-max)
21291 (org-element-property :contents-end element))))
21292 ;; Do nothing if point is at an affiliated keyword.
21293 (if (< (point) beg) t
21294 (when (derived-mode-p 'message-mode)
21295 ;; In `message-mode', do not fill following
21296 ;; citation in current paragraph nor text before
21297 ;; message body.
21298 (let ((body-start (save-excursion (message-goto-body))))
21299 (when body-start (setq beg (max body-start beg))))
21300 (when (save-excursion
21301 (re-search-forward
21302 (concat "^" message-cite-prefix-regexp) end t))
21303 (setq end (match-beginning 0))))
21304 ;; Fill paragraph, taking line breaks into
21305 ;; consideration. For that, slice the paragraph
21306 ;; using line breaks as separators, and fill the
21307 ;; parts in reverse order to avoid messing with
21308 ;; markers.
21309 (save-excursion
21310 (goto-char end)
21311 (mapc
21312 (lambda (pos)
21313 (fill-region-as-paragraph pos (point) justify)
21314 (goto-char pos))
21315 ;; Find the list of ending positions for line
21316 ;; breaks in the current paragraph. Add paragraph
21317 ;; beginning to include first slice.
21318 (nreverse
21319 (cons
21321 (org-element-map
21322 (org-element--parse-objects
21323 beg end nil org-element-all-objects)
21324 'line-break
21325 (lambda (lb) (org-element-property :end lb)))))))
21326 t)))
21327 ;; Contents of `comment-block' type elements should be
21328 ;; filled as plain text, but only if point is within block
21329 ;; markers.
21330 (comment-block
21331 (let* ((case-fold-search t)
21332 (beg (save-excursion
21333 (goto-char (org-element-property :begin element))
21334 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21335 (forward-line)
21336 (point)))
21337 (end (save-excursion
21338 (goto-char (org-element-property :end element))
21339 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21340 (line-beginning-position))))
21341 (when (and (>= (point) beg) (< (point) end))
21342 (fill-region-as-paragraph
21343 (save-excursion
21344 (end-of-line)
21345 (re-search-backward "^[ \t]*$" beg 'move)
21346 (line-beginning-position))
21347 (save-excursion
21348 (beginning-of-line)
21349 (re-search-forward "^[ \t]*$" end 'move)
21350 (line-beginning-position))
21351 justify)))
21353 ;; Fill comments.
21354 (comment (fill-comment-paragraph justify))
21355 ;; Ignore every other element.
21356 (otherwise t)))))))
21358 (defun org-auto-fill-function ()
21359 "Auto-fill function."
21360 ;; Check if auto-filling is meaningful.
21361 (let ((fc (current-fill-column)))
21362 (when (and fc (> (current-column) fc))
21363 (let ((fill-prefix (org-adaptive-fill-function)))
21364 (when fill-prefix (do-auto-fill))))))
21366 (defun org-comment-line-break-function (&optional soft)
21367 "Break line at point and indent, continuing comment if within one.
21368 The inserted newline is marked hard if variable
21369 `use-hard-newlines' is true, unless optional argument SOFT is
21370 non-nil."
21371 (if soft (insert-and-inherit ?\n) (newline 1))
21372 (save-excursion (forward-char -1) (delete-horizontal-space))
21373 (delete-horizontal-space)
21374 (indent-to-left-margin)
21375 (insert-before-markers-and-inherit fill-prefix))
21378 ;;; Comments
21380 ;; Org comments syntax is quite complex. It requires the entire line
21381 ;; to be just a comment. Also, even with the right syntax at the
21382 ;; beginning of line, some some elements (i.e. verse-block or
21383 ;; example-block) don't accept comments. Usual Emacs comment commands
21384 ;; cannot cope with those requirements. Therefore, Org replaces them.
21386 ;; Org still relies on `comment-dwim', but cannot trust
21387 ;; `comment-only-p'. So, `comment-region-function' and
21388 ;; `uncomment-region-function' both point
21389 ;; to`org-comment-or-uncomment-region'. Eventually,
21390 ;; `org-insert-comment' takes care of insertion of comments at the
21391 ;; beginning of line.
21393 ;; `org-setup-comments-handling' install comments related variables
21394 ;; during `org-mode' initialization.
21396 (defun org-setup-comments-handling ()
21397 (interactive)
21398 (org-set-local 'comment-use-syntax nil)
21399 (org-set-local 'comment-start "# ")
21400 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21401 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21402 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21403 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21405 (defun org-insert-comment ()
21406 "Insert an empty comment above current line.
21407 If the line is empty, insert comment at its beginning."
21408 (beginning-of-line)
21409 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21410 (org-indent-line)
21411 (insert "# "))
21413 (defvar comment-empty-lines) ; From newcomment.el.
21414 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21415 "Comment or uncomment each non-blank line in the region.
21416 Uncomment each non-blank line between BEG and END if it only
21417 contains commented lines. Otherwise, comment them."
21418 (save-restriction
21419 ;; Restrict region
21420 (narrow-to-region (save-excursion (goto-char beg)
21421 (skip-chars-forward " \r\t\n" end)
21422 (line-beginning-position))
21423 (save-excursion (goto-char end)
21424 (skip-chars-backward " \r\t\n" beg)
21425 (line-end-position)))
21426 (let ((uncommentp
21427 ;; UNCOMMENTP is non-nil when every non blank line between
21428 ;; BEG and END is a comment.
21429 (save-excursion
21430 (goto-char (point-min))
21431 (while (and (not (eobp))
21432 (let ((element (org-element-at-point)))
21433 (and (eq (org-element-type element) 'comment)
21434 (goto-char (min (point-max)
21435 (org-element-property
21436 :end element)))))))
21437 (eobp))))
21438 (if uncommentp
21439 ;; Only blank lines and comments in region: uncomment it.
21440 (save-excursion
21441 (goto-char (point-min))
21442 (while (not (eobp))
21443 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21444 (replace-match "" nil nil nil 1))
21445 (forward-line)))
21446 ;; Comment each line in region.
21447 (let ((min-indent (point-max)))
21448 ;; First find the minimum indentation across all lines.
21449 (save-excursion
21450 (goto-char (point-min))
21451 (while (and (not (eobp)) (not (zerop min-indent)))
21452 (unless (looking-at "[ \t]*$")
21453 (setq min-indent (min min-indent (current-indentation))))
21454 (forward-line)))
21455 ;; Then loop over all lines.
21456 (save-excursion
21457 (goto-char (point-min))
21458 (while (not (eobp))
21459 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21460 (org-move-to-column min-indent t)
21461 (insert comment-start))
21462 (forward-line))))))))
21465 ;;; Other stuff.
21467 (defun org-toggle-fixed-width-section (arg)
21468 "Toggle the fixed-width export.
21469 If there is no active region, the QUOTE keyword at the current headline is
21470 inserted or removed. When present, it causes the text between this headline
21471 and the next to be exported as fixed-width text, and unmodified.
21472 If there is an active region, this command adds or removes a colon as the
21473 first character of this line. If the first character of a line is a colon,
21474 this line is also exported in fixed-width font."
21475 (interactive "P")
21476 (let* ((cc 0)
21477 (regionp (org-region-active-p))
21478 (beg (if regionp (region-beginning) (point)))
21479 (end (if regionp (region-end)))
21480 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21481 (case-fold-search nil)
21482 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21483 off)
21484 (if regionp
21485 (save-excursion
21486 (goto-char beg)
21487 (setq cc (current-column))
21488 (beginning-of-line 1)
21489 (setq off (looking-at re))
21490 (while (> nlines 0)
21491 (setq nlines (1- nlines))
21492 (beginning-of-line 1)
21493 (cond
21494 (arg
21495 (org-move-to-column cc t)
21496 (insert ": \n")
21497 (forward-line -1))
21498 ((and off (looking-at re))
21499 (replace-match "" t t nil 1))
21500 ((not off) (org-move-to-column cc t) (insert ": ")))
21501 (forward-line 1)))
21502 (save-excursion
21503 (org-back-to-heading)
21504 (cond
21505 ((looking-at (format org-heading-keyword-regexp-format
21506 org-quote-string))
21507 (goto-char (match-end 1))
21508 (looking-at (concat " +" org-quote-string))
21509 (replace-match "" t t)
21510 (when (eolp) (insert " ")))
21511 ((looking-at org-outline-regexp)
21512 (goto-char (match-end 0))
21513 (insert org-quote-string " ")))))))
21515 (defun org-reftex-citation ()
21516 "Use reftex-citation to insert a citation into the buffer.
21517 This looks for a line like
21519 #+BIBLIOGRAPHY: foo plain option:-d
21521 and derives from it that foo.bib is the bibliography file relevant
21522 for this document. It then installs the necessary environment for RefTeX
21523 to work in this buffer and calls `reftex-citation' to insert a citation
21524 into the buffer.
21526 Export of such citations to both LaTeX and HTML is handled by the contributed
21527 package org-exp-bibtex by Taru Karttunen."
21528 (interactive)
21529 (let ((reftex-docstruct-symbol 'rds)
21530 (reftex-cite-format "\\cite{%l}")
21531 rds bib)
21532 (save-excursion
21533 (save-restriction
21534 (widen)
21535 (let ((case-fold-search t)
21536 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21537 (if (not (save-excursion
21538 (or (re-search-forward re nil t)
21539 (re-search-backward re nil t))))
21540 (error "No bibliography defined in file")
21541 (setq bib (concat (match-string 1) ".bib")
21542 rds (list (list 'bib bib)))))))
21543 (call-interactively 'reftex-citation)))
21545 ;;;; Functions extending outline functionality
21547 (defun org-beginning-of-line (&optional arg)
21548 "Go to the beginning of the current line. If that is invisible, continue
21549 to a visible line beginning. This makes the function of C-a more intuitive.
21550 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21551 first attempt, and only move to after the tags when the cursor is already
21552 beyond the end of the headline."
21553 (interactive "P")
21554 (let ((pos (point))
21555 (special (if (consp org-special-ctrl-a/e)
21556 (car org-special-ctrl-a/e)
21557 org-special-ctrl-a/e))
21558 refpos)
21559 (if (org-bound-and-true-p line-move-visual)
21560 (beginning-of-visual-line 1)
21561 (beginning-of-line 1))
21562 (if (and arg (fboundp 'move-beginning-of-line))
21563 (call-interactively 'move-beginning-of-line)
21564 (if (bobp)
21566 (backward-char 1)
21567 (if (org-truely-invisible-p)
21568 (while (and (not (bobp)) (org-truely-invisible-p))
21569 (backward-char 1)
21570 (beginning-of-line 1))
21571 (forward-char 1))))
21572 (when special
21573 (cond
21574 ((and (looking-at org-complex-heading-regexp)
21575 (= (char-after (match-end 1)) ?\ ))
21576 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21577 (point-at-eol)))
21578 (goto-char
21579 (if (eq special t)
21580 (cond ((> pos refpos) refpos)
21581 ((= pos (point)) refpos)
21582 (t (point)))
21583 (cond ((> pos (point)) (point))
21584 ((not (eq last-command this-command)) (point))
21585 (t refpos)))))
21586 ((org-at-item-p)
21587 ;; Being at an item and not looking at an the item means point
21588 ;; was previously moved to beginning of a visual line, which
21589 ;; doesn't contain the item. Therefore, do nothing special,
21590 ;; just stay here.
21591 (when (looking-at org-list-full-item-re)
21592 ;; Set special position at first white space character after
21593 ;; bullet, and check-box, if any.
21594 (let ((after-bullet
21595 (let ((box (match-end 3)))
21596 (if (not box) (match-end 1)
21597 (let ((after (char-after box)))
21598 (if (and after (= after ? )) (1+ box) box))))))
21599 ;; Special case: Move point to special position when
21600 ;; currently after it or at beginning of line.
21601 (if (eq special t)
21602 (when (or (> pos after-bullet) (= (point) pos))
21603 (goto-char after-bullet))
21604 ;; Reversed case: Move point to special position when
21605 ;; point was already at beginning of line and command is
21606 ;; repeated.
21607 (when (and (= (point) pos) (eq last-command this-command))
21608 (goto-char after-bullet))))))))
21609 (org-no-warnings
21610 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21612 (defun org-end-of-line (&optional arg)
21613 "Go to the end of the line.
21614 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21615 first attempt, and only move to after the tags when the cursor is already
21616 beyond the end of the headline."
21617 (interactive "P")
21618 (let ((special (if (consp org-special-ctrl-a/e)
21619 (cdr org-special-ctrl-a/e)
21620 org-special-ctrl-a/e)))
21621 (cond
21622 ((or (not special) arg
21623 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21624 (call-interactively
21625 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21626 ((fboundp 'move-end-of-line) 'move-end-of-line)
21627 (t 'end-of-line))))
21628 ((org-at-heading-p)
21629 (let ((pos (point)))
21630 (beginning-of-line 1)
21631 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21632 (if (eq special t)
21633 (if (or (< pos (match-beginning 1))
21634 (= pos (match-end 0)))
21635 (goto-char (match-beginning 1))
21636 (goto-char (match-end 0)))
21637 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21638 (goto-char (match-end 0))
21639 (goto-char (match-beginning 1))))
21640 (call-interactively (if (fboundp 'move-end-of-line)
21641 'move-end-of-line
21642 'end-of-line)))))
21643 ((org-at-drawer-p)
21644 (move-end-of-line 1)
21645 (when (overlays-at (1- (point))) (backward-char 1)))
21646 ;; At an item: Move before any hidden text.
21647 (t (call-interactively
21648 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21649 ((fboundp 'move-end-of-line) 'move-end-of-line)
21650 (t 'end-of-line)))))
21651 (org-no-warnings
21652 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21654 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21655 (define-key org-mode-map "\C-e" 'org-end-of-line)
21657 (defun org-backward-sentence (&optional arg)
21658 "Go to beginning of sentence, or beginning of table field.
21659 This will call `backward-sentence' or `org-table-beginning-of-field',
21660 depending on context."
21661 (interactive "P")
21662 (cond
21663 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21664 (t (call-interactively 'backward-sentence))))
21666 (defun org-forward-sentence (&optional arg)
21667 "Go to end of sentence, or end of table field.
21668 This will call `forward-sentence' or `org-table-end-of-field',
21669 depending on context."
21670 (interactive "P")
21671 (cond
21672 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21673 (t (call-interactively 'forward-sentence))))
21675 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21676 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21678 (defun org-kill-line (&optional arg)
21679 "Kill line, to tags or end of line."
21680 (interactive "P")
21681 (cond
21682 ((or (not org-special-ctrl-k)
21683 (bolp)
21684 (not (org-at-heading-p)))
21685 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21686 org-ctrl-k-protect-subtree)
21687 (if (or (eq org-ctrl-k-protect-subtree 'error)
21688 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21689 (error "C-k aborted - would kill hidden subtree")))
21690 (call-interactively
21691 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21692 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21693 (kill-region (point) (match-beginning 1))
21694 (org-set-tags nil t))
21695 (t (kill-region (point) (point-at-eol)))))
21697 (define-key org-mode-map "\C-k" 'org-kill-line)
21699 (defun org-yank (&optional arg)
21700 "Yank. If the kill is a subtree, treat it specially.
21701 This command will look at the current kill and check if is a single
21702 subtree, or a series of subtrees[1]. If it passes the test, and if the
21703 cursor is at the beginning of a line or after the stars of a currently
21704 empty headline, then the yank is handled specially. How exactly depends
21705 on the value of the following variables, both set by default.
21707 org-yank-folded-subtrees
21708 When set, the subtree(s) will be folded after insertion, but only
21709 if doing so would now swallow text after the yanked text.
21711 org-yank-adjusted-subtrees
21712 When set, the subtree will be promoted or demoted in order to
21713 fit into the local outline tree structure, which means that the level
21714 will be adjusted so that it becomes the smaller one of the two
21715 *visible* surrounding headings.
21717 Any prefix to this command will cause `yank' to be called directly with
21718 no special treatment. In particular, a simple \\[universal-argument] prefix \
21719 will just
21720 plainly yank the text as it is.
21722 \[1] The test checks if the first non-white line is a heading
21723 and if there are no other headings with fewer stars."
21724 (interactive "P")
21725 (org-yank-generic 'yank arg))
21727 (defun org-yank-generic (command arg)
21728 "Perform some yank-like command.
21730 This function implements the behavior described in the `org-yank'
21731 documentation. However, it has been generalized to work for any
21732 interactive command with similar behavior."
21734 ;; pretend to be command COMMAND
21735 (setq this-command command)
21737 (if arg
21738 (call-interactively command)
21740 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21741 (and (org-kill-is-subtree-p)
21742 (or (bolp)
21743 (and (looking-at "[ \t]*$")
21744 (string-match
21745 "\\`\\*+\\'"
21746 (buffer-substring (point-at-bol) (point)))))))
21747 swallowp)
21748 (cond
21749 ((and subtreep org-yank-folded-subtrees)
21750 (let ((beg (point))
21751 end)
21752 (if (and subtreep org-yank-adjusted-subtrees)
21753 (org-paste-subtree nil nil 'for-yank)
21754 (call-interactively command))
21756 (setq end (point))
21757 (goto-char beg)
21758 (when (and (bolp) subtreep
21759 (not (setq swallowp
21760 (org-yank-folding-would-swallow-text beg end))))
21761 (org-with-limited-levels
21762 (or (looking-at org-outline-regexp)
21763 (re-search-forward org-outline-regexp-bol end t))
21764 (while (and (< (point) end) (looking-at org-outline-regexp))
21765 (hide-subtree)
21766 (org-cycle-show-empty-lines 'folded)
21767 (condition-case nil
21768 (outline-forward-same-level 1)
21769 (error (goto-char end))))))
21770 (when swallowp
21771 (message
21772 "Inserted text not folded because that would swallow text"))
21774 (goto-char end)
21775 (skip-chars-forward " \t\n\r")
21776 (beginning-of-line 1)
21777 (push-mark beg 'nomsg)))
21778 ((and subtreep org-yank-adjusted-subtrees)
21779 (let ((beg (point-at-bol)))
21780 (org-paste-subtree nil nil 'for-yank)
21781 (push-mark beg 'nomsg)))
21783 (call-interactively command))))))
21785 (defun org-yank-folding-would-swallow-text (beg end)
21786 "Would hide-subtree at BEG swallow any text after END?"
21787 (let (level)
21788 (org-with-limited-levels
21789 (save-excursion
21790 (goto-char beg)
21791 (when (or (looking-at org-outline-regexp)
21792 (re-search-forward org-outline-regexp-bol end t))
21793 (setq level (org-outline-level)))
21794 (goto-char end)
21795 (skip-chars-forward " \t\r\n\v\f")
21796 (if (or (eobp)
21797 (and (bolp) (looking-at org-outline-regexp)
21798 (<= (org-outline-level) level)))
21799 nil ; Nothing would be swallowed
21800 t))))) ; something would swallow
21802 (define-key org-mode-map "\C-y" 'org-yank)
21804 (defun org-truely-invisible-p ()
21805 "Check if point is at a character currently not visible.
21806 This version does not only check the character property, but also
21807 `visible-mode'."
21808 ;; Early versions of noutline don't have `outline-invisible-p'.
21809 (if (org-bound-and-true-p visible-mode)
21811 (outline-invisible-p)))
21813 (defun org-invisible-p2 ()
21814 "Check if point is at a character currently not visible."
21815 (save-excursion
21816 (if (and (eolp) (not (bobp))) (backward-char 1))
21817 ;; Early versions of noutline don't have `outline-invisible-p'.
21818 (outline-invisible-p)))
21820 (defun org-back-to-heading (&optional invisible-ok)
21821 "Call `outline-back-to-heading', but provide a better error message."
21822 (condition-case nil
21823 (outline-back-to-heading invisible-ok)
21824 (error (error "Before first headline at position %d in buffer %s"
21825 (point) (current-buffer)))))
21827 (defun org-before-first-heading-p ()
21828 "Before first heading?"
21829 (save-excursion
21830 (end-of-line)
21831 (null (re-search-backward org-outline-regexp-bol nil t))))
21833 (defun org-at-heading-p (&optional ignored)
21834 (outline-on-heading-p t))
21835 ;; Compatibility alias with Org versions < 7.8.03
21836 (defalias 'org-on-heading-p 'org-at-heading-p)
21838 (defun org-at-comment-p nil
21839 "Is cursor in a line starting with a # character?"
21840 (save-excursion
21841 (beginning-of-line)
21842 (looking-at "^#")))
21844 (defun org-at-drawer-p nil
21845 "Is cursor at a drawer keyword?"
21846 (save-excursion
21847 (move-beginning-of-line 1)
21848 (looking-at org-drawer-regexp)))
21850 (defun org-at-block-p nil
21851 "Is cursor at a block keyword?"
21852 (save-excursion
21853 (move-beginning-of-line 1)
21854 (looking-at org-block-regexp)))
21856 (defun org-point-at-end-of-empty-headline ()
21857 "If point is at the end of an empty headline, return t, else nil.
21858 If the heading only contains a TODO keyword, it is still still considered
21859 empty."
21860 (and (looking-at "[ \t]*$")
21861 (when org-todo-line-regexp
21862 (save-excursion
21863 (beginning-of-line 1)
21864 (let ((case-fold-search nil))
21865 (looking-at org-todo-line-regexp)
21866 (string= (match-string 3) ""))))))
21868 (defun org-at-heading-or-item-p ()
21869 (or (org-at-heading-p) (org-at-item-p)))
21871 (defun org-at-target-p ()
21872 (or (org-in-regexp org-radio-target-regexp)
21873 (org-in-regexp org-target-regexp)))
21874 ;; Compatibility alias with Org versions < 7.8.03
21875 (defalias 'org-on-target-p 'org-at-target-p)
21877 (defun org-up-heading-all (arg)
21878 "Move to the heading line of which the present line is a subheading.
21879 This function considers both visible and invisible heading lines.
21880 With argument, move up ARG levels."
21881 (if (fboundp 'outline-up-heading-all)
21882 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21883 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21885 (defun org-up-heading-safe ()
21886 "Move to the heading line of which the present line is a subheading.
21887 This version will not throw an error. It will return the level of the
21888 headline found, or nil if no higher level is found.
21890 Also, this function will be a lot faster than `outline-up-heading',
21891 because it relies on stars being the outline starters. This can really
21892 make a significant difference in outlines with very many siblings."
21893 (let (start-level re)
21894 (org-back-to-heading t)
21895 (setq start-level (funcall outline-level))
21896 (if (equal start-level 1)
21898 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21899 (if (re-search-backward re nil t)
21900 (funcall outline-level)))))
21902 (defun org-first-sibling-p ()
21903 "Is this heading the first child of its parents?"
21904 (interactive)
21905 (let ((re org-outline-regexp-bol)
21906 level l)
21907 (unless (org-at-heading-p t)
21908 (error "Not at a heading"))
21909 (setq level (funcall outline-level))
21910 (save-excursion
21911 (if (not (re-search-backward re nil t))
21913 (setq l (funcall outline-level))
21914 (< l level)))))
21916 (defun org-goto-sibling (&optional previous)
21917 "Goto the next sibling, even if it is invisible.
21918 When PREVIOUS is set, go to the previous sibling instead. Returns t
21919 when a sibling was found. When none is found, return nil and don't
21920 move point."
21921 (let ((fun (if previous 're-search-backward 're-search-forward))
21922 (pos (point))
21923 (re org-outline-regexp-bol)
21924 level l)
21925 (when (condition-case nil (org-back-to-heading t) (error nil))
21926 (setq level (funcall outline-level))
21927 (catch 'exit
21928 (or previous (forward-char 1))
21929 (while (funcall fun re nil t)
21930 (setq l (funcall outline-level))
21931 (when (< l level) (goto-char pos) (throw 'exit nil))
21932 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21933 (goto-char pos)
21934 nil))))
21936 (defun org-show-siblings ()
21937 "Show all siblings of the current headline."
21938 (save-excursion
21939 (while (org-goto-sibling) (org-flag-heading nil)))
21940 (save-excursion
21941 (while (org-goto-sibling 'previous)
21942 (org-flag-heading nil))))
21944 (defun org-goto-first-child ()
21945 "Goto the first child, even if it is invisible.
21946 Return t when a child was found. Otherwise don't move point and
21947 return nil."
21948 (let (level (pos (point)) (re org-outline-regexp-bol))
21949 (when (condition-case nil (org-back-to-heading t) (error nil))
21950 (setq level (outline-level))
21951 (forward-char 1)
21952 (if (and (re-search-forward re nil t) (> (outline-level) level))
21953 (progn (goto-char (match-beginning 0)) t)
21954 (goto-char pos) nil))))
21956 (defun org-show-hidden-entry ()
21957 "Show an entry where even the heading is hidden."
21958 (save-excursion
21959 (org-show-entry)))
21961 (defun org-flag-heading (flag &optional entry)
21962 "Flag the current heading. FLAG non-nil means make invisible.
21963 When ENTRY is non-nil, show the entire entry."
21964 (save-excursion
21965 (org-back-to-heading t)
21966 ;; Check if we should show the entire entry
21967 (if entry
21968 (progn
21969 (org-show-entry)
21970 (save-excursion
21971 (and (outline-next-heading)
21972 (org-flag-heading nil))))
21973 (outline-flag-region (max (point-min) (1- (point)))
21974 (save-excursion (outline-end-of-heading) (point))
21975 flag))))
21977 (defun org-get-next-sibling ()
21978 "Move to next heading of the same level, and return point.
21979 If there is no such heading, return nil.
21980 This is like outline-next-sibling, but invisible headings are ok."
21981 (let ((level (funcall outline-level)))
21982 (outline-next-heading)
21983 (while (and (not (eobp)) (> (funcall outline-level) level))
21984 (outline-next-heading))
21985 (if (or (eobp) (< (funcall outline-level) level))
21987 (point))))
21989 (defun org-get-last-sibling ()
21990 "Move to previous heading of the same level, and return point.
21991 If there is no such heading, return nil."
21992 (let ((opoint (point))
21993 (level (funcall outline-level)))
21994 (outline-previous-heading)
21995 (when (and (/= (point) opoint) (outline-on-heading-p t))
21996 (while (and (> (funcall outline-level) level)
21997 (not (bobp)))
21998 (outline-previous-heading))
21999 (if (< (funcall outline-level) level)
22001 (point)))))
22003 (defun org-end-of-subtree (&optional invisible-OK to-heading)
22004 ;; This contains an exact copy of the original function, but it uses
22005 ;; `org-back-to-heading', to make it work also in invisible
22006 ;; trees. And is uses an invisible-OK argument.
22007 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22008 ;; Furthermore, when used inside Org, finding the end of a large subtree
22009 ;; with many children and grandchildren etc, this can be much faster
22010 ;; than the outline version.
22011 (org-back-to-heading invisible-OK)
22012 (let ((first t)
22013 (level (funcall outline-level)))
22014 (if (and (derived-mode-p 'org-mode) (< level 1000))
22015 ;; A true heading (not a plain list item), in Org-mode
22016 ;; This means we can easily find the end by looking
22017 ;; only for the right number of stars. Using a regexp to do
22018 ;; this is so much faster than using a Lisp loop.
22019 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22020 (forward-char 1)
22021 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22022 ;; something else, do it the slow way
22023 (while (and (not (eobp))
22024 (or first (> (funcall outline-level) level)))
22025 (setq first nil)
22026 (outline-next-heading)))
22027 (unless to-heading
22028 (if (memq (preceding-char) '(?\n ?\^M))
22029 (progn
22030 ;; Go to end of line before heading
22031 (forward-char -1)
22032 (if (memq (preceding-char) '(?\n ?\^M))
22033 ;; leave blank line before heading
22034 (forward-char -1))))))
22035 (point))
22037 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22038 "Use Org version in org-mode, for dramatic speed-up."
22039 (if (derived-mode-p 'org-mode)
22040 (progn
22041 (org-end-of-subtree nil t)
22042 (unless (eobp) (backward-char 1)))
22043 ad-do-it))
22045 (defun org-end-of-meta-data-and-drawers ()
22046 "Jump to the first text after meta data and drawers in the current entry.
22047 This will move over empty lines, lines with planning time stamps,
22048 clocking lines, and drawers."
22049 (org-back-to-heading t)
22050 (let ((end (save-excursion (outline-next-heading) (point)))
22051 (re (concat "\\(" org-drawer-regexp "\\)"
22052 "\\|" "[ \t]*" org-keyword-time-regexp)))
22053 (forward-line 1)
22054 (while (re-search-forward re end t)
22055 (if (not (match-end 1))
22056 ;; empty or planning line
22057 (forward-line 1)
22058 ;; a drawer, find the end
22059 (re-search-forward "^[ \t]*:END:" end 'move)
22060 (forward-line 1)))
22061 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22062 (point)))
22064 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22065 "Move forward to the arg'th subheading at same level as this one.
22066 Stop at the first and last subheadings of a superior heading.
22067 Normally this only looks at visible headings, but when INVISIBLE-OK is
22068 non-nil it will also look at invisible ones."
22069 (interactive "p")
22070 (org-back-to-heading invisible-ok)
22071 (org-at-heading-p)
22072 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22073 (re (format "^\\*\\{1,%d\\} " level))
22075 (forward-char 1)
22076 (while (> arg 0)
22077 (while (and (re-search-forward re nil 'move)
22078 (setq l (- (match-end 0) (match-beginning 0) 1))
22079 (= l level)
22080 (not invisible-ok)
22081 (progn (backward-char 1) (outline-invisible-p)))
22082 (if (< l level) (setq arg 1)))
22083 (setq arg (1- arg)))
22084 (beginning-of-line 1)))
22086 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22087 "Move backward to the arg'th subheading at same level as this one.
22088 Stop at the first and last subheadings of a superior heading."
22089 (interactive "p")
22090 (org-back-to-heading)
22091 (org-at-heading-p)
22092 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22093 (re (format "^\\*\\{1,%d\\} " level))
22095 (while (> arg 0)
22096 (while (and (re-search-backward re nil 'move)
22097 (setq l (- (match-end 0) (match-beginning 0) 1))
22098 (= l level)
22099 (not invisible-ok)
22100 (outline-invisible-p))
22101 (if (< l level) (setq arg 1)))
22102 (setq arg (1- arg)))))
22104 ;;;###autoload
22105 (defun org-forward-element ()
22106 "Move forward by one element.
22107 Move to the next element at the same level, when possible."
22108 (interactive)
22109 (cond ((eobp) (error "Cannot move further down"))
22110 ((org-with-limited-levels (org-at-heading-p))
22111 (let ((origin (point)))
22112 (org-forward-heading-same-level 1)
22113 (unless (org-with-limited-levels (org-at-heading-p))
22114 (goto-char origin)
22115 (error "Cannot move further down"))))
22117 (let* ((elem (org-element-at-point))
22118 (end (org-element-property :end elem))
22119 (parent (org-element-property :parent elem)))
22120 (if (and parent (= (org-element-property :contents-end parent) end))
22121 (goto-char (org-element-property :end parent))
22122 (goto-char end))))))
22124 ;;;###autoload
22125 (defun org-backward-element ()
22126 "Move backward by one element.
22127 Move to the previous element at the same level, when possible."
22128 (interactive)
22129 (cond ((bobp) (error "Cannot move further up"))
22130 ((org-with-limited-levels (org-at-heading-p))
22131 ;; At an headline, move to the previous one, if any, or stay
22132 ;; here.
22133 (let ((origin (point)))
22134 (org-backward-heading-same-level 1)
22135 (unless (org-with-limited-levels (org-at-heading-p))
22136 (goto-char origin)
22137 (error "Cannot move further up"))))
22139 (let* ((trail (org-element-at-point 'keep-trail))
22140 (elem (car trail))
22141 (prev-elem (nth 1 trail))
22142 (beg (org-element-property :begin elem)))
22143 (cond
22144 ;; Move to beginning of current element if point isn't
22145 ;; there already.
22146 ((/= (point) beg) (goto-char beg))
22147 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22148 ((org-before-first-heading-p) (goto-char (point-min)))
22149 (t (org-back-to-heading)))))))
22151 ;;;###autoload
22152 (defun org-up-element ()
22153 "Move to upper element."
22154 (interactive)
22155 (if (org-with-limited-levels (org-at-heading-p))
22156 (unless (org-up-heading-safe) (error "No surrounding element"))
22157 (let* ((elem (org-element-at-point))
22158 (parent (org-element-property :parent elem)))
22159 (if parent (goto-char (org-element-property :begin parent))
22160 (if (org-with-limited-levels (org-before-first-heading-p))
22161 (error "No surrounding element")
22162 (org-with-limited-levels (org-back-to-heading)))))))
22164 ;;;###autoload
22165 (defvar org-element-greater-elements)
22166 (defun org-down-element ()
22167 "Move to inner element."
22168 (interactive)
22169 (let ((element (org-element-at-point)))
22170 (cond
22171 ((memq (org-element-type element) '(plain-list table))
22172 (goto-char (org-element-property :contents-begin element))
22173 (forward-char))
22174 ((memq (org-element-type element) org-element-greater-elements)
22175 ;; If contents are hidden, first disclose them.
22176 (when (org-element-property :hiddenp element) (org-cycle))
22177 (goto-char (or (org-element-property :contents-begin element)
22178 (error "No content for this element"))))
22179 (t (error "No inner element")))))
22181 ;;;###autoload
22182 (defun org-drag-element-backward ()
22183 "Move backward element at point."
22184 (interactive)
22185 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22186 (let* ((trail (org-element-at-point 'keep-trail))
22187 (elem (car trail))
22188 (prev-elem (nth 1 trail)))
22189 ;; Error out if no previous element or previous element is
22190 ;; a parent of the current one.
22191 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22192 (error "Cannot drag element backward")
22193 (let ((pos (point)))
22194 (org-element-swap-A-B prev-elem elem)
22195 (goto-char (+ (org-element-property :begin prev-elem)
22196 (- pos (org-element-property :begin elem)))))))))
22198 ;;;###autoload
22199 (defun org-drag-element-forward ()
22200 "Move forward element at point."
22201 (interactive)
22202 (let* ((pos (point))
22203 (elem (org-element-at-point)))
22204 (when (= (point-max) (org-element-property :end elem))
22205 (error "Cannot drag element forward"))
22206 (goto-char (org-element-property :end elem))
22207 (let ((next-elem (org-element-at-point)))
22208 (when (or (org-element-nested-p elem next-elem)
22209 (and (eq (org-element-type next-elem) 'headline)
22210 (not (eq (org-element-type elem) 'headline))))
22211 (goto-char pos)
22212 (error "Cannot drag element forward"))
22213 ;; Compute new position of point: it's shifted by NEXT-ELEM
22214 ;; body's length (without final blanks) and by the length of
22215 ;; blanks between ELEM and NEXT-ELEM.
22216 (let ((size-next (- (save-excursion
22217 (goto-char (org-element-property :end next-elem))
22218 (skip-chars-backward " \r\t\n")
22219 (forward-line)
22220 ;; Small correction if buffer doesn't end
22221 ;; with a newline character.
22222 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22223 (org-element-property :begin next-elem)))
22224 (size-blank (- (org-element-property :end elem)
22225 (save-excursion
22226 (goto-char (org-element-property :end elem))
22227 (skip-chars-backward " \r\t\n")
22228 (forward-line)
22229 (point)))))
22230 (org-element-swap-A-B elem next-elem)
22231 (goto-char (+ pos size-next size-blank))))))
22233 ;;;###autoload
22234 (defun org-mark-element ()
22235 "Put point at beginning of this element, mark at end.
22237 Interactively, if this command is repeated or (in Transient Mark
22238 mode) if the mark is active, it marks the next element after the
22239 ones already marked."
22240 (interactive)
22241 (let (deactivate-mark)
22242 (if (and (org-called-interactively-p 'any)
22243 (or (and (eq last-command this-command) (mark t))
22244 (and transient-mark-mode mark-active)))
22245 (set-mark
22246 (save-excursion
22247 (goto-char (mark))
22248 (goto-char (org-element-property :end (org-element-at-point)))))
22249 (let ((element (org-element-at-point)))
22250 (end-of-line)
22251 (push-mark (org-element-property :end element) t t)
22252 (goto-char (org-element-property :begin element))))))
22254 ;;;###autoload
22255 (defun org-narrow-to-element ()
22256 "Narrow buffer to current element."
22257 (interactive)
22258 (let ((elem (org-element-at-point)))
22259 (cond
22260 ((eq (car elem) 'headline)
22261 (narrow-to-region
22262 (org-element-property :begin elem)
22263 (org-element-property :end elem)))
22264 ((memq (car elem) org-element-greater-elements)
22265 (narrow-to-region
22266 (org-element-property :contents-begin elem)
22267 (org-element-property :contents-end elem)))
22269 (narrow-to-region
22270 (org-element-property :begin elem)
22271 (org-element-property :end elem))))))
22273 ;;;###autoload
22274 (defun org-transpose-element ()
22275 "Transpose current and previous elements, keeping blank lines between.
22276 Point is moved after both elements."
22277 (interactive)
22278 (org-skip-whitespace)
22279 (let ((end (org-element-property :end (org-element-at-point))))
22280 (org-drag-element-backward)
22281 (goto-char end)))
22283 ;;;###autoload
22284 (defun org-unindent-buffer ()
22285 "Un-indent the visible part of the buffer.
22286 Relative indentation (between items, inside blocks, etc.) isn't
22287 modified."
22288 (interactive)
22289 (unless (eq major-mode 'org-mode)
22290 (error "Cannot un-indent a buffer not in Org mode"))
22291 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22292 unindent-tree ; For byte-compiler.
22293 (unindent-tree
22294 (function
22295 (lambda (contents)
22296 (mapc
22297 (lambda (element)
22298 (if (memq (org-element-type element) '(headline section))
22299 (funcall unindent-tree (org-element-contents element))
22300 (save-excursion
22301 (save-restriction
22302 (narrow-to-region
22303 (org-element-property :begin element)
22304 (org-element-property :end element))
22305 (org-do-remove-indentation)))))
22306 (reverse contents))))))
22307 (funcall unindent-tree (org-element-contents parse-tree))))
22309 (defun org-show-subtree ()
22310 "Show everything after this heading at deeper levels."
22311 (interactive)
22312 (outline-flag-region
22313 (point)
22314 (save-excursion
22315 (org-end-of-subtree t t))
22316 nil))
22318 (defun org-show-entry ()
22319 "Show the body directly following this heading.
22320 Show the heading too, if it is currently invisible."
22321 (interactive)
22322 (save-excursion
22323 (condition-case nil
22324 (progn
22325 (org-back-to-heading t)
22326 (outline-flag-region
22327 (max (point-min) (1- (point)))
22328 (save-excursion
22329 (if (re-search-forward
22330 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22331 (match-beginning 1)
22332 (point-max)))
22333 nil)
22334 (org-cycle-hide-drawers 'children))
22335 (error nil))))
22337 (defun org-make-options-regexp (kwds &optional extra)
22338 "Make a regular expression for keyword lines."
22339 (concat
22340 "^#\\+\\("
22341 (mapconcat 'regexp-quote kwds "\\|")
22342 (if extra (concat "\\|" extra))
22343 "\\):[ \t]*\\(.*\\)"))
22345 ;; Make isearch reveal the necessary context
22346 (defun org-isearch-end ()
22347 "Reveal context after isearch exits."
22348 (when isearch-success ; only if search was successful
22349 (if (featurep 'xemacs)
22350 ;; Under XEmacs, the hook is run in the correct place,
22351 ;; we directly show the context.
22352 (org-show-context 'isearch)
22353 ;; In Emacs the hook runs *before* restoring the overlays.
22354 ;; So we have to use a one-time post-command-hook to do this.
22355 ;; (Emacs 22 has a special variable, see function `org-mode')
22356 (unless (and (boundp 'isearch-mode-end-hook-quit)
22357 isearch-mode-end-hook-quit)
22358 ;; Only when the isearch was not quitted.
22359 (org-add-hook 'post-command-hook 'org-isearch-post-command
22360 'append 'local)))))
22362 (defun org-isearch-post-command ()
22363 "Remove self from hook, and show context."
22364 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22365 (org-show-context 'isearch))
22368 ;;;; Integration with and fixes for other packages
22370 ;;; Imenu support
22372 (defvar org-imenu-markers nil
22373 "All markers currently used by Imenu.")
22374 (make-variable-buffer-local 'org-imenu-markers)
22376 (defun org-imenu-new-marker (&optional pos)
22377 "Return a new marker for use by Imenu, and remember the marker."
22378 (let ((m (make-marker)))
22379 (move-marker m (or pos (point)))
22380 (push m org-imenu-markers)
22383 (defun org-imenu-get-tree ()
22384 "Produce the index for Imenu."
22385 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22386 (setq org-imenu-markers nil)
22387 (let* ((n org-imenu-depth)
22388 (re (concat "^" (org-get-limited-outline-regexp)))
22389 (subs (make-vector (1+ n) nil))
22390 (last-level 0)
22391 m level head)
22392 (save-excursion
22393 (save-restriction
22394 (widen)
22395 (goto-char (point-max))
22396 (while (re-search-backward re nil t)
22397 (setq level (org-reduced-level (funcall outline-level)))
22398 (when (and (<= level n)
22399 (looking-at org-complex-heading-regexp))
22400 (setq head (org-link-display-format
22401 (org-match-string-no-properties 4))
22402 m (org-imenu-new-marker))
22403 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22404 (if (>= level last-level)
22405 (push (cons head m) (aref subs level))
22406 (push (cons head (aref subs (1+ level))) (aref subs level))
22407 (loop for i from (1+ level) to n do (aset subs i nil)))
22408 (setq last-level level)))))
22409 (aref subs 1)))
22411 (eval-after-load "imenu"
22412 '(progn
22413 (add-hook 'imenu-after-jump-hook
22414 (lambda ()
22415 (if (derived-mode-p 'org-mode)
22416 (org-show-context 'org-goto))))))
22418 (defun org-link-display-format (link)
22419 "Replace a link with either the description, or the link target
22420 if no description is present"
22421 (save-match-data
22422 (if (string-match org-bracket-link-analytic-regexp link)
22423 (replace-match (if (match-end 5)
22424 (match-string 5 link)
22425 (concat (match-string 1 link)
22426 (match-string 3 link)))
22427 nil t link)
22428 link)))
22430 (defun org-toggle-link-display ()
22431 "Toggle the literal or descriptive display of links."
22432 (interactive)
22433 (if org-descriptive-links
22434 (progn (org-remove-from-invisibility-spec '(org-link))
22435 (org-restart-font-lock)
22436 (setq org-descriptive-links nil))
22437 (progn (add-to-invisibility-spec '(org-link))
22438 (org-restart-font-lock)
22439 (setq org-descriptive-links t))))
22441 ;; Speedbar support
22443 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22444 "Overlay marking the agenda restriction line in speedbar.")
22445 (overlay-put org-speedbar-restriction-lock-overlay
22446 'face 'org-agenda-restriction-lock)
22447 (overlay-put org-speedbar-restriction-lock-overlay
22448 'help-echo "Agendas are currently limited to this item.")
22449 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22451 (defun org-speedbar-set-agenda-restriction ()
22452 "Restrict future agenda commands to the location at point in speedbar.
22453 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22454 (interactive)
22455 (require 'org-agenda)
22456 (let (p m tp np dir txt)
22457 (cond
22458 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22459 'org-imenu t))
22460 (setq m (get-text-property p 'org-imenu-marker))
22461 (with-current-buffer (marker-buffer m)
22462 (goto-char m)
22463 (org-agenda-set-restriction-lock 'subtree)))
22464 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22465 'speedbar-function 'speedbar-find-file))
22466 (setq tp (previous-single-property-change
22467 (1+ p) 'speedbar-function)
22468 np (next-single-property-change
22469 tp 'speedbar-function)
22470 dir (speedbar-line-directory)
22471 txt (buffer-substring-no-properties (or tp (point-min))
22472 (or np (point-max))))
22473 (with-current-buffer (find-file-noselect
22474 (let ((default-directory dir))
22475 (expand-file-name txt)))
22476 (unless (derived-mode-p 'org-mode)
22477 (error "Cannot restrict to non-Org-mode file"))
22478 (org-agenda-set-restriction-lock 'file)))
22479 (t (error "Don't know how to restrict Org-mode's agenda")))
22480 (move-overlay org-speedbar-restriction-lock-overlay
22481 (point-at-bol) (point-at-eol))
22482 (setq current-prefix-arg nil)
22483 (org-agenda-maybe-redo)))
22485 (eval-after-load "speedbar"
22486 '(progn
22487 (speedbar-add-supported-extension ".org")
22488 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22489 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22490 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22491 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22492 (add-hook 'speedbar-visiting-tag-hook
22493 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22495 ;;; Fixes and Hacks for problems with other packages
22497 ;; Make flyspell not check words in links, to not mess up our keymap
22498 (defun org-mode-flyspell-verify ()
22499 "Don't let flyspell put overlays at active buttons, or on
22500 {todo,all-time,additional-option-like}-keywords."
22501 (let ((pos (max (1- (point)) (point-min)))
22502 (word (thing-at-point 'word)))
22503 (and (not (get-text-property pos 'keymap))
22504 (not (get-text-property pos 'org-no-flyspell))
22505 (not (member word org-todo-keywords-1))
22506 (not (member word org-all-time-keywords))
22507 (not (member word org-options-keywords))
22508 (not (member word (mapcar 'car org-startup-options)))
22509 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22511 (defun org-remove-flyspell-overlays-in (beg end)
22512 "Remove flyspell overlays in region."
22513 (and (org-bound-and-true-p flyspell-mode)
22514 (fboundp 'flyspell-delete-region-overlays)
22515 (flyspell-delete-region-overlays beg end))
22516 (add-text-properties beg end '(org-no-flyspell t)))
22518 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22519 (eval-after-load "bookmark"
22520 '(if (boundp 'bookmark-after-jump-hook)
22521 ;; We can use the hook
22522 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22523 ;; Hook not available, use advice
22524 (defadvice bookmark-jump (after org-make-visible activate)
22525 "Make the position visible."
22526 (org-bookmark-jump-unhide))))
22528 ;; Make sure saveplace shows the location if it was hidden
22529 (eval-after-load "saveplace"
22530 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22531 "Make the position visible."
22532 (org-bookmark-jump-unhide)))
22534 ;; Make sure ecb shows the location if it was hidden
22535 (eval-after-load "ecb"
22536 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22537 "Make hierarchy visible when jumping into location from ECB tree buffer."
22538 (if (derived-mode-p 'org-mode)
22539 (org-show-context))))
22541 (defun org-bookmark-jump-unhide ()
22542 "Unhide the current position, to show the bookmark location."
22543 (and (derived-mode-p 'org-mode)
22544 (or (outline-invisible-p)
22545 (save-excursion (goto-char (max (point-min) (1- (point))))
22546 (outline-invisible-p)))
22547 (org-show-context 'bookmark-jump)))
22549 ;; Make session.el ignore our circular variable
22550 (eval-after-load "session"
22551 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22553 ;;;; Experimental code
22555 (defun org-closed-in-range ()
22556 "Sparse tree of items closed in a certain time range.
22557 Still experimental, may disappear in the future."
22558 (interactive)
22559 ;; Get the time interval from the user.
22560 (let* ((time1 (org-float-time
22561 (org-read-date nil 'to-time nil "Starting date: ")))
22562 (time2 (org-float-time
22563 (org-read-date nil 'to-time nil "End date:")))
22564 ;; callback function
22565 (callback (lambda ()
22566 (let ((time
22567 (org-float-time
22568 (apply 'encode-time
22569 (org-parse-time-string
22570 (match-string 1))))))
22571 ;; check if time in interval
22572 (and (>= time time1) (<= time time2))))))
22573 ;; make tree, check each match with the callback
22574 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22576 ;;;; Finish up
22578 (provide 'org)
22580 (run-hooks 'org-load-hook)
22582 ;;; org.el ends here