Use generated-autoload-file: "org-loaddefs.el" as a local variable.
[org-mode/org-tableheadings.git] / lisp / org.el
blob6ff9fa817e782bd3432d9553bab6d0b4210ab73c
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" nil t)
83 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
84 ;; some places -- e.g. see the macro org-with-limited-levels.
86 ;; In Org buffers, the value of `outline-regexp' is that of
87 ;; `org-outline-regexp'. The only function still directly relying on
88 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
89 ;; job when `orgstruct-mode' is active.
90 (defvar org-outline-regexp "\\*+ "
91 "Regexp to match Org headlines.")
93 (defvar org-outline-regexp-bol "^\\*+ "
94 "Regexp to match Org headlines.
95 This is similar to `org-outline-regexp' but additionally makes
96 sure that we are at the beginning of the line.")
98 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
99 "Matches an headline, putting stars and text into groups.
100 Stars are put in group 1 and the trimmed body in group 2.")
102 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
103 (when (fboundp 'defvaralias)
104 (unless (boundp 'calendar-view-holidays-initially-flag)
105 (defvaralias 'calendar-view-holidays-initially-flag
106 'view-calendar-holidays-initially))
107 (unless (boundp 'calendar-view-diary-initially-flag)
108 (defvaralias 'calendar-view-diary-initially-flag
109 'view-diary-entries-initially))
110 (unless (boundp 'diary-fancy-buffer)
111 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
113 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
114 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
115 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
116 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
117 (declare-function org-at-clock-log-p "org-clock" ())
118 (declare-function org-clock-timestamps-up "org-clock" ())
119 (declare-function org-clock-timestamps-down "org-clock" ())
120 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
122 ;; load languages based on value of `org-babel-load-languages'
123 (defvar org-babel-load-languages)
124 ;;;###autoload
125 (defun org-babel-do-load-languages (sym value)
126 "Load the languages defined in `org-babel-load-languages'."
127 (set-default sym value)
128 (mapc (lambda (pair)
129 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
130 (if active
131 (progn
132 (require (intern (concat "ob-" lang))))
133 (progn
134 (funcall 'fmakunbound
135 (intern (concat "org-babel-execute:" lang)))
136 (funcall 'fmakunbound
137 (intern (concat "org-babel-expand-body:" lang)))))))
138 org-babel-load-languages))
140 (defcustom org-babel-load-languages '((emacs-lisp . t))
141 "Languages which can be evaluated in Org-mode buffers.
142 This list can be used to load support for any of the languages
143 below, note that each language will depend on a different set of
144 system executables and/or Emacs modes. When a language is
145 \"loaded\", then code blocks in that language can be evaluated
146 with `org-babel-execute-src-block' bound by default to C-c
147 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
148 be set to remove code block evaluation from the C-c C-c
149 keybinding. By default only Emacs Lisp (which has no
150 requirements) is loaded."
151 :group 'org-babel
152 :set 'org-babel-do-load-languages
153 :version "24.1"
154 :type '(alist :tag "Babel Languages"
155 :key-type
156 (choice
157 (const :tag "Awk" awk)
158 (const :tag "C" C)
159 (const :tag "R" R)
160 (const :tag "Asymptote" asymptote)
161 (const :tag "Calc" calc)
162 (const :tag "Clojure" clojure)
163 (const :tag "CSS" css)
164 (const :tag "Ditaa" ditaa)
165 (const :tag "Dot" dot)
166 (const :tag "Emacs Lisp" emacs-lisp)
167 (const :tag "Fortran" fortran)
168 (const :tag "Gnuplot" gnuplot)
169 (const :tag "Haskell" haskell)
170 (const :tag "IO" io)
171 (const :tag "Java" java)
172 (const :tag "Javascript" js)
173 (const :tag "LaTeX" latex)
174 (const :tag "Ledger" ledger)
175 (const :tag "Lilypond" lilypond)
176 (const :tag "Lisp" lisp)
177 (const :tag "Maxima" maxima)
178 (const :tag "Matlab" matlab)
179 (const :tag "Mscgen" mscgen)
180 (const :tag "Ocaml" ocaml)
181 (const :tag "Octave" octave)
182 (const :tag "Org" org)
183 (const :tag "Perl" perl)
184 (const :tag "Pico Lisp" picolisp)
185 (const :tag "PlantUML" plantuml)
186 (const :tag "Python" python)
187 (const :tag "Ruby" ruby)
188 (const :tag "Sass" sass)
189 (const :tag "Scala" scala)
190 (const :tag "Scheme" scheme)
191 (const :tag "Screen" screen)
192 (const :tag "Shell Script" sh)
193 (const :tag "Shen" shen)
194 (const :tag "Sql" sql)
195 (const :tag "Sqlite" sqlite))
196 :value-type (boolean :tag "Activate" :value t)))
198 ;;;; Customization variables
199 (defcustom org-clone-delete-id nil
200 "Remove ID property of clones of a subtree.
201 When non-nil, clones of a subtree don't inherit the ID property.
202 Otherwise they inherit the ID property with a new unique
203 identifier."
204 :type 'boolean
205 :version "24.1"
206 :group 'org-id)
208 ;;; Version
209 (require 'org-compat)
210 (org-check-version)
211 ;;;###autoload
212 (defun org-version (&optional here full message)
213 "Show the org-mode version in the echo area.
214 With prefix argument HERE, insert it at point.
215 When FULL is non-nil, use a verbose version string.
216 When MESSAGE is non-nil, display a message with the version."
217 (interactive "P")
218 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
219 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
220 (org-trash (or
221 (and (fboundp 'org-release) (fboundp 'org-git-version))
222 (load (concat org-dir "org-version.el")
223 'noerror 'nomessage 'nosuffix)))
224 (org-version (org-release))
225 (git-version (org-git-version))
226 (version (format "Org-mode version %s (%s @ %s)"
227 org-version
228 git-version
229 (if org-install-dir
230 (if (string= org-dir org-install-dir)
231 org-install-dir
232 (concat "mixed installation! " org-install-dir " and " org-dir))
233 "org-install.el can not be found!")))
234 (_version (if full version org-version)))
235 (if (org-called-interactively-p 'interactive)
236 (if here
237 (insert version)
238 (message version))
239 (if message (message _version))
240 _version)))
242 (defconst org-version (org-version))
244 ;;; Compatibility constants
246 ;;; The custom variables
248 (defgroup org nil
249 "Outline-based notes management and organizer."
250 :tag "Org"
251 :group 'outlines
252 :group 'calendar)
254 (defcustom org-mode-hook nil
255 "Mode hook for Org-mode, run after the mode was turned on."
256 :group 'org
257 :type 'hook)
259 (defcustom org-load-hook nil
260 "Hook that is run after org.el has been loaded."
261 :group 'org
262 :type 'hook)
264 (defcustom org-log-buffer-setup-hook nil
265 "Hook that is run after an Org log buffer is created."
266 :group 'org
267 :version "24.1"
268 :type 'hook)
270 (defvar org-modules) ; defined below
271 (defvar org-modules-loaded nil
272 "Have the modules been loaded already?")
274 (defun org-load-modules-maybe (&optional force)
275 "Load all extensions listed in `org-modules'."
276 (when (or force (not org-modules-loaded))
277 (mapc (lambda (ext)
278 (condition-case nil (require ext)
279 (error (message "Problems while trying to load feature `%s'" ext))))
280 org-modules)
281 (setq org-modules-loaded t)))
283 (defun org-set-modules (var value)
284 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
285 (set var value)
286 (when (featurep 'org)
287 (org-load-modules-maybe 'force)))
289 (when (org-bound-and-true-p org-modules)
290 (let ((a (member 'org-infojs org-modules)))
291 (and a (setcar a 'org-jsinfo))))
293 (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)
294 "Modules that should always be loaded together with org.el.
295 If a description starts with <C>, the file is not part of Emacs
296 and loading it will require that you have downloaded and properly installed
297 the org-mode distribution.
299 You can also use this system to load external packages (i.e. neither Org
300 core modules, nor modules from the CONTRIB directory). Just add symbols
301 to the end of the list. If the package is called org-xyz.el, then you need
302 to add the symbol `xyz', and the package must have a call to
304 (provide 'org-xyz)"
305 :group 'org
306 :set 'org-set-modules
307 :type
308 '(set :greedy t
309 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
310 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
311 (const :tag " crypt: Encryption of subtrees" org-crypt)
312 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
313 (const :tag " docview: Links to doc-view buffers" org-docview)
314 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
315 (const :tag " id: Global IDs for identifying entries" org-id)
316 (const :tag " info: Links to Info nodes" org-info)
317 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
318 (const :tag " habit: Track your consistency with habits" org-habit)
319 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
320 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
321 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
322 (const :tag " mew Links to Mew folders/messages" org-mew)
323 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
324 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
325 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
326 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
327 (const :tag " vm: Links to VM folders/messages" org-vm)
328 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
329 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
330 (const :tag " mouse: Additional mouse support" org-mouse)
331 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
333 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
334 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
335 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
336 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
337 (const :tag "C collector: Collect properties into tables" org-collector)
338 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
339 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
340 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
341 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
342 (const :tag "C eval: Include command output as text" org-eval)
343 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
344 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
345 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
346 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
347 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
349 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
351 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
352 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
353 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
354 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
355 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
356 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
357 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
358 (const :tag "C mtags: Support for muse-like tags" org-mtags)
359 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
360 (const :tag "C registry: A registry for Org-mode links" org-registry)
361 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
362 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
363 (const :tag "C secretary: Team management with org-mode" org-secretary)
364 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
365 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
366 (const :tag "C track: Keep up with Org-mode development" org-track)
367 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
368 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
369 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
371 (defcustom org-support-shift-select nil
372 "Non-nil means make shift-cursor commands select text when possible.
374 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
375 start selecting a region, or enlarge regions started in this way.
376 In Org-mode, in special contexts, these same keys are used for
377 other purposes, important enough to compete with shift selection.
378 Org tries to balance these needs by supporting `shift-select-mode'
379 outside these special contexts, under control of this variable.
381 The default of this variable is nil, to avoid confusing behavior. Shifted
382 cursor keys will then execute Org commands in the following contexts:
383 - on a headline, changing TODO state (left/right) and priority (up/down)
384 - on a time stamp, changing the time
385 - in a plain list item, changing the bullet type
386 - in a property definition line, switching between allowed values
387 - in the BEGIN line of a clock table (changing the time block).
388 Outside these contexts, the commands will throw an error.
390 When this variable is t and the cursor is not in a special
391 context, Org-mode will support shift-selection for making and
392 enlarging regions. To make this more effective, the bullet
393 cycling will no longer happen anywhere in an item line, but only
394 if the cursor is exactly on the bullet.
396 If you set this variable to the symbol `always', then the keys
397 will not be special in headlines, property lines, and item lines,
398 to make shift selection work there as well. If this is what you
399 want, you can use the following alternative commands: `C-c C-t'
400 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
401 can be used to switch TODO sets, `C-c -' to cycle item bullet
402 types, and properties can be edited by hand or in column view.
404 However, when the cursor is on a timestamp, shift-cursor commands
405 will still edit the time stamp - this is just too good to give up.
407 XEmacs user should have this variable set to nil, because
408 `shift-select-mode' is in Emacs 23 or later only."
409 :group 'org
410 :type '(choice
411 (const :tag "Never" nil)
412 (const :tag "When outside special context" t)
413 (const :tag "Everywhere except timestamps" always)))
415 (defcustom org-loop-over-headlines-in-active-region nil
416 "Shall some commands act upon headlines in the active region?
418 When set to `t', some commands will be performed in all headlines
419 within the active region.
421 When set to `start-level', some commands will be performed in all
422 headlines within the active region, provided that these headlines
423 are of the same level than the first one.
425 When set to a string, those commands will be performed on the
426 matching headlines within the active region. Such string must be
427 a tags/property/todo match as it is used in the agenda tags view.
429 The list of commands is: `org-schedule', `org-deadline',
430 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
431 `org-archive-to-archive-sibling'. The archiving commands skip
432 already archived entries."
433 :type '(choice (const :tag "Don't loop" nil)
434 (const :tag "All headlines in active region" t)
435 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
436 (string :tag "Tags/Property/Todo matcher"))
437 :version "24.1"
438 :group 'org-todo
439 :group 'org-archive)
441 (defgroup org-startup nil
442 "Options concerning startup of Org-mode."
443 :tag "Org Startup"
444 :group 'org)
446 (defcustom org-startup-folded t
447 "Non-nil means entering Org-mode will switch to OVERVIEW.
448 This can also be configured on a per-file basis by adding one of
449 the following lines anywhere in the buffer:
451 #+STARTUP: fold (or `overview', this is equivalent)
452 #+STARTUP: nofold (or `showall', this is equivalent)
453 #+STARTUP: content
454 #+STARTUP: showeverything"
455 :group 'org-startup
456 :type '(choice
457 (const :tag "nofold: show all" nil)
458 (const :tag "fold: overview" t)
459 (const :tag "content: all headlines" content)
460 (const :tag "show everything, even drawers" showeverything)))
462 (defcustom org-startup-truncated t
463 "Non-nil means entering Org-mode will set `truncate-lines'.
464 This is useful since some lines containing links can be very long and
465 uninteresting. Also tables look terrible when wrapped."
466 :group 'org-startup
467 :type 'boolean)
469 (defcustom org-startup-indented nil
470 "Non-nil means turn on `org-indent-mode' on startup.
471 This can also be configured on a per-file basis by adding one of
472 the following lines anywhere in the buffer:
474 #+STARTUP: indent
475 #+STARTUP: noindent"
476 :group 'org-structure
477 :type '(choice
478 (const :tag "Not" nil)
479 (const :tag "Globally (slow on startup in large files)" t)))
481 (defcustom org-use-sub-superscripts t
482 "Non-nil means interpret \"_\" and \"^\" for export.
483 When this option is turned on, you can use TeX-like syntax for sub- and
484 superscripts. Several characters after \"_\" or \"^\" will be
485 considered as a single item - so grouping with {} is normally not
486 needed. For example, the following things will be parsed as single
487 sub- or superscripts.
489 10^24 or 10^tau several digits will be considered 1 item.
490 10^-12 or 10^-tau a leading sign with digits or a word
491 x^2-y^3 will be read as x^2 - y^3, because items are
492 terminated by almost any nonword/nondigit char.
493 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
495 Still, ambiguity is possible - so when in doubt use {} to enclose the
496 sub/superscript. If you set this variable to the symbol `{}',
497 the braces are *required* in order to trigger interpretations as
498 sub/superscript. This can be helpful in documents that need \"_\"
499 frequently in plain text.
501 Not all export backends support this, but HTML does.
503 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
504 :group 'org-startup
505 :group 'org-export-translation
506 :version "24.1"
507 :type '(choice
508 (const :tag "Always interpret" t)
509 (const :tag "Only with braces" {})
510 (const :tag "Never interpret" nil)))
512 (if (fboundp 'defvaralias)
513 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
516 (defcustom org-startup-with-beamer-mode nil
517 "Non-nil means turn on `org-beamer-mode' on startup.
518 This can also be configured on a per-file basis by adding one of
519 the following lines anywhere in the buffer:
521 #+STARTUP: beamer"
522 :group 'org-startup
523 :version "24.1"
524 :type 'boolean)
526 (defcustom org-startup-align-all-tables nil
527 "Non-nil means align all tables when visiting a file.
528 This is useful when the column width in tables is forced with <N> cookies
529 in table fields. Such tables will look correct only after the first re-align.
530 This can also be configured on a per-file basis by adding one of
531 the following lines anywhere in the buffer:
532 #+STARTUP: align
533 #+STARTUP: noalign"
534 :group 'org-startup
535 :type 'boolean)
537 (defcustom org-startup-with-inline-images nil
538 "Non-nil means show inline images when loading a new Org file.
539 This can also be configured on a per-file basis by adding one of
540 the following lines anywhere in the buffer:
541 #+STARTUP: inlineimages
542 #+STARTUP: noinlineimages"
543 :group 'org-startup
544 :version "24.1"
545 :type 'boolean)
547 (defcustom org-insert-mode-line-in-empty-file nil
548 "Non-nil means insert the first line setting Org-mode in empty files.
549 When the function `org-mode' is called interactively in an empty file, this
550 normally means that the file name does not automatically trigger Org-mode.
551 To ensure that the file will always be in Org-mode in the future, a
552 line enforcing Org-mode will be inserted into the buffer, if this option
553 has been set."
554 :group 'org-startup
555 :type 'boolean)
557 (defcustom org-replace-disputed-keys nil
558 "Non-nil means use alternative key bindings for some keys.
559 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
560 These keys are also used by other packages like shift-selection-mode'
561 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
562 If you want to use Org-mode together with one of these other modes,
563 or more generally if you would like to move some Org-mode commands to
564 other keys, set this variable and configure the keys with the variable
565 `org-disputed-keys'.
567 This option is only relevant at load-time of Org-mode, and must be set
568 *before* org.el is loaded. Changing it requires a restart of Emacs to
569 become effective."
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-use-extra-keys nil
574 "Non-nil means use extra key sequence definitions for certain commands.
575 This happens automatically if you run XEmacs or if `window-system'
576 is nil. This variable lets you do the same manually. You must
577 set it before loading org.
579 Example: on Carbon Emacs 22 running graphically, with an external
580 keyboard on a Powerbook, the default way of setting M-left might
581 not work for either Alt or ESC. Setting this variable will make
582 it work for ESC."
583 :group 'org-startup
584 :type 'boolean)
586 (if (fboundp 'defvaralias)
587 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
589 (defcustom org-disputed-keys
590 '(([(shift up)] . [(meta p)])
591 ([(shift down)] . [(meta n)])
592 ([(shift left)] . [(meta -)])
593 ([(shift right)] . [(meta +)])
594 ([(control shift right)] . [(meta shift +)])
595 ([(control shift left)] . [(meta shift -)]))
596 "Keys for which Org-mode and other modes compete.
597 This is an alist, cars are the default keys, second element specifies
598 the alternative to use when `org-replace-disputed-keys' is t.
600 Keys can be specified in any syntax supported by `define-key'.
601 The value of this option takes effect only at Org-mode's startup,
602 therefore you'll have to restart Emacs to apply it after changing."
603 :group 'org-startup
604 :type 'alist)
606 (defun org-key (key)
607 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
608 Or return the original if not disputed.
609 Also apply the translations defined in `org-xemacs-key-equivalents'."
610 (when org-replace-disputed-keys
611 (let* ((nkey (key-description key))
612 (x (org-find-if (lambda (x)
613 (equal (key-description (car x)) nkey))
614 org-disputed-keys)))
615 (setq key (if x (cdr x) key))))
616 (when (featurep 'xemacs)
617 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
618 key)
620 (defun org-find-if (predicate seq)
621 (catch 'exit
622 (while seq
623 (if (funcall predicate (car seq))
624 (throw 'exit (car seq))
625 (pop seq)))))
627 (defun org-defkey (keymap key def)
628 "Define a key, possibly translated, as returned by `org-key'."
629 (define-key keymap (org-key key) def))
631 (defcustom org-ellipsis nil
632 "The ellipsis to use in the Org-mode outline.
633 When nil, just use the standard three dots. When a string, use that instead,
634 When a face, use the standard 3 dots, but with the specified face.
635 The change affects only Org-mode (which will then use its own display table).
636 Changing this requires executing `M-x org-mode' in a buffer to become
637 effective."
638 :group 'org-startup
639 :type '(choice (const :tag "Default" nil)
640 (face :tag "Face" :value org-warning)
641 (string :tag "String" :value "...#")))
643 (defvar org-display-table nil
644 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
646 (defgroup org-keywords nil
647 "Keywords in Org-mode."
648 :tag "Org Keywords"
649 :group 'org)
651 (defcustom org-deadline-string "DEADLINE:"
652 "String to mark deadline entries.
653 A deadline is this string, followed by a time stamp. Should be a word,
654 terminated by a colon. You can insert a schedule keyword and
655 a timestamp with \\[org-deadline].
656 Changes become only effective after restarting Emacs."
657 :group 'org-keywords
658 :type 'string)
660 (defcustom org-scheduled-string "SCHEDULED:"
661 "String to mark scheduled TODO entries.
662 A schedule is this string, followed by a time stamp. Should be a word,
663 terminated by a colon. You can insert a schedule keyword and
664 a timestamp with \\[org-schedule].
665 Changes become only effective after restarting Emacs."
666 :group 'org-keywords
667 :type 'string)
669 (defcustom org-closed-string "CLOSED:"
670 "String used as the prefix for timestamps logging closing a TODO entry."
671 :group 'org-keywords
672 :type 'string)
674 (defcustom org-clock-string "CLOCK:"
675 "String used as prefix for timestamps clocking work hours on an item."
676 :group 'org-keywords
677 :type 'string)
679 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
680 org-scheduled-string "\\|"
681 org-deadline-string "\\|"
682 org-closed-string "\\|"
683 org-clock-string "\\)")
684 "Matches a line with planning or clock info.")
686 (defcustom org-comment-string "COMMENT"
687 "Entries starting with this keyword will never be exported.
688 An entry can be toggled between COMMENT and normal with
689 \\[org-toggle-comment].
690 Changes become only effective after restarting Emacs."
691 :group 'org-keywords
692 :type 'string)
694 (defcustom org-quote-string "QUOTE"
695 "Entries starting with this keyword will be exported in fixed-width font.
696 Quoting applies only to the text in the entry following the headline, and does
697 not extend beyond the next headline, even if that is lower level.
698 An entry can be toggled between QUOTE and normal with
699 \\[org-toggle-fixed-width-section]."
700 :group 'org-keywords
701 :type 'string)
703 (defconst org-repeat-re
704 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
705 "Regular expression for specifying repeated events.
706 After a match, group 1 contains the repeat expression.")
708 (defgroup org-structure nil
709 "Options concerning the general structure of Org-mode files."
710 :tag "Org Structure"
711 :group 'org)
713 (defgroup org-reveal-location nil
714 "Options about how to make context of a location visible."
715 :tag "Org Reveal Location"
716 :group 'org-structure)
718 (defconst org-context-choice
719 '(choice
720 (const :tag "Always" t)
721 (const :tag "Never" nil)
722 (repeat :greedy t :tag "Individual contexts"
723 (cons
724 (choice :tag "Context"
725 (const agenda)
726 (const org-goto)
727 (const occur-tree)
728 (const tags-tree)
729 (const link-search)
730 (const mark-goto)
731 (const bookmark-jump)
732 (const isearch)
733 (const default))
734 (boolean))))
735 "Contexts for the reveal options.")
737 (defcustom org-show-hierarchy-above '((default . t))
738 "Non-nil means show full hierarchy when revealing a location.
739 Org-mode often shows locations in an org-mode file which might have
740 been invisible before. When this is set, the hierarchy of headings
741 above the exposed location is shown.
742 Turning this off for example for sparse trees makes them very compact.
743 Instead of t, this can also be an alist specifying this option for different
744 contexts. Valid contexts are
745 agenda when exposing an entry from the agenda
746 org-goto when using the command `org-goto' on key C-c C-j
747 occur-tree when using the command `org-occur' on key C-c /
748 tags-tree when constructing a sparse tree based on tags matches
749 link-search when exposing search matches associated with a link
750 mark-goto when exposing the jump goal of a mark
751 bookmark-jump when exposing a bookmark location
752 isearch when exiting from an incremental search
753 default default for all contexts not set explicitly"
754 :group 'org-reveal-location
755 :type org-context-choice)
757 (defcustom org-show-following-heading '((default . nil))
758 "Non-nil means show following heading when revealing a location.
759 Org-mode often shows locations in an org-mode file which might have
760 been invisible before. When this is set, the heading following the
761 match is shown.
762 Turning this off for example for sparse trees makes them very compact,
763 but makes it harder to edit the location of the match. In such a case,
764 use the command \\[org-reveal] to show more context.
765 Instead of t, this can also be an alist specifying this option for different
766 contexts. See `org-show-hierarchy-above' for valid contexts."
767 :group 'org-reveal-location
768 :type org-context-choice)
770 (defcustom org-show-siblings '((default . nil) (isearch t))
771 "Non-nil means show all sibling heading when revealing a location.
772 Org-mode often shows locations in an org-mode file which might have
773 been invisible before. When this is set, the sibling of the current entry
774 heading are all made visible. If `org-show-hierarchy-above' is t,
775 the same happens on each level of the hierarchy above the current entry.
777 By default this is on for the isearch context, off for all other contexts.
778 Turning this off for example for sparse trees makes them very compact,
779 but makes it harder to edit the location of the match. In such a case,
780 use the command \\[org-reveal] to show more context.
781 Instead of t, this can also be an alist specifying this option for different
782 contexts. See `org-show-hierarchy-above' for valid contexts."
783 :group 'org-reveal-location
784 :type org-context-choice)
786 (defcustom org-show-entry-below '((default . nil))
787 "Non-nil means show the entry below a headline when revealing a location.
788 Org-mode often shows locations in an org-mode file which might have
789 been invisible before. When this is set, the text below the headline that is
790 exposed is also shown.
792 By default this is off for all contexts.
793 Instead of t, this can also be an alist specifying this option for different
794 contexts. See `org-show-hierarchy-above' for valid contexts."
795 :group 'org-reveal-location
796 :type org-context-choice)
798 (defcustom org-indirect-buffer-display 'other-window
799 "How should indirect tree buffers be displayed?
800 This applies to indirect buffers created with the commands
801 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
802 Valid values are:
803 current-window Display in the current window
804 other-window Just display in another window.
805 dedicated-frame Create one new frame, and re-use it each time.
806 new-frame Make a new frame each time. Note that in this case
807 previously-made indirect buffers are kept, and you need to
808 kill these buffers yourself."
809 :group 'org-structure
810 :group 'org-agenda-windows
811 :type '(choice
812 (const :tag "In current window" current-window)
813 (const :tag "In current frame, other window" other-window)
814 (const :tag "Each time a new frame" new-frame)
815 (const :tag "One dedicated frame" dedicated-frame)))
817 (defcustom org-use-speed-commands nil
818 "Non-nil means activate single letter commands at beginning of a headline.
819 This may also be a function to test for appropriate locations where speed
820 commands should be active."
821 :group 'org-structure
822 :type '(choice
823 (const :tag "Never" nil)
824 (const :tag "At beginning of headline stars" t)
825 (function)))
827 (defcustom org-speed-commands-user nil
828 "Alist of additional speed commands.
829 This list will be checked before `org-speed-commands-default'
830 when the variable `org-use-speed-commands' is non-nil
831 and when the cursor is at the beginning of a headline.
832 The car if each entry is a string with a single letter, which must
833 be assigned to `self-insert-command' in the global map.
834 The cdr is either a command to be called interactively, a function
835 to be called, or a form to be evaluated.
836 An entry that is just a list with a single string will be interpreted
837 as a descriptive headline that will be added when listing the speed
838 commands in the Help buffer using the `?' speed command."
839 :group 'org-structure
840 :type '(repeat :value ("k" . ignore)
841 (choice :value ("k" . ignore)
842 (list :tag "Descriptive Headline" (string :tag "Headline"))
843 (cons :tag "Letter and Command"
844 (string :tag "Command letter")
845 (choice
846 (function)
847 (sexp))))))
849 (defgroup org-cycle nil
850 "Options concerning visibility cycling in Org-mode."
851 :tag "Org Cycle"
852 :group 'org-structure)
854 (defcustom org-cycle-skip-children-state-if-no-children t
855 "Non-nil means skip CHILDREN state in entries that don't have any."
856 :group 'org-cycle
857 :type 'boolean)
859 (defcustom org-cycle-max-level nil
860 "Maximum level which should still be subject to visibility cycling.
861 Levels higher than this will, for cycling, be treated as text, not a headline.
862 When `org-odd-levels-only' is set, a value of N in this variable actually
863 means 2N-1 stars as the limiting headline.
864 When nil, cycle all levels.
865 Note that the limiting level of cycling is also influenced by
866 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
867 `org-inlinetask-min-level' is, cycling will be limited to levels one less
868 than its value."
869 :group 'org-cycle
870 :type '(choice
871 (const :tag "No limit" nil)
872 (integer :tag "Maximum level")))
874 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
875 "Names of drawers. Drawers are not opened by cycling on the headline above.
876 Drawers only open with a TAB on the drawer line itself. A drawer looks like
877 this:
878 :DRAWERNAME:
879 .....
880 :END:
881 The drawer \"PROPERTIES\" is special for capturing properties through
882 the property API.
884 Drawers can be defined on the per-file basis with a line like:
886 #+DRAWERS: HIDDEN STATE PROPERTIES"
887 :group 'org-structure
888 :group 'org-cycle
889 :type '(repeat (string :tag "Drawer Name")))
891 (defcustom org-hide-block-startup nil
892 "Non-nil means entering Org-mode will fold all blocks.
893 This can also be set in on a per-file basis with
895 #+STARTUP: hideblocks
896 #+STARTUP: showblocks"
897 :group 'org-startup
898 :group 'org-cycle
899 :type 'boolean)
901 (defcustom org-cycle-global-at-bob nil
902 "Cycle globally if cursor is at beginning of buffer and not at a headline.
903 This makes it possible to do global cycling without having to use S-TAB or
904 \\[universal-argument] TAB. For this special case to work, the first line
905 of the buffer must not be a headline -- it may be empty or some other text.
906 When used in this way, `org-cycle-hook' is disabled temporarily to make
907 sure the cursor stays at the beginning of the buffer. When this option is
908 nil, don't do anything special at the beginning of the buffer."
909 :group 'org-cycle
910 :type 'boolean)
912 (defcustom org-cycle-level-after-item/entry-creation t
913 "Non-nil means cycle entry level or item indentation in new empty entries.
915 When the cursor is at the end of an empty headline, i.e with only stars
916 and maybe a TODO keyword, TAB will then switch the entry to become a child,
917 and then all possible ancestor states, before returning to the original state.
918 This makes data entry extremely fast: M-RET to create a new headline,
919 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
921 When the cursor is at the end of an empty plain list item, one TAB will
922 make it a subitem, two or more tabs will back up to make this an item
923 higher up in the item hierarchy."
924 :group 'org-cycle
925 :type 'boolean)
927 (defcustom org-cycle-emulate-tab t
928 "Where should `org-cycle' emulate TAB.
929 nil Never
930 white Only in completely white lines
931 whitestart Only at the beginning of lines, before the first non-white char
932 t Everywhere except in headlines
933 exc-hl-bol Everywhere except at the start of a headline
934 If TAB is used in a place where it does not emulate TAB, the current subtree
935 visibility is cycled."
936 :group 'org-cycle
937 :type '(choice (const :tag "Never" nil)
938 (const :tag "Only in completely white lines" white)
939 (const :tag "Before first char in a line" whitestart)
940 (const :tag "Everywhere except in headlines" t)
941 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
944 (defcustom org-cycle-separator-lines 2
945 "Number of empty lines needed to keep an empty line between collapsed trees.
946 If you leave an empty line between the end of a subtree and the following
947 headline, this empty line is hidden when the subtree is folded.
948 Org-mode will leave (exactly) one empty line visible if the number of
949 empty lines is equal or larger to the number given in this variable.
950 So the default 2 means at least 2 empty lines after the end of a subtree
951 are needed to produce free space between a collapsed subtree and the
952 following headline.
954 If the number is negative, and the number of empty lines is at least -N,
955 all empty lines are shown.
957 Special case: when 0, never leave empty lines in collapsed view."
958 :group 'org-cycle
959 :type 'integer)
960 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
962 (defcustom org-pre-cycle-hook nil
963 "Hook that is run before visibility cycling is happening.
964 The function(s) in this hook must accept a single argument which indicates
965 the new state that will be set right after running this hook. The
966 argument is a symbol. Before a global state change, it can have the values
967 `overview', `content', or `all'. Before a local state change, it can have
968 the values `folded', `children', or `subtree'."
969 :group 'org-cycle
970 :type 'hook)
972 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
973 org-cycle-hide-drawers
974 org-cycle-show-empty-lines
975 org-optimize-window-after-visibility-change)
976 "Hook that is run after `org-cycle' has changed the buffer visibility.
977 The function(s) in this hook must accept a single argument which indicates
978 the new state that was set by the most recent `org-cycle' command. The
979 argument is a symbol. After a global state change, it can have the values
980 `overview', `contents', or `all'. After a local state change, it can have
981 the values `folded', `children', or `subtree'."
982 :group 'org-cycle
983 :type 'hook)
985 (defgroup org-edit-structure nil
986 "Options concerning structure editing in Org-mode."
987 :tag "Org Edit Structure"
988 :group 'org-structure)
990 (defcustom org-odd-levels-only nil
991 "Non-nil means skip even levels and only use odd levels for the outline.
992 This has the effect that two stars are being added/taken away in
993 promotion/demotion commands. It also influences how levels are
994 handled by the exporters.
995 Changing it requires restart of `font-lock-mode' to become effective
996 for fontification also in regions already fontified.
997 You may also set this on a per-file basis by adding one of the following
998 lines to the buffer:
1000 #+STARTUP: odd
1001 #+STARTUP: oddeven"
1002 :group 'org-edit-structure
1003 :group 'org-appearance
1004 :type 'boolean)
1006 (defcustom org-adapt-indentation t
1007 "Non-nil means adapt indentation to outline node level.
1009 When this variable is set, Org assumes that you write outlines by
1010 indenting text in each node to align with the headline (after the stars).
1011 The following issues are influenced by this variable:
1013 - When this is set and the *entire* text in an entry is indented, the
1014 indentation is increased by one space in a demotion command, and
1015 decreased by one in a promotion command. If any line in the entry
1016 body starts with text at column 0, indentation is not changed at all.
1018 - Property drawers and planning information is inserted indented when
1019 this variable s set. When nil, they will not be indented.
1021 - TAB indents a line relative to context. The lines below a headline
1022 will be indented when this variable is set.
1024 Note that this is all about true indentation, by adding and removing
1025 space characters. See also `org-indent.el' which does level-dependent
1026 indentation in a virtual way, i.e. at display time in Emacs."
1027 :group 'org-edit-structure
1028 :type 'boolean)
1030 (defcustom org-special-ctrl-a/e nil
1031 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1033 When t, `C-a' will bring back the cursor to the beginning of the
1034 headline text, i.e. after the stars and after a possible TODO
1035 keyword. In an item, this will be the position after bullet and
1036 check-box, if any. When the cursor is already at that position,
1037 another `C-a' will bring it to the beginning of the line.
1039 `C-e' will jump to the end of the headline, ignoring the presence
1040 of tags in the headline. A second `C-e' will then jump to the
1041 true end of the line, after any tags. This also means that, when
1042 this variable is non-nil, `C-e' also will never jump beyond the
1043 end of the heading of a folded section, i.e. not after the
1044 ellipses.
1046 When set to the symbol `reversed', the first `C-a' or `C-e' works
1047 normally, going to the true line boundary first. Only a directly
1048 following, identical keypress will bring the cursor to the
1049 special positions.
1051 This may also be a cons cell where the behavior for `C-a' and
1052 `C-e' is set separately."
1053 :group 'org-edit-structure
1054 :type '(choice
1055 (const :tag "off" nil)
1056 (const :tag "on: after stars/bullet and before tags first" t)
1057 (const :tag "reversed: true line boundary first" reversed)
1058 (cons :tag "Set C-a and C-e separately"
1059 (choice :tag "Special C-a"
1060 (const :tag "off" nil)
1061 (const :tag "on: after stars/bullet first" t)
1062 (const :tag "reversed: before stars/bullet first" reversed))
1063 (choice :tag "Special C-e"
1064 (const :tag "off" nil)
1065 (const :tag "on: before tags first" t)
1066 (const :tag "reversed: after tags first" reversed)))))
1067 (if (fboundp 'defvaralias)
1068 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1070 (defcustom org-special-ctrl-k nil
1071 "Non-nil means `C-k' will behave specially in headlines.
1072 When nil, `C-k' will call the default `kill-line' command.
1073 When t, the following will happen while the cursor is in the headline:
1075 - When the cursor is at the beginning of a headline, kill the entire
1076 line and possible the folded subtree below the line.
1077 - When in the middle of the headline text, kill the headline up to the tags.
1078 - When after the headline text, kill the tags."
1079 :group 'org-edit-structure
1080 :type 'boolean)
1082 (defcustom org-ctrl-k-protect-subtree nil
1083 "Non-nil means, do not delete a hidden subtree with C-k.
1084 When set to the symbol `error', simply throw an error when C-k is
1085 used to kill (part-of) a headline that has hidden text behind it.
1086 Any other non-nil value will result in a query to the user, if it is
1087 OK to kill that hidden subtree. When nil, kill without remorse."
1088 :group 'org-edit-structure
1089 :version "24.1"
1090 :type '(choice
1091 (const :tag "Do not protect hidden subtrees" nil)
1092 (const :tag "Protect hidden subtrees with a security query" t)
1093 (const :tag "Never kill a hidden subtree with C-k" error)))
1095 (defcustom org-catch-invisible-edits nil
1096 "Check if in invisible region before inserting or deleting a character.
1097 Valid values are:
1099 nil Do not check, so just do invisible edits.
1100 error Throw an error and do nothing.
1101 show Make point visible, and do the requested edit.
1102 show-and-error Make point visible, then throw an error and abort the edit.
1103 smart Make point visible, and do insertion/deletion if it is
1104 adjacent to visible text and the change feels predictable.
1105 Never delete a previously invisible character or add in the
1106 middle or right after an invisible region. Basically, this
1107 allows insertion and backward-delete right before ellipses.
1108 FIXME: maybe in this case we should not even show?"
1109 :group 'org-edit-structure
1110 :version "24.1"
1111 :type '(choice
1112 (const :tag "Do not check" nil)
1113 (const :tag "Throw error when trying to edit" error)
1114 (const :tag "Unhide, but do not do the edit" show-and-error)
1115 (const :tag "Show invisible part and do the edit" show)
1116 (const :tag "Be smart and do the right thing" smart)))
1118 (defcustom org-yank-folded-subtrees t
1119 "Non-nil means when yanking subtrees, fold them.
1120 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1121 it starts with a heading and all other headings in it are either children
1122 or siblings, then fold all the subtrees. However, do this only if no
1123 text after the yank would be swallowed into a folded tree by this action."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defcustom org-yank-adjusted-subtrees nil
1128 "Non-nil means when yanking subtrees, adjust the level.
1129 With this setting, `org-paste-subtree' is used to insert the subtree, see
1130 this function for details."
1131 :group 'org-edit-structure
1132 :type 'boolean)
1134 (defcustom org-M-RET-may-split-line '((default . t))
1135 "Non-nil means M-RET will split the line at the cursor position.
1136 When nil, it will go to the end of the line before making a
1137 new line.
1138 You may also set this option in a different way for different
1139 contexts. Valid contexts are:
1141 headline when creating a new headline
1142 item when creating a new item
1143 table in a table field
1144 default the value to be used for all contexts not explicitly
1145 customized"
1146 :group 'org-structure
1147 :group 'org-table
1148 :type '(choice
1149 (const :tag "Always" t)
1150 (const :tag "Never" nil)
1151 (repeat :greedy t :tag "Individual contexts"
1152 (cons
1153 (choice :tag "Context"
1154 (const headline)
1155 (const item)
1156 (const table)
1157 (const default))
1158 (boolean)))))
1161 (defcustom org-insert-heading-respect-content nil
1162 "Non-nil means insert new headings after the current subtree.
1163 When nil, the new heading is created directly after the current line.
1164 The commands \\[org-insert-heading-respect-content] and
1165 \\[org-insert-todo-heading-respect-content] turn this variable on
1166 for the duration of the command."
1167 :group 'org-structure
1168 :type 'boolean)
1170 (defcustom org-blank-before-new-entry '((heading . auto)
1171 (plain-list-item . auto))
1172 "Should `org-insert-heading' leave a blank line before new heading/item?
1173 The value is an alist, with `heading' and `plain-list-item' as CAR,
1174 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1175 which case Org will look at the surrounding headings/items and try to
1176 make an intelligent decision whether to insert a blank line or not.
1178 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1179 set, the setting here is ignored and no empty line is inserted, to avoid
1180 breaking the list structure."
1181 :group 'org-edit-structure
1182 :type '(list
1183 (cons (const heading)
1184 (choice (const :tag "Never" nil)
1185 (const :tag "Always" t)
1186 (const :tag "Auto" auto)))
1187 (cons (const plain-list-item)
1188 (choice (const :tag "Never" nil)
1189 (const :tag "Always" t)
1190 (const :tag "Auto" auto)))))
1192 (defcustom org-insert-heading-hook nil
1193 "Hook being run after inserting a new heading."
1194 :group 'org-edit-structure
1195 :type 'hook)
1197 (defcustom org-enable-fixed-width-editor t
1198 "Non-nil means lines starting with \":\" are treated as fixed-width.
1199 This currently only means they are never auto-wrapped.
1200 When nil, such lines will be treated like ordinary lines.
1201 See also the QUOTE keyword."
1202 :group 'org-edit-structure
1203 :type 'boolean)
1205 (defcustom org-goto-auto-isearch t
1206 "Non-nil means typing characters in `org-goto' starts incremental search."
1207 :group 'org-edit-structure
1208 :type 'boolean)
1210 (defgroup org-sparse-trees nil
1211 "Options concerning sparse trees in Org-mode."
1212 :tag "Org Sparse Trees"
1213 :group 'org-structure)
1215 (defcustom org-highlight-sparse-tree-matches t
1216 "Non-nil means highlight all matches that define a sparse tree.
1217 The highlights will automatically disappear the next time the buffer is
1218 changed by an edit command."
1219 :group 'org-sparse-trees
1220 :type 'boolean)
1222 (defcustom org-remove-highlights-with-change t
1223 "Non-nil means any change to the buffer will remove temporary highlights.
1224 Such highlights are created by `org-occur' and `org-clock-display'.
1225 When nil, `C-c C-c needs to be used to get rid of the highlights.
1226 The highlights created by `org-preview-latex-fragment' always need
1227 `C-c C-c' to be removed."
1228 :group 'org-sparse-trees
1229 :group 'org-time
1230 :type 'boolean)
1233 (defcustom org-occur-hook '(org-first-headline-recenter)
1234 "Hook that is run after `org-occur' has constructed a sparse tree.
1235 This can be used to recenter the window to show as much of the structure
1236 as possible."
1237 :group 'org-sparse-trees
1238 :type 'hook)
1240 (defgroup org-imenu-and-speedbar nil
1241 "Options concerning imenu and speedbar in Org-mode."
1242 :tag "Org Imenu and Speedbar"
1243 :group 'org-structure)
1245 (defcustom org-imenu-depth 2
1246 "The maximum level for Imenu access to Org-mode headlines.
1247 This also applied for speedbar access."
1248 :group 'org-imenu-and-speedbar
1249 :type 'integer)
1251 (defgroup org-table nil
1252 "Options concerning tables in Org-mode."
1253 :tag "Org Table"
1254 :group 'org)
1256 (defcustom org-enable-table-editor 'optimized
1257 "Non-nil means lines starting with \"|\" are handled by the table editor.
1258 When nil, such lines will be treated like ordinary lines.
1260 When equal to the symbol `optimized', the table editor will be optimized to
1261 do the following:
1262 - Automatic overwrite mode in front of whitespace in table fields.
1263 This makes the structure of the table stay in tact as long as the edited
1264 field does not exceed the column width.
1265 - Minimize the number of realigns. Normally, the table is aligned each time
1266 TAB or RET are pressed to move to another field. With optimization this
1267 happens only if changes to a field might have changed the column width.
1268 Optimization requires replacing the functions `self-insert-command',
1269 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1270 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1271 very good at guessing when a re-align will be necessary, but you can always
1272 force one with \\[org-ctrl-c-ctrl-c].
1274 If you would like to use the optimized version in Org-mode, but the
1275 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1277 This variable can be used to turn on and off the table editor during a session,
1278 but in order to toggle optimization, a restart is required.
1280 See also the variable `org-table-auto-blank-field'."
1281 :group 'org-table
1282 :type '(choice
1283 (const :tag "off" nil)
1284 (const :tag "on" t)
1285 (const :tag "on, optimized" optimized)))
1287 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1288 (version<= emacs-version "24.1"))
1289 "Non-nil means cluster self-insert commands for undo when possible.
1290 If this is set, then, like in the Emacs command loop, 20 consecutive
1291 characters will be undone together.
1292 This is configurable, because there is some impact on typing performance."
1293 :group 'org-table
1294 :type 'boolean)
1296 (defcustom org-table-tab-recognizes-table.el t
1297 "Non-nil means TAB will automatically notice a table.el table.
1298 When it sees such a table, it moves point into it and - if necessary -
1299 calls `table-recognize-table'."
1300 :group 'org-table-editing
1301 :type 'boolean)
1303 (defgroup org-link nil
1304 "Options concerning links in Org-mode."
1305 :tag "Org Link"
1306 :group 'org)
1308 (defvar org-link-abbrev-alist-local nil
1309 "Buffer-local version of `org-link-abbrev-alist', which see.
1310 The value of this is taken from the #+LINK lines.")
1311 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1313 (defcustom org-link-abbrev-alist nil
1314 "Alist of link abbreviations.
1315 The car of each element is a string, to be replaced at the start of a link.
1316 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1317 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1319 [[linkkey:tag][description]]
1321 The 'linkkey' must be a word word, starting with a letter, followed
1322 by letters, numbers, '-' or '_'.
1324 If REPLACE is a string, the tag will simply be appended to create the link.
1325 If the string contains \"%s\", the tag will be inserted there. If the string
1326 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1327 at that point (see the function `url-hexify-string'). If the string contains
1328 the specifier \"%(my-function)\", then the custom function `my-function' will
1329 be invoked: this function takes the tag as its only argument and must return
1330 a string.
1332 REPLACE may also be a function that will be called with the tag as the
1333 only argument to create the link, which should be returned as a string.
1335 See the manual for examples."
1336 :group 'org-link
1337 :type '(repeat
1338 (cons
1339 (string :tag "Protocol")
1340 (choice
1341 (string :tag "Format")
1342 (function)))))
1344 (defcustom org-descriptive-links t
1345 "Non-nil means Org will display descriptive links.
1346 E.g. [[http://orgmode.org][Org website]] will be displayed as
1347 \"Org Website\", hiding the link itself and just displaying its
1348 description. When set to `nil', Org will display the full links
1349 literally.
1351 You can interactively set the value of this variable by calling
1352 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1353 :group 'org-link
1354 :type 'boolean)
1356 (defcustom org-link-file-path-type 'adaptive
1357 "How the path name in file links should be stored.
1358 Valid values are:
1360 relative Relative to the current directory, i.e. the directory of the file
1361 into which the link is being inserted.
1362 absolute Absolute path, if possible with ~ for home directory.
1363 noabbrev Absolute path, no abbreviation of home directory.
1364 adaptive Use relative path for files in the current directory and sub-
1365 directories of it. For other files, use an absolute path."
1366 :group 'org-link
1367 :type '(choice
1368 (const relative)
1369 (const absolute)
1370 (const noabbrev)
1371 (const adaptive)))
1373 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1374 "Types of links that should be activated in Org-mode files.
1375 This is a list of symbols, each leading to the activation of a certain link
1376 type. In principle, it does not hurt to turn on most link types - there may
1377 be a small gain when turning off unused link types. The types are:
1379 bracket The recommended [[link][description]] or [[link]] links with hiding.
1380 angle Links in angular brackets that may contain whitespace like
1381 <bbdb:Carsten Dominik>.
1382 plain Plain links in normal text, no whitespace, like http://google.com.
1383 radio Text that is matched by a radio target, see manual for details.
1384 tag Tag settings in a headline (link to tag search).
1385 date Time stamps (link to calendar).
1386 footnote Footnote labels.
1388 Changing this variable requires a restart of Emacs to become effective."
1389 :group 'org-link
1390 :type '(set :greedy t
1391 (const :tag "Double bracket links" bracket)
1392 (const :tag "Angular bracket links" angle)
1393 (const :tag "Plain text links" plain)
1394 (const :tag "Radio target matches" radio)
1395 (const :tag "Tags" tag)
1396 (const :tag "Timestamps" date)
1397 (const :tag "Footnotes" footnote)))
1399 (defcustom org-make-link-description-function nil
1400 "Function to use for generating link descriptions from links.
1401 When nil, the link location will be used. This function must take
1402 two parameters: the first one is the link, the second one is the
1403 description generated by `org-insert-link'. The function should
1404 return the description to use."
1405 :group 'org-link
1406 :type 'function)
1408 (defgroup org-link-store nil
1409 "Options concerning storing links in Org-mode."
1410 :tag "Org Store Link"
1411 :group 'org-link)
1413 (defcustom org-url-hexify-p t
1414 "When non-nil, hexify URL when creating a link."
1415 :type 'boolean
1416 :version "24.3"
1417 :group 'org-link-store)
1419 (defcustom org-email-link-description-format "Email %c: %.30s"
1420 "Format of the description part of a link to an email or usenet message.
1421 The following %-escapes will be replaced by corresponding information:
1423 %F full \"From\" field
1424 %f name, taken from \"From\" field, address if no name
1425 %T full \"To\" field
1426 %t first name in \"To\" field, address if no name
1427 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1428 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1429 %s subject
1430 %d date
1431 %m message-id.
1433 You may use normal field width specification between the % and the letter.
1434 This is for example useful to limit the length of the subject.
1436 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1437 :group 'org-link-store
1438 :type 'string)
1440 (defcustom org-from-is-user-regexp
1441 (let (r1 r2)
1442 (when (and user-mail-address (not (string= user-mail-address "")))
1443 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1444 (when (and user-full-name (not (string= user-full-name "")))
1445 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1446 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1447 "Regexp matched against the \"From:\" header of an email or usenet message.
1448 It should match if the message is from the user him/herself."
1449 :group 'org-link-store
1450 :type 'regexp)
1452 (defcustom org-context-in-file-links t
1453 "Non-nil means file links from `org-store-link' contain context.
1454 A search string will be added to the file name with :: as separator and
1455 used to find the context when the link is activated by the command
1456 `org-open-at-point'. When this option is t, the entire active region
1457 will be placed in the search string of the file link. If set to a
1458 positive integer, only the first n lines of context will be stored.
1460 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1461 negates this setting for the duration of the command."
1462 :group 'org-link-store
1463 :type '(choice boolean integer))
1465 (defcustom org-keep-stored-link-after-insertion nil
1466 "Non-nil means keep link in list for entire session.
1468 The command `org-store-link' adds a link pointing to the current
1469 location to an internal list. These links accumulate during a session.
1470 The command `org-insert-link' can be used to insert links into any
1471 Org-mode file (offering completion for all stored links). When this
1472 option is nil, every link which has been inserted once using \\[org-insert-link]
1473 will be removed from the list, to make completing the unused links
1474 more efficient."
1475 :group 'org-link-store
1476 :type 'boolean)
1478 (defgroup org-link-follow nil
1479 "Options concerning following links in Org-mode."
1480 :tag "Org Follow Link"
1481 :group 'org-link)
1483 (defcustom org-link-translation-function nil
1484 "Function to translate links with different syntax to Org syntax.
1485 This can be used to translate links created for example by the Planner
1486 or emacs-wiki packages to Org syntax.
1487 The function must accept two parameters, a TYPE containing the link
1488 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1489 which is everything after the link protocol. It should return a cons
1490 with possibly modified values of type and path.
1491 Org contains a function for this, so if you set this variable to
1492 `org-translate-link-from-planner', you should be able follow many
1493 links created by planner."
1494 :group 'org-link-follow
1495 :type 'function)
1497 (defcustom org-follow-link-hook nil
1498 "Hook that is run after a link has been followed."
1499 :group 'org-link-follow
1500 :type 'hook)
1502 (defcustom org-tab-follows-link nil
1503 "Non-nil means on links TAB will follow the link.
1504 Needs to be set before org.el is loaded.
1505 This really should not be used, it does not make sense, and the
1506 implementation is bad."
1507 :group 'org-link-follow
1508 :type 'boolean)
1510 (defcustom org-return-follows-link nil
1511 "Non-nil means on links RET will follow the link."
1512 :group 'org-link-follow
1513 :type 'boolean)
1515 (defcustom org-mouse-1-follows-link
1516 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1517 "Non-nil means mouse-1 on a link will follow the link.
1518 A longer mouse click will still set point. Does not work on XEmacs.
1519 Needs to be set before org.el is loaded."
1520 :group 'org-link-follow
1521 :type 'boolean)
1523 (defcustom org-mark-ring-length 4
1524 "Number of different positions to be recorded in the ring.
1525 Changing this requires a restart of Emacs to work correctly."
1526 :group 'org-link-follow
1527 :type 'integer)
1529 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1530 "Non-nil means internal links in Org files must exactly match a headline.
1531 When nil, the link search tries to match a phrase with all words
1532 in the search text."
1533 :group 'org-link-follow
1534 :version "24.1"
1535 :type '(choice
1536 (const :tag "Use fuzzy text search" nil)
1537 (const :tag "Match only exact headline" t)
1538 (const :tag "Match exact headline or query to create it"
1539 query-to-create)))
1541 (defcustom org-link-frame-setup
1542 '((vm . vm-visit-folder-other-frame)
1543 (vm-imap . vm-visit-imap-folder-other-frame)
1544 (gnus . org-gnus-no-new-news)
1545 (file . find-file-other-window)
1546 (wl . wl-other-frame))
1547 "Setup the frame configuration for following links.
1548 When following a link with Emacs, it may often be useful to display
1549 this link in another window or frame. This variable can be used to
1550 set this up for the different types of links.
1551 For VM, use any of
1552 `vm-visit-folder'
1553 `vm-visit-folder-other-window'
1554 `vm-visit-folder-other-frame'
1555 For Gnus, use any of
1556 `gnus'
1557 `gnus-other-frame'
1558 `org-gnus-no-new-news'
1559 For FILE, use any of
1560 `find-file'
1561 `find-file-other-window'
1562 `find-file-other-frame'
1563 For Wanderlust use any of
1564 `wl'
1565 `wl-other-frame'
1566 For the calendar, use the variable `calendar-setup'.
1567 For BBDB, it is currently only possible to display the matches in
1568 another window."
1569 :group 'org-link-follow
1570 :type '(list
1571 (cons (const vm)
1572 (choice
1573 (const vm-visit-folder)
1574 (const vm-visit-folder-other-window)
1575 (const vm-visit-folder-other-frame)))
1576 (cons (const gnus)
1577 (choice
1578 (const gnus)
1579 (const gnus-other-frame)
1580 (const org-gnus-no-new-news)))
1581 (cons (const file)
1582 (choice
1583 (const find-file)
1584 (const find-file-other-window)
1585 (const find-file-other-frame)))
1586 (cons (const wl)
1587 (choice
1588 (const wl)
1589 (const wl-other-frame)))))
1591 (defcustom org-display-internal-link-with-indirect-buffer nil
1592 "Non-nil means use indirect buffer to display infile links.
1593 Activating internal links (from one location in a file to another location
1594 in the same file) normally just jumps to the location. When the link is
1595 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1596 is displayed in
1597 another window. When this option is set, the other window actually displays
1598 an indirect buffer clone of the current buffer, to avoid any visibility
1599 changes to the current buffer."
1600 :group 'org-link-follow
1601 :type 'boolean)
1603 (defcustom org-open-non-existing-files nil
1604 "Non-nil means `org-open-file' will open non-existing files.
1605 When nil, an error will be generated.
1606 This variable applies only to external applications because they
1607 might choke on non-existing files. If the link is to a file that
1608 will be opened in Emacs, the variable is ignored."
1609 :group 'org-link-follow
1610 :type 'boolean)
1612 (defcustom org-open-directory-means-index-dot-org nil
1613 "Non-nil means a link to a directory really means to index.org.
1614 When nil, following a directory link will run dired or open a finder/explorer
1615 window on that directory."
1616 :group 'org-link-follow
1617 :type 'boolean)
1619 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1620 "Function and arguments to call for following mailto links.
1621 This is a list with the first element being a Lisp function, and the
1622 remaining elements being arguments to the function. In string arguments,
1623 %a will be replaced by the address, and %s will be replaced by the subject
1624 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1625 :group 'org-link-follow
1626 :type '(choice
1627 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1628 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1629 (const :tag "message-mail" (message-mail "%a" "%s"))
1630 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1632 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1633 "Non-nil means ask for confirmation before executing shell links.
1634 Shell links can be dangerous: just think about a link
1636 [[shell:rm -rf ~/*][Google Search]]
1638 This link would show up in your Org-mode document as \"Google Search\",
1639 but really it would remove your entire home directory.
1640 Therefore we advise against setting this variable to nil.
1641 Just change it to `y-or-n-p' if you want to confirm with a
1642 single keystroke rather than having to type \"yes\"."
1643 :group 'org-link-follow
1644 :type '(choice
1645 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1646 (const :tag "with y-or-n (faster)" y-or-n-p)
1647 (const :tag "no confirmation (dangerous)" nil)))
1648 (put 'org-confirm-shell-link-function
1649 'safe-local-variable
1650 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1652 (defcustom org-confirm-shell-link-not-regexp ""
1653 "A regexp to skip confirmation for shell links."
1654 :group 'org-link-follow
1655 :version "24.1"
1656 :type 'regexp)
1658 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1659 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1660 Elisp links can be dangerous: just think about a link
1662 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1664 This link would show up in your Org-mode document as \"Google Search\",
1665 but really it would remove your entire home directory.
1666 Therefore we advise against setting this variable to nil.
1667 Just change it to `y-or-n-p' if you want to confirm with a
1668 single keystroke rather than having to type \"yes\"."
1669 :group 'org-link-follow
1670 :type '(choice
1671 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1672 (const :tag "with y-or-n (faster)" y-or-n-p)
1673 (const :tag "no confirmation (dangerous)" nil)))
1674 (put 'org-confirm-shell-link-function
1675 'safe-local-variable
1676 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1678 (defcustom org-confirm-elisp-link-not-regexp ""
1679 "A regexp to skip confirmation for Elisp links."
1680 :group 'org-link-follow
1681 :version "24.1"
1682 :type 'regexp)
1684 (defconst org-file-apps-defaults-gnu
1685 '((remote . emacs)
1686 (system . mailcap)
1687 (t . mailcap))
1688 "Default file applications on a UNIX or GNU/Linux system.
1689 See `org-file-apps'.")
1691 (defconst org-file-apps-defaults-macosx
1692 '((remote . emacs)
1693 (t . "open %s")
1694 (system . "open %s")
1695 ("ps.gz" . "gv %s")
1696 ("eps.gz" . "gv %s")
1697 ("dvi" . "xdvi %s")
1698 ("fig" . "xfig %s"))
1699 "Default file applications on a MacOS X system.
1700 The system \"open\" is known as a default, but we use X11 applications
1701 for some files for which the OS does not have a good default.
1702 See `org-file-apps'.")
1704 (defconst org-file-apps-defaults-windowsnt
1705 (list
1706 '(remote . emacs)
1707 (cons t
1708 (list (if (featurep 'xemacs)
1709 'mswindows-shell-execute
1710 'w32-shell-execute)
1711 "open" 'file))
1712 (cons 'system
1713 (list (if (featurep 'xemacs)
1714 'mswindows-shell-execute
1715 'w32-shell-execute)
1716 "open" 'file)))
1717 "Default file applications on a Windows NT system.
1718 The system \"open\" is used for most files.
1719 See `org-file-apps'.")
1721 (defcustom org-file-apps
1723 (auto-mode . emacs)
1724 ("\\.mm\\'" . default)
1725 ("\\.x?html?\\'" . default)
1726 ("\\.pdf\\'" . default)
1728 "External applications for opening `file:path' items in a document.
1729 Org-mode uses system defaults for different file types, but
1730 you can use this variable to set the application for a given file
1731 extension. The entries in this list are cons cells where the car identifies
1732 files and the cdr the corresponding command. Possible values for the
1733 file identifier are
1734 \"string\" A string as a file identifier can be interpreted in different
1735 ways, depending on its contents:
1737 - Alphanumeric characters only:
1738 Match links with this file extension.
1739 Example: (\"pdf\" . \"evince %s\")
1740 to open PDFs with evince.
1742 - Regular expression: Match links where the
1743 filename matches the regexp. If you want to
1744 use groups here, use shy groups.
1746 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1747 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1748 to open *.html and *.xhtml with firefox.
1750 - Regular expression which contains (non-shy) groups:
1751 Match links where the whole link, including \"::\", and
1752 anything after that, matches the regexp.
1753 In a custom command string, %1, %2, etc. are replaced with
1754 the parts of the link that were matched by the groups.
1755 For backwards compatibility, if a command string is given
1756 that does not use any of the group matches, this case is
1757 handled identically to the second one (i.e. match against
1758 file name only).
1759 In a custom lisp form, you can access the group matches with
1760 (match-string n link).
1762 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1763 to open [[file:document.pdf::5]] with evince at page 5.
1765 `directory' Matches a directory
1766 `remote' Matches a remote file, accessible through tramp or efs.
1767 Remote files most likely should be visited through Emacs
1768 because external applications cannot handle such paths.
1769 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1770 so all files Emacs knows how to handle. Using this with
1771 command `emacs' will open most files in Emacs. Beware that this
1772 will also open html files inside Emacs, unless you add
1773 (\"html\" . default) to the list as well.
1774 t Default for files not matched by any of the other options.
1775 `system' The system command to open files, like `open' on Windows
1776 and Mac OS X, and mailcap under GNU/Linux. This is the command
1777 that will be selected if you call `C-c C-o' with a double
1778 \\[universal-argument] \\[universal-argument] prefix.
1780 Possible values for the command are:
1781 `emacs' The file will be visited by the current Emacs process.
1782 `default' Use the default application for this file type, which is the
1783 association for t in the list, most likely in the system-specific
1784 part.
1785 This can be used to overrule an unwanted setting in the
1786 system-specific variable.
1787 `system' Use the system command for opening files, like \"open\".
1788 This command is specified by the entry whose car is `system'.
1789 Most likely, the system-specific version of this variable
1790 does define this command, but you can overrule/replace it
1791 here.
1792 string A command to be executed by a shell; %s will be replaced
1793 by the path to the file.
1794 sexp A Lisp form which will be evaluated. The file path will
1795 be available in the Lisp variable `file'.
1796 For more examples, see the system specific constants
1797 `org-file-apps-defaults-macosx'
1798 `org-file-apps-defaults-windowsnt'
1799 `org-file-apps-defaults-gnu'."
1800 :group 'org-link-follow
1801 :type '(repeat
1802 (cons (choice :value ""
1803 (string :tag "Extension")
1804 (const :tag "System command to open files" system)
1805 (const :tag "Default for unrecognized files" t)
1806 (const :tag "Remote file" remote)
1807 (const :tag "Links to a directory" directory)
1808 (const :tag "Any files that have Emacs modes"
1809 auto-mode))
1810 (choice :value ""
1811 (const :tag "Visit with Emacs" emacs)
1812 (const :tag "Use default" default)
1813 (const :tag "Use the system command" system)
1814 (string :tag "Command")
1815 (sexp :tag "Lisp form")))))
1817 (defcustom org-doi-server-url "http://dx.doi.org/"
1818 "The URL of the DOI server."
1819 :type 'string
1820 :version "24.3"
1821 :group 'org-link-follow)
1823 (defgroup org-refile nil
1824 "Options concerning refiling entries in Org-mode."
1825 :tag "Org Refile"
1826 :group 'org)
1828 (defcustom org-directory "~/org"
1829 "Directory with org files.
1830 This is just a default location to look for Org files. There is no need
1831 at all to put your files into this directory. It is only used in the
1832 following situations:
1834 1. When a capture template specifies a target file that is not an
1835 absolute path. The path will then be interpreted relative to
1836 `org-directory'
1837 2. When a capture note is filed away in an interactive way (when exiting the
1838 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1839 with `org-directory' as the default path."
1840 :group 'org-refile
1841 :group 'org-remember
1842 :group 'org-capture
1843 :type 'directory)
1845 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1846 "Default target for storing notes.
1847 Used as a fall back file for org-remember.el and org-capture.el, for
1848 templates that do not specify a target file."
1849 :group 'org-refile
1850 :group 'org-remember
1851 :group 'org-capture
1852 :type '(choice
1853 (const :tag "Default from remember-data-file" nil)
1854 file))
1856 (defcustom org-goto-interface 'outline
1857 "The default interface to be used for `org-goto'.
1858 Allowed values are:
1859 outline The interface shows an outline of the relevant file
1860 and the correct heading is found by moving through
1861 the outline or by searching with incremental search.
1862 outline-path-completion Headlines in the current buffer are offered via
1863 completion. This is the interface also used by
1864 the refile command."
1865 :group 'org-refile
1866 :type '(choice
1867 (const :tag "Outline" outline)
1868 (const :tag "Outline-path-completion" outline-path-completion)))
1870 (defcustom org-goto-max-level 5
1871 "Maximum target level when running `org-goto' with refile interface."
1872 :group 'org-refile
1873 :type 'integer)
1875 (defcustom org-reverse-note-order nil
1876 "Non-nil means store new notes at the beginning of a file or entry.
1877 When nil, new notes will be filed to the end of a file or entry.
1878 This can also be a list with cons cells of regular expressions that
1879 are matched against file names, and values."
1880 :group 'org-remember
1881 :group 'org-capture
1882 :group 'org-refile
1883 :type '(choice
1884 (const :tag "Reverse always" t)
1885 (const :tag "Reverse never" nil)
1886 (repeat :tag "By file name regexp"
1887 (cons regexp boolean))))
1889 (defcustom org-log-refile nil
1890 "Information to record when a task is refiled.
1892 Possible values are:
1894 nil Don't add anything
1895 time Add a time stamp to the task
1896 note Prompt for a note and add it with template `org-log-note-headings'
1898 This option can also be set with on a per-file-basis with
1900 #+STARTUP: nologrefile
1901 #+STARTUP: logrefile
1902 #+STARTUP: lognoterefile
1904 You can have local logging settings for a subtree by setting the LOGGING
1905 property to one or more of these keywords.
1907 When bulk-refiling from the agenda, the value `note' is forbidden and
1908 will temporarily be changed to `time'."
1909 :group 'org-refile
1910 :group 'org-progress
1911 :version "24.1"
1912 :type '(choice
1913 (const :tag "No logging" nil)
1914 (const :tag "Record timestamp" time)
1915 (const :tag "Record timestamp with note." note)))
1917 (defcustom org-refile-targets nil
1918 "Targets for refiling entries with \\[org-refile].
1919 This is a list of cons cells. Each cell contains:
1920 - a specification of the files to be considered, either a list of files,
1921 or a symbol whose function or variable value will be used to retrieve
1922 a file name or a list of file names. If you use `org-agenda-files' for
1923 that, all agenda files will be scanned for targets. Nil means consider
1924 headings in the current buffer.
1925 - A specification of how to find candidate refile targets. This may be
1926 any of:
1927 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1928 This tag has to be present in all target headlines, inheritance will
1929 not be considered.
1930 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1931 todo keyword.
1932 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1933 headlines that are refiling targets.
1934 - a cons cell (:level . N). Any headline of level N is considered a target.
1935 Note that, when `org-odd-levels-only' is set, level corresponds to
1936 order in hierarchy, not to the number of stars.
1937 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1938 Note that, when `org-odd-levels-only' is set, level corresponds to
1939 order in hierarchy, not to the number of stars.
1941 Each element of this list generates a set of possible targets.
1942 The union of these sets is presented (with completion) to
1943 the user by `org-refile'.
1945 You can set the variable `org-refile-target-verify-function' to a function
1946 to verify each headline found by the simple criteria above.
1948 When this variable is nil, all top-level headlines in the current buffer
1949 are used, equivalent to the value `((nil . (:level . 1))'."
1950 :group 'org-refile
1951 :type '(repeat
1952 (cons
1953 (choice :value org-agenda-files
1954 (const :tag "All agenda files" org-agenda-files)
1955 (const :tag "Current buffer" nil)
1956 (function) (variable) (file))
1957 (choice :tag "Identify target headline by"
1958 (cons :tag "Specific tag" (const :value :tag) (string))
1959 (cons :tag "TODO keyword" (const :value :todo) (string))
1960 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1961 (cons :tag "Level number" (const :value :level) (integer))
1962 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1964 (defcustom org-refile-target-verify-function nil
1965 "Function to verify if the headline at point should be a refile target.
1966 The function will be called without arguments, with point at the
1967 beginning of the headline. It should return t and leave point
1968 where it is if the headline is a valid target for refiling.
1970 If the target should not be selected, the function must return nil.
1971 In addition to this, it may move point to a place from where the search
1972 should be continued. For example, the function may decide that the entire
1973 subtree of the current entry should be excluded and move point to the end
1974 of the subtree."
1975 :group 'org-refile
1976 :type 'function)
1978 (defcustom org-refile-use-cache nil
1979 "Non-nil means cache refile targets to speed up the process.
1980 The cache for a particular file will be updated automatically when
1981 the buffer has been killed, or when any of the marker used for flagging
1982 refile targets no longer points at a live buffer.
1983 If you have added new entries to a buffer that might themselves be targets,
1984 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1985 find that easier, `C-u C-u C-u C-c C-w'."
1986 :group 'org-refile
1987 :version "24.1"
1988 :type 'boolean)
1990 (defcustom org-refile-use-outline-path nil
1991 "Non-nil means provide refile targets as paths.
1992 So a level 3 headline will be available as level1/level2/level3.
1994 When the value is `file', also include the file name (without directory)
1995 into the path. In this case, you can also stop the completion after
1996 the file name, to get entries inserted as top level in the file.
1998 When `full-file-path', include the full file path."
1999 :group 'org-refile
2000 :type '(choice
2001 (const :tag "Not" nil)
2002 (const :tag "Yes" t)
2003 (const :tag "Start with file name" file)
2004 (const :tag "Start with full file path" full-file-path)))
2006 (defcustom org-outline-path-complete-in-steps t
2007 "Non-nil means complete the outline path in hierarchical steps.
2008 When Org-mode uses the refile interface to select an outline path
2009 \(see variable `org-refile-use-outline-path'), the completion of
2010 the path can be done is a single go, or if can be done in steps down
2011 the headline hierarchy. Going in steps is probably the best if you
2012 do not use a special completion package like `ido' or `icicles'.
2013 However, when using these packages, going in one step can be very
2014 fast, while still showing the whole path to the entry."
2015 :group 'org-refile
2016 :type 'boolean)
2018 (defcustom org-refile-allow-creating-parent-nodes nil
2019 "Non-nil means allow to create new nodes as refile targets.
2020 New nodes are then created by adding \"/new node name\" to the completion
2021 of an existing node. When the value of this variable is `confirm',
2022 new node creation must be confirmed by the user (recommended)
2023 When nil, the completion must match an existing entry.
2025 Note that, if the new heading is not seen by the criteria
2026 listed in `org-refile-targets', multiple instances of the same
2027 heading would be created by trying again to file under the new
2028 heading."
2029 :group 'org-refile
2030 :type '(choice
2031 (const :tag "Never" nil)
2032 (const :tag "Always" t)
2033 (const :tag "Prompt for confirmation" confirm)))
2035 (defcustom org-refile-active-region-within-subtree nil
2036 "Non-nil means also refile active region within a subtree.
2038 By default `org-refile' doesn't allow refiling regions if they
2039 don't contain a set of subtrees, but it might be convenient to
2040 do so sometimes: in that case, the first line of the region is
2041 converted to a headline before refiling."
2042 :group 'org-refile
2043 :version "24.1"
2044 :type 'boolean)
2046 (defgroup org-todo nil
2047 "Options concerning TODO items in Org-mode."
2048 :tag "Org TODO"
2049 :group 'org)
2051 (defgroup org-progress nil
2052 "Options concerning Progress logging in Org-mode."
2053 :tag "Org Progress"
2054 :group 'org-time)
2056 (defvar org-todo-interpretation-widgets
2057 '((:tag "Sequence (cycling hits every state)" sequence)
2058 (:tag "Type (cycling directly to DONE)" type))
2059 "The available interpretation symbols for customizing `org-todo-keywords'.
2060 Interested libraries should add to this list.")
2062 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2063 "List of TODO entry keyword sequences and their interpretation.
2064 \\<org-mode-map>This is a list of sequences.
2066 Each sequence starts with a symbol, either `sequence' or `type',
2067 indicating if the keywords should be interpreted as a sequence of
2068 action steps, or as different types of TODO items. The first
2069 keywords are states requiring action - these states will select a headline
2070 for inclusion into the global TODO list Org-mode produces. If one of
2071 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2072 signify that no further action is necessary. If \"|\" is not found,
2073 the last keyword is treated as the only DONE state of the sequence.
2075 The command \\[org-todo] cycles an entry through these states, and one
2076 additional state where no keyword is present. For details about this
2077 cycling, see the manual.
2079 TODO keywords and interpretation can also be set on a per-file basis with
2080 the special #+SEQ_TODO and #+TYP_TODO lines.
2082 Each keyword can optionally specify a character for fast state selection
2083 \(in combination with the variable `org-use-fast-todo-selection')
2084 and specifiers for state change logging, using the same syntax that
2085 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2086 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2087 indicates to record a time stamp each time this state is selected.
2089 Each keyword may also specify if a timestamp or a note should be
2090 recorded when entering or leaving the state, by adding additional
2091 characters in the parenthesis after the keyword. This looks like this:
2092 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2093 record only the time of the state change. With X and Y being either
2094 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2095 Y when leaving the state if and only if the *target* state does not
2096 define X. You may omit any of the fast-selection key or X or /Y,
2097 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2099 For backward compatibility, this variable may also be just a list
2100 of keywords. In this case the interpretation (sequence or type) will be
2101 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2102 :group 'org-todo
2103 :group 'org-keywords
2104 :type '(choice
2105 (repeat :tag "Old syntax, just keywords"
2106 (string :tag "Keyword"))
2107 (repeat :tag "New syntax"
2108 (cons
2109 (choice
2110 :tag "Interpretation"
2111 ;;Quick and dirty way to see
2112 ;;`org-todo-interpretations'. This takes the
2113 ;;place of item arguments
2114 :convert-widget
2115 (lambda (widget)
2116 (widget-put widget
2117 :args (mapcar
2118 #'(lambda (x)
2119 (widget-convert
2120 (cons 'const x)))
2121 org-todo-interpretation-widgets))
2122 widget))
2123 (repeat
2124 (string :tag "Keyword"))))))
2126 (defvar org-todo-keywords-1 nil
2127 "All TODO and DONE keywords active in a buffer.")
2128 (make-variable-buffer-local 'org-todo-keywords-1)
2129 (defvar org-todo-keywords-for-agenda nil)
2130 (defvar org-done-keywords-for-agenda nil)
2131 (defvar org-drawers-for-agenda nil)
2132 (defvar org-todo-keyword-alist-for-agenda nil)
2133 (defvar org-tag-alist-for-agenda nil)
2134 (defvar org-agenda-contributing-files nil)
2135 (defvar org-not-done-keywords nil)
2136 (make-variable-buffer-local 'org-not-done-keywords)
2137 (defvar org-done-keywords nil)
2138 (make-variable-buffer-local 'org-done-keywords)
2139 (defvar org-todo-heads nil)
2140 (make-variable-buffer-local 'org-todo-heads)
2141 (defvar org-todo-sets nil)
2142 (make-variable-buffer-local 'org-todo-sets)
2143 (defvar org-todo-log-states nil)
2144 (make-variable-buffer-local 'org-todo-log-states)
2145 (defvar org-todo-kwd-alist nil)
2146 (make-variable-buffer-local 'org-todo-kwd-alist)
2147 (defvar org-todo-key-alist nil)
2148 (make-variable-buffer-local 'org-todo-key-alist)
2149 (defvar org-todo-key-trigger nil)
2150 (make-variable-buffer-local 'org-todo-key-trigger)
2152 (defcustom org-todo-interpretation 'sequence
2153 "Controls how TODO keywords are interpreted.
2154 This variable is in principle obsolete and is only used for
2155 backward compatibility, if the interpretation of todo keywords is
2156 not given already in `org-todo-keywords'. See that variable for
2157 more information."
2158 :group 'org-todo
2159 :group 'org-keywords
2160 :type '(choice (const sequence)
2161 (const type)))
2163 (defcustom org-use-fast-todo-selection t
2164 "Non-nil means use the fast todo selection scheme with C-c C-t.
2165 This variable describes if and under what circumstances the cycling
2166 mechanism for TODO keywords will be replaced by a single-key, direct
2167 selection scheme.
2169 When nil, fast selection is never used.
2171 When the symbol `prefix', it will be used when `org-todo' is called
2172 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2173 `C-u t' in an agenda buffer.
2175 When t, fast selection is used by default. In this case, the prefix
2176 argument forces cycling instead.
2178 In all cases, the special interface is only used if access keys have
2179 actually been assigned by the user, i.e. if keywords in the configuration
2180 are followed by a letter in parenthesis, like TODO(t)."
2181 :group 'org-todo
2182 :type '(choice
2183 (const :tag "Never" nil)
2184 (const :tag "By default" t)
2185 (const :tag "Only with C-u C-c C-t" prefix)))
2187 (defcustom org-provide-todo-statistics t
2188 "Non-nil means update todo statistics after insert and toggle.
2189 ALL-HEADLINES means update todo statistics by including headlines
2190 with no TODO keyword as well, counting them as not done.
2191 A list of TODO keywords means the same, but skip keywords that are
2192 not in this list.
2194 When this is set, todo statistics is updated in the parent of the
2195 current entry each time a todo state is changed."
2196 :group 'org-todo
2197 :type '(choice
2198 (const :tag "Yes, only for TODO entries" t)
2199 (const :tag "Yes, including all entries" 'all-headlines)
2200 (repeat :tag "Yes, for TODOs in this list"
2201 (string :tag "TODO keyword"))
2202 (other :tag "No TODO statistics" nil)))
2204 (defcustom org-hierarchical-todo-statistics t
2205 "Non-nil means TODO statistics covers just direct children.
2206 When nil, all entries in the subtree are considered.
2207 This has only an effect if `org-provide-todo-statistics' is set.
2208 To set this to nil for only a single subtree, use a COOKIE_DATA
2209 property and include the word \"recursive\" into the value."
2210 :group 'org-todo
2211 :type 'boolean)
2213 (defcustom org-after-todo-state-change-hook nil
2214 "Hook which is run after the state of a TODO item was changed.
2215 The new state (a string with a TODO keyword, or nil) is available in the
2216 Lisp variable `org-state'."
2217 :group 'org-todo
2218 :type 'hook)
2220 (defvar org-blocker-hook nil
2221 "Hook for functions that are allowed to block a state change.
2223 Each function gets as its single argument a property list, see
2224 `org-trigger-hook' for more information about this list.
2226 If any of the functions in this hook returns nil, the state change
2227 is blocked.")
2229 (defvar org-trigger-hook nil
2230 "Hook for functions that are triggered by a state change.
2232 Each function gets as its single argument a property list with at least
2233 the following elements:
2235 (:type type-of-change :position pos-at-entry-start
2236 :from old-state :to new-state)
2238 Depending on the type, more properties may be present.
2240 This mechanism is currently implemented for:
2242 TODO state changes
2243 ------------------
2244 :type todo-state-change
2245 :from previous state (keyword as a string), or nil, or a symbol
2246 'todo' or 'done', to indicate the general type of state.
2247 :to new state, like in :from")
2249 (defcustom org-enforce-todo-dependencies nil
2250 "Non-nil means undone TODO entries will block switching the parent to DONE.
2251 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2252 be blocked if any prior sibling is not yet done.
2253 Finally, if the parent is blocked because of ordered siblings of its own,
2254 the child will also be blocked."
2255 :set (lambda (var val)
2256 (set var val)
2257 (if val
2258 (add-hook 'org-blocker-hook
2259 'org-block-todo-from-children-or-siblings-or-parent)
2260 (remove-hook 'org-blocker-hook
2261 'org-block-todo-from-children-or-siblings-or-parent)))
2262 :group 'org-todo
2263 :type 'boolean)
2265 (defcustom org-enforce-todo-checkbox-dependencies nil
2266 "Non-nil means unchecked boxes will block switching the parent to DONE.
2267 When this is nil, checkboxes have no influence on switching TODO states.
2268 When non-nil, you first need to check off all check boxes before the TODO
2269 entry can be switched to DONE.
2270 This variable needs to be set before org.el is loaded, and you need to
2271 restart Emacs after a change to make the change effective. The only way
2272 to change is while Emacs is running is through the customize interface."
2273 :set (lambda (var val)
2274 (set var val)
2275 (if val
2276 (add-hook 'org-blocker-hook
2277 'org-block-todo-from-checkboxes)
2278 (remove-hook 'org-blocker-hook
2279 'org-block-todo-from-checkboxes)))
2280 :group 'org-todo
2281 :type 'boolean)
2283 (defcustom org-treat-insert-todo-heading-as-state-change nil
2284 "Non-nil means inserting a TODO heading is treated as state change.
2285 So when the command \\[org-insert-todo-heading] is used, state change
2286 logging will apply if appropriate. When nil, the new TODO item will
2287 be inserted directly, and no logging will take place."
2288 :group 'org-todo
2289 :type 'boolean)
2291 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2292 "Non-nil means switching TODO states with S-cursor counts as state change.
2293 This is the default behavior. However, setting this to nil allows a
2294 convenient way to select a TODO state and bypass any logging associated
2295 with that."
2296 :group 'org-todo
2297 :type 'boolean)
2299 (defcustom org-todo-state-tags-triggers nil
2300 "Tag changes that should be triggered by TODO state changes.
2301 This is a list. Each entry is
2303 (state-change (tag . flag) .......)
2305 State-change can be a string with a state, and empty string to indicate the
2306 state that has no TODO keyword, or it can be one of the symbols `todo'
2307 or `done', meaning any not-done or done state, respectively."
2308 :group 'org-todo
2309 :group 'org-tags
2310 :type '(repeat
2311 (cons (choice :tag "When changing to"
2312 (const :tag "Not-done state" todo)
2313 (const :tag "Done state" done)
2314 (string :tag "State"))
2315 (repeat
2316 (cons :tag "Tag action"
2317 (string :tag "Tag")
2318 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2320 (defcustom org-log-done nil
2321 "Information to record when a task moves to the DONE state.
2323 Possible values are:
2325 nil Don't add anything, just change the keyword
2326 time Add a time stamp to the task
2327 note Prompt for a note and add it with template `org-log-note-headings'
2329 This option can also be set with on a per-file-basis with
2331 #+STARTUP: nologdone
2332 #+STARTUP: logdone
2333 #+STARTUP: lognotedone
2335 You can have local logging settings for a subtree by setting the LOGGING
2336 property to one or more of these keywords."
2337 :group 'org-todo
2338 :group 'org-progress
2339 :type '(choice
2340 (const :tag "No logging" nil)
2341 (const :tag "Record CLOSED timestamp" time)
2342 (const :tag "Record CLOSED timestamp with note." note)))
2344 ;; Normalize old uses of org-log-done.
2345 (cond
2346 ((eq org-log-done t) (setq org-log-done 'time))
2347 ((and (listp org-log-done) (memq 'done org-log-done))
2348 (setq org-log-done 'note)))
2350 (defcustom org-log-reschedule nil
2351 "Information to record when the scheduling date of a tasks is modified.
2353 Possible values are:
2355 nil Don't add anything, just change the date
2356 time Add a time stamp to the task
2357 note Prompt for a note and add it with template `org-log-note-headings'
2359 This option can also be set with on a per-file-basis with
2361 #+STARTUP: nologreschedule
2362 #+STARTUP: logreschedule
2363 #+STARTUP: lognotereschedule"
2364 :group 'org-todo
2365 :group 'org-progress
2366 :type '(choice
2367 (const :tag "No logging" nil)
2368 (const :tag "Record timestamp" time)
2369 (const :tag "Record timestamp with note." note)))
2371 (defcustom org-log-redeadline nil
2372 "Information to record when the deadline date of a tasks is modified.
2374 Possible values are:
2376 nil Don't add anything, just change the date
2377 time Add a time stamp to the task
2378 note Prompt for a note and add it with template `org-log-note-headings'
2380 This option can also be set with on a per-file-basis with
2382 #+STARTUP: nologredeadline
2383 #+STARTUP: logredeadline
2384 #+STARTUP: lognoteredeadline
2386 You can have local logging settings for a subtree by setting the LOGGING
2387 property to one or more of these keywords."
2388 :group 'org-todo
2389 :group 'org-progress
2390 :type '(choice
2391 (const :tag "No logging" nil)
2392 (const :tag "Record timestamp" time)
2393 (const :tag "Record timestamp with note." note)))
2395 (defcustom org-log-note-clock-out nil
2396 "Non-nil means record a note when clocking out of an item.
2397 This can also be configured on a per-file basis by adding one of
2398 the following lines anywhere in the buffer:
2400 #+STARTUP: lognoteclock-out
2401 #+STARTUP: nolognoteclock-out"
2402 :group 'org-todo
2403 :group 'org-progress
2404 :type 'boolean)
2406 (defcustom org-log-done-with-time t
2407 "Non-nil means the CLOSED time stamp will contain date and time.
2408 When nil, only the date will be recorded."
2409 :group 'org-progress
2410 :type 'boolean)
2412 (defcustom org-log-note-headings
2413 '((done . "CLOSING NOTE %t")
2414 (state . "State %-12s from %-12S %t")
2415 (note . "Note taken on %t")
2416 (reschedule . "Rescheduled from %S on %t")
2417 (delschedule . "Not scheduled, was %S on %t")
2418 (redeadline . "New deadline from %S on %t")
2419 (deldeadline . "Removed deadline, was %S on %t")
2420 (refile . "Refiled on %t")
2421 (clock-out . ""))
2422 "Headings for notes added to entries.
2423 The value is an alist, with the car being a symbol indicating the note
2424 context, and the cdr is the heading to be used. The heading may also be the
2425 empty string.
2426 %t in the heading will be replaced by a time stamp.
2427 %T will be an active time stamp instead the default inactive one
2428 %d will be replaced by a short-format time stamp.
2429 %D will be replaced by an active short-format time stamp.
2430 %s will be replaced by the new TODO state, in double quotes.
2431 %S will be replaced by the old TODO state, in double quotes.
2432 %u will be replaced by the user name.
2433 %U will be replaced by the full user name.
2435 In fact, it is not a good idea to change the `state' entry, because
2436 agenda log mode depends on the format of these entries."
2437 :group 'org-todo
2438 :group 'org-progress
2439 :type '(list :greedy t
2440 (cons (const :tag "Heading when closing an item" done) string)
2441 (cons (const :tag
2442 "Heading when changing todo state (todo sequence only)"
2443 state) string)
2444 (cons (const :tag "Heading when just taking a note" note) string)
2445 (cons (const :tag "Heading when clocking out" clock-out) string)
2446 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2447 (cons (const :tag "Heading when rescheduling" reschedule) string)
2448 (cons (const :tag "Heading when changing deadline" redeadline) string)
2449 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2450 (cons (const :tag "Heading when refiling" refile) string)))
2452 (unless (assq 'note org-log-note-headings)
2453 (push '(note . "%t") org-log-note-headings))
2455 (defcustom org-log-into-drawer nil
2456 "Non-nil means insert state change notes and time stamps into a drawer.
2457 When nil, state changes notes will be inserted after the headline and
2458 any scheduling and clock lines, but not inside a drawer.
2460 The value of this variable should be the name of the drawer to use.
2461 LOGBOOK is proposed as the default drawer for this purpose, you can
2462 also set this to a string to define the drawer of your choice.
2464 A value of t is also allowed, representing \"LOGBOOK\".
2466 If this variable is set, `org-log-state-notes-insert-after-drawers'
2467 will be ignored.
2469 You can set the property LOG_INTO_DRAWER to overrule this setting for
2470 a subtree."
2471 :group 'org-todo
2472 :group 'org-progress
2473 :type '(choice
2474 (const :tag "Not into a drawer" nil)
2475 (const :tag "LOGBOOK" t)
2476 (string :tag "Other")))
2478 (if (fboundp 'defvaralias)
2479 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2481 (defun org-log-into-drawer ()
2482 "Return the value of `org-log-into-drawer', but let properties overrule.
2483 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2484 used instead of the default value."
2485 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2486 (cond
2487 ((or (not p) (equal p "nil")) org-log-into-drawer)
2488 ((equal p "t") "LOGBOOK")
2489 (t p))))
2491 (defcustom org-log-state-notes-insert-after-drawers nil
2492 "Non-nil means insert state change notes after any drawers in entry.
2493 Only the drawers that *immediately* follow the headline and the
2494 deadline/scheduled line are skipped.
2495 When nil, insert notes right after the heading and perhaps the line
2496 with deadline/scheduling if present.
2498 This variable will have no effect if `org-log-into-drawer' is
2499 set."
2500 :group 'org-todo
2501 :group 'org-progress
2502 :type 'boolean)
2504 (defcustom org-log-states-order-reversed t
2505 "Non-nil means the latest state note will be directly after heading.
2506 When nil, the state change notes will be ordered according to time."
2507 :group 'org-todo
2508 :group 'org-progress
2509 :type 'boolean)
2511 (defcustom org-todo-repeat-to-state nil
2512 "The TODO state to which a repeater should return the repeating task.
2513 By default this is the first task in a TODO sequence, or the previous state
2514 in a TODO_TYP set. But you can specify another task here.
2515 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2516 :group 'org-todo
2517 :version "24.1"
2518 :type '(choice (const :tag "Head of sequence" nil)
2519 (string :tag "Specific state")))
2521 (defcustom org-log-repeat 'time
2522 "Non-nil means record moving through the DONE state when triggering repeat.
2523 An auto-repeating task is immediately switched back to TODO when
2524 marked DONE. If you are not logging state changes (by adding \"@\"
2525 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2526 record a closing note, there will be no record of the task moving
2527 through DONE. This variable forces taking a note anyway.
2529 nil Don't force a record
2530 time Record a time stamp
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologrepeat
2536 #+STARTUP: logrepeat
2537 #+STARTUP: lognoterepeat
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "Don't force a record" nil)
2545 (const :tag "Force recording the DONE state" time)
2546 (const :tag "Force recording a note with the DONE state" note)))
2549 (defgroup org-priorities nil
2550 "Priorities in Org-mode."
2551 :tag "Org Priorities"
2552 :group 'org-todo)
2554 (defcustom org-enable-priority-commands t
2555 "Non-nil means priority commands are active.
2556 When nil, these commands will be disabled, so that you never accidentally
2557 set a priority."
2558 :group 'org-priorities
2559 :type 'boolean)
2561 (defcustom org-highest-priority ?A
2562 "The highest priority of TODO items. A character like ?A, ?B etc.
2563 Must have a smaller ASCII number than `org-lowest-priority'."
2564 :group 'org-priorities
2565 :type 'character)
2567 (defcustom org-lowest-priority ?C
2568 "The lowest priority of TODO items. A character like ?A, ?B etc.
2569 Must have a larger ASCII number than `org-highest-priority'."
2570 :group 'org-priorities
2571 :type 'character)
2573 (defcustom org-default-priority ?B
2574 "The default priority of TODO items.
2575 This is the priority an item gets if no explicit priority is given.
2576 When starting to cycle on an empty priority the first step in the cycle
2577 depends on `org-priority-start-cycle-with-default'. The resulting first
2578 step priority must not exceed the range from `org-highest-priority' to
2579 `org-lowest-priority' which means that `org-default-priority' has to be
2580 in this range exclusive or inclusive the range boundaries. Else the
2581 first step refuses to set the default and the second will fall back
2582 to (depending on the command used) the highest or lowest priority."
2583 :group 'org-priorities
2584 :type 'character)
2586 (defcustom org-priority-start-cycle-with-default t
2587 "Non-nil means start with default priority when starting to cycle.
2588 When this is nil, the first step in the cycle will be (depending on the
2589 command used) one higher or lower than the default priority.
2590 See also `org-default-priority'."
2591 :group 'org-priorities
2592 :type 'boolean)
2594 (defcustom org-get-priority-function nil
2595 "Function to extract the priority from a string.
2596 The string is normally the headline. If this is nil Org computes the
2597 priority from the priority cookie like [#A] in the headline. It returns
2598 an integer, increasing by 1000 for each priority level.
2599 The user can set a different function here, which should take a string
2600 as an argument and return the numeric priority."
2601 :group 'org-priorities
2602 :version "24.1"
2603 :type 'function)
2605 (defgroup org-time nil
2606 "Options concerning time stamps and deadlines in Org-mode."
2607 :tag "Org Time"
2608 :group 'org)
2610 (defcustom org-insert-labeled-timestamps-at-point nil
2611 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2612 When nil, these labeled time stamps are forces into the second line of an
2613 entry, just after the headline. When scheduling from the global TODO list,
2614 the time stamp will always be forced into the second line."
2615 :group 'org-time
2616 :type 'boolean)
2618 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2619 "Formats for `format-time-string' which are used for time stamps.
2620 It is not recommended to change this constant.")
2622 (defcustom org-time-stamp-rounding-minutes '(0 5)
2623 "Number of minutes to round time stamps to.
2624 These are two values, the first applies when first creating a time stamp.
2625 The second applies when changing it with the commands `S-up' and `S-down'.
2626 When changing the time stamp, this means that it will change in steps
2627 of N minutes, as given by the second value.
2629 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2630 numbers should be factors of 60, so for example 5, 10, 15.
2632 When this is larger than 1, you can still force an exact time stamp by using
2633 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2634 and by using a prefix arg to `S-up/down' to specify the exact number
2635 of minutes to shift."
2636 :group 'org-time
2637 :get #'(lambda (var) ; Make sure both elements are there
2638 (if (integerp (default-value var))
2639 (list (default-value var) 5)
2640 (default-value var)))
2641 :type '(list
2642 (integer :tag "when inserting times")
2643 (integer :tag "when modifying times")))
2645 ;; Normalize old customizations of this variable.
2646 (when (integerp org-time-stamp-rounding-minutes)
2647 (setq org-time-stamp-rounding-minutes
2648 (list org-time-stamp-rounding-minutes
2649 org-time-stamp-rounding-minutes)))
2651 (defcustom org-display-custom-times nil
2652 "Non-nil means overlay custom formats over all time stamps.
2653 The formats are defined through the variable `org-time-stamp-custom-formats'.
2654 To turn this on on a per-file basis, insert anywhere in the file:
2655 #+STARTUP: customtime"
2656 :group 'org-time
2657 :set 'set-default
2658 :type 'sexp)
2659 (make-variable-buffer-local 'org-display-custom-times)
2661 (defcustom org-time-stamp-custom-formats
2662 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2663 "Custom formats for time stamps. See `format-time-string' for the syntax.
2664 These are overlaid over the default ISO format if the variable
2665 `org-display-custom-times' is set. Time like %H:%M should be at the
2666 end of the second format. The custom formats are also honored by export
2667 commands, if custom time display is turned on at the time of export."
2668 :group 'org-time
2669 :type 'sexp)
2671 (defun org-time-stamp-format (&optional long inactive)
2672 "Get the right format for a time string."
2673 (let ((f (if long (cdr org-time-stamp-formats)
2674 (car org-time-stamp-formats))))
2675 (if inactive
2676 (concat "[" (substring f 1 -1) "]")
2677 f)))
2679 (defcustom org-time-clocksum-format "%d:%02d"
2680 "The format string used when creating CLOCKSUM lines.
2681 This is also used when org-mode generates a time duration."
2682 :group 'org-time
2683 :type 'string)
2685 (defcustom org-time-clocksum-use-fractional nil
2686 "If non-nil, \\[org-clock-display] uses fractional times.
2687 org-mode generates a time duration."
2688 :group 'org-time
2689 :type 'boolean)
2691 (defcustom org-time-clocksum-fractional-format "%.2f"
2692 "The format string used when creating CLOCKSUM lines, or when
2693 org-mode generates a time duration."
2694 :group 'org-time
2695 :type 'string)
2697 (defcustom org-deadline-warning-days 14
2698 "No. of days before expiration during which a deadline becomes active.
2699 This variable governs the display in sparse trees and in the agenda.
2700 When 0 or negative, it means use this number (the absolute value of it)
2701 even if a deadline has a different individual lead time specified.
2703 Custom commands can set this variable in the options section."
2704 :group 'org-time
2705 :group 'org-agenda-daily/weekly
2706 :type 'integer)
2708 (defcustom org-read-date-prefer-future t
2709 "Non-nil means assume future for incomplete date input from user.
2710 This affects the following situations:
2711 1. The user gives a month but not a year.
2712 For example, if it is April and you enter \"feb 2\", this will be read
2713 as Feb 2, *next* year. \"May 5\", however, will be this year.
2714 2. The user gives a day, but no month.
2715 For example, if today is the 15th, and you enter \"3\", Org-mode will
2716 read this as the third of *next* month. However, if you enter \"17\",
2717 it will be considered as *this* month.
2719 If you set this variable to the symbol `time', then also the following
2720 will work:
2722 3. If the user gives a time.
2723 If the time is before now, it will be interpreted as tomorrow.
2725 Currently none of this works for ISO week specifications.
2727 When this option is nil, the current day, month and year will always be
2728 used as defaults.
2730 See also `org-agenda-jump-prefer-future'."
2731 :group 'org-time
2732 :type '(choice
2733 (const :tag "Never" nil)
2734 (const :tag "Check month and day" t)
2735 (const :tag "Check month, day, and time" time)))
2737 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2738 "Should the agenda jump command prefer the future for incomplete dates?
2739 The default is to do the same as configured in `org-read-date-prefer-future'.
2740 But you can also set a deviating value here.
2741 This may t or nil, or the symbol `org-read-date-prefer-future'."
2742 :group 'org-agenda
2743 :group 'org-time
2744 :version "24.1"
2745 :type '(choice
2746 (const :tag "Use org-read-date-prefer-future"
2747 org-read-date-prefer-future)
2748 (const :tag "Never" nil)
2749 (const :tag "Always" t)))
2751 (defcustom org-read-date-force-compatible-dates t
2752 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2754 Depending on the system Emacs is running on, certain dates cannot
2755 be represented with the type used internally to represent time.
2756 Dates between 1970-1-1 and 2038-1-1 can always be represented
2757 correctly. Some systems allow for earlier dates, some for later,
2758 some for both. One way to find out it to insert any date into an
2759 Org buffer, putting the cursor on the year and hitting S-up and
2760 S-down to test the range.
2762 When this variable is set to t, the date/time prompt will not let
2763 you specify dates outside the 1970-2037 range, so it is certain that
2764 these dates will work in whatever version of Emacs you are
2765 running, and also that you can move a file from one Emacs implementation
2766 to another. WHenever Org is forcing the year for you, it will display
2767 a message and beep.
2769 When this variable is nil, Org will check if the date is
2770 representable in the specific Emacs implementation you are using.
2771 If not, it will force a year, usually the current year, and beep
2772 to remind you. Currently this setting is not recommended because
2773 the likelihood that you will open your Org files in an Emacs that
2774 has limited date range is not negligible.
2776 A workaround for this problem is to use diary sexp dates for time
2777 stamps outside of this range."
2778 :group 'org-time
2779 :version "24.1"
2780 :type 'boolean)
2782 (defcustom org-read-date-display-live t
2783 "Non-nil means display current interpretation of date prompt live.
2784 This display will be in an overlay, in the minibuffer."
2785 :group 'org-time
2786 :type 'boolean)
2788 (defcustom org-read-date-popup-calendar t
2789 "Non-nil means pop up a calendar when prompting for a date.
2790 In the calendar, the date can be selected with mouse-1. However, the
2791 minibuffer will also be active, and you can simply enter the date as well.
2792 When nil, only the minibuffer will be available."
2793 :group 'org-time
2794 :type 'boolean)
2795 (if (fboundp 'defvaralias)
2796 (defvaralias 'org-popup-calendar-for-date-prompt
2797 'org-read-date-popup-calendar))
2799 (defcustom org-read-date-minibuffer-setup-hook nil
2800 "Hook to be used to set up keys for the date/time interface.
2801 Add key definitions to `minibuffer-local-map', which will be a temporary
2802 copy."
2803 :group 'org-time
2804 :type 'hook)
2806 (defcustom org-extend-today-until 0
2807 "The hour when your day really ends. Must be an integer.
2808 This has influence for the following applications:
2809 - When switching the agenda to \"today\". It it is still earlier than
2810 the time given here, the day recognized as TODAY is actually yesterday.
2811 - When a date is read from the user and it is still before the time given
2812 here, the current date and time will be assumed to be yesterday, 23:59.
2813 Also, timestamps inserted in capture templates follow this rule.
2815 IMPORTANT: This is a feature whose implementation is and likely will
2816 remain incomplete. Really, it is only here because past midnight seems to
2817 be the favorite working time of John Wiegley :-)"
2818 :group 'org-time
2819 :type 'integer)
2821 (defcustom org-use-effective-time nil
2822 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2823 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2824 \"effective time\" of any timestamps between midnight and 8am will be
2825 23:59 of the previous day."
2826 :group 'org-time
2827 :version "24.1"
2828 :type 'boolean)
2830 (defcustom org-edit-timestamp-down-means-later nil
2831 "Non-nil means S-down will increase the time in a time stamp.
2832 When nil, S-up will increase."
2833 :group 'org-time
2834 :type 'boolean)
2836 (defcustom org-calendar-follow-timestamp-change t
2837 "Non-nil means make the calendar window follow timestamp changes.
2838 When a timestamp is modified and the calendar window is visible, it will be
2839 moved to the new date."
2840 :group 'org-time
2841 :type 'boolean)
2843 (defgroup org-tags nil
2844 "Options concerning tags in Org-mode."
2845 :tag "Org Tags"
2846 :group 'org)
2848 (defcustom org-tag-alist nil
2849 "List of tags allowed in Org-mode files.
2850 When this list is nil, Org-mode will base TAG input on what is already in the
2851 buffer.
2852 The value of this variable is an alist, the car of each entry must be a
2853 keyword as a string, the cdr may be a character that is used to select
2854 that tag through the fast-tag-selection interface.
2855 See the manual for details."
2856 :group 'org-tags
2857 :type '(repeat
2858 (choice
2859 (cons (string :tag "Tag name")
2860 (character :tag "Access char"))
2861 (list :tag "Start radio group"
2862 (const :startgroup)
2863 (option (string :tag "Group description")))
2864 (list :tag "End radio group"
2865 (const :endgroup)
2866 (option (string :tag "Group description")))
2867 (const :tag "New line" (:newline)))))
2869 (defcustom org-tag-persistent-alist nil
2870 "List of tags that will always appear in all Org-mode files.
2871 This is in addition to any in buffer settings or customizations
2872 of `org-tag-alist'.
2873 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2874 The value of this variable is an alist, the car of each entry must be a
2875 keyword as a string, the cdr may be a character that is used to select
2876 that tag through the fast-tag-selection interface.
2877 See the manual for details.
2878 To disable these tags on a per-file basis, insert anywhere in the file:
2879 #+STARTUP: noptag"
2880 :group 'org-tags
2881 :type '(repeat
2882 (choice
2883 (cons (string :tag "Tag name")
2884 (character :tag "Access char"))
2885 (const :tag "Start radio group" (:startgroup))
2886 (const :tag "End radio group" (:endgroup))
2887 (const :tag "New line" (:newline)))))
2889 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2890 "If non-nil, always offer completion for all tags of all agenda files.
2891 Instead of customizing this variable directly, you might want to
2892 set it locally for capture buffers, because there no list of
2893 tags in that file can be created dynamically (there are none).
2895 (add-hook 'org-capture-mode-hook
2896 (lambda ()
2897 (set (make-local-variable
2898 'org-complete-tags-always-offer-all-agenda-tags)
2899 t)))"
2900 :group 'org-tags
2901 :version "24.1"
2902 :type 'boolean)
2904 (defvar org-file-tags nil
2905 "List of tags that can be inherited by all entries in the file.
2906 The tags will be inherited if the variable `org-use-tag-inheritance'
2907 says they should be.
2908 This variable is populated from #+FILETAGS lines.")
2910 (defcustom org-use-fast-tag-selection 'auto
2911 "Non-nil means use fast tag selection scheme.
2912 This is a special interface to select and deselect tags with single keys.
2913 When nil, fast selection is never used.
2914 When the symbol `auto', fast selection is used if and only if selection
2915 characters for tags have been configured, either through the variable
2916 `org-tag-alist' or through a #+TAGS line in the buffer.
2917 When t, fast selection is always used and selection keys are assigned
2918 automatically if necessary."
2919 :group 'org-tags
2920 :type '(choice
2921 (const :tag "Always" t)
2922 (const :tag "Never" nil)
2923 (const :tag "When selection characters are configured" 'auto)))
2925 (defcustom org-fast-tag-selection-single-key nil
2926 "Non-nil means fast tag selection exits after first change.
2927 When nil, you have to press RET to exit it.
2928 During fast tag selection, you can toggle this flag with `C-c'.
2929 This variable can also have the value `expert'. In this case, the window
2930 displaying the tags menu is not even shown, until you press C-c again."
2931 :group 'org-tags
2932 :type '(choice
2933 (const :tag "No" nil)
2934 (const :tag "Yes" t)
2935 (const :tag "Expert" expert)))
2937 (defvar org-fast-tag-selection-include-todo nil
2938 "Non-nil means fast tags selection interface will also offer TODO states.
2939 This is an undocumented feature, you should not rely on it.")
2941 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2942 "The column to which tags should be indented in a headline.
2943 If this number is positive, it specifies the column. If it is negative,
2944 it means that the tags should be flushright to that column. For example,
2945 -80 works well for a normal 80 character screen.
2946 When 0, place tags directly after headline text, with only one space in
2947 between."
2948 :group 'org-tags
2949 :type 'integer)
2951 (defcustom org-auto-align-tags t
2952 "Non-nil keeps tags aligned when modifying headlines.
2953 Some operations (i.e. demoting) change the length of a headline and
2954 therefore shift the tags around. With this option turned on, after
2955 each such operation the tags are again aligned to `org-tags-column'."
2956 :group 'org-tags
2957 :type 'boolean)
2959 (defcustom org-use-tag-inheritance t
2960 "Non-nil means tags in levels apply also for sublevels.
2961 When nil, only the tags directly given in a specific line apply there.
2962 This may also be a list of tags that should be inherited, or a regexp that
2963 matches tags that should be inherited. Additional control is possible
2964 with the variable `org-tags-exclude-from-inheritance' which gives an
2965 explicit list of tags to be excluded from inheritance., even if the value of
2966 `org-use-tag-inheritance' would select it for inheritance.
2968 If this option is t, a match early-on in a tree can lead to a large
2969 number of matches in the subtree when constructing the agenda or creating
2970 a sparse tree. If you only want to see the first match in a tree during
2971 a search, check out the variable `org-tags-match-list-sublevels'."
2972 :group 'org-tags
2973 :type '(choice
2974 (const :tag "Not" nil)
2975 (const :tag "Always" t)
2976 (repeat :tag "Specific tags" (string :tag "Tag"))
2977 (regexp :tag "Tags matched by regexp")))
2979 (defcustom org-tags-exclude-from-inheritance nil
2980 "List of tags that should never be inherited.
2981 This is a way to exclude a few tags from inheritance. For way to do
2982 the opposite, to actively allow inheritance for selected tags,
2983 see the variable `org-use-tag-inheritance'."
2984 :group 'org-tags
2985 :type '(repeat (string :tag "Tag")))
2987 (defun org-tag-inherit-p (tag)
2988 "Check if TAG is one that should be inherited."
2989 (cond
2990 ((member tag org-tags-exclude-from-inheritance) nil)
2991 ((eq org-use-tag-inheritance t) t)
2992 ((not org-use-tag-inheritance) nil)
2993 ((stringp org-use-tag-inheritance)
2994 (string-match org-use-tag-inheritance tag))
2995 ((listp org-use-tag-inheritance)
2996 (member tag org-use-tag-inheritance))
2997 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2999 (defcustom org-tags-match-list-sublevels t
3000 "Non-nil means list also sublevels of headlines matching a search.
3001 This variable applies to tags/property searches, and also to stuck
3002 projects because this search is based on a tags match as well.
3004 When set to the symbol `indented', sublevels are indented with
3005 leading dots.
3007 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3008 the sublevels of a headline matching a tag search often also match
3009 the same search. Listing all of them can create very long lists.
3010 Setting this variable to nil causes subtrees of a match to be skipped.
3012 This variable is semi-obsolete and probably should always be true. It
3013 is better to limit inheritance to certain tags using the variables
3014 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3015 :group 'org-tags
3016 :type '(choice
3017 (const :tag "No, don't list them" nil)
3018 (const :tag "Yes, do list them" t)
3019 (const :tag "List them, indented with leading dots" indented)))
3021 (defcustom org-tags-sort-function nil
3022 "When set, tags are sorted using this function as a comparator."
3023 :group 'org-tags
3024 :type '(choice
3025 (const :tag "No sorting" nil)
3026 (const :tag "Alphabetical" string<)
3027 (const :tag "Reverse alphabetical" string>)
3028 (function :tag "Custom function" nil)))
3030 (defvar org-tags-history nil
3031 "History of minibuffer reads for tags.")
3032 (defvar org-last-tags-completion-table nil
3033 "The last used completion table for tags.")
3034 (defvar org-after-tags-change-hook nil
3035 "Hook that is run after the tags in a line have changed.")
3037 (defgroup org-properties nil
3038 "Options concerning properties in Org-mode."
3039 :tag "Org Properties"
3040 :group 'org)
3042 (defcustom org-property-format "%-10s %s"
3043 "How property key/value pairs should be formatted by `indent-line'.
3044 When `indent-line' hits a property definition, it will format the line
3045 according to this format, mainly to make sure that the values are
3046 lined-up with respect to each other."
3047 :group 'org-properties
3048 :type 'string)
3050 (defcustom org-properties-postprocess-alist nil
3051 "Alist of properties and functions to adjust inserted values.
3052 Elements of this alist must be of the form
3054 ([string] [function])
3056 where [string] must be a property name and [function] must be a
3057 lambda expression: this lambda expression must take one argument,
3058 the value to adjust, and return the new value as a string.
3060 For example, this element will allow the property \"Remaining\"
3061 to be updated wrt the relation between the \"Effort\" property
3062 and the clock summary:
3064 ((\"Remaining\" (lambda(value)
3065 (let ((clocksum (org-clock-sum-current-item))
3066 (effort (org-duration-string-to-minutes
3067 (org-entry-get (point) \"Effort\"))))
3068 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3069 :group 'org-properties
3070 :version "24.1"
3071 :type '(alist :key-type (string :tag "Property")
3072 :value-type (function :tag "Function")))
3074 (defcustom org-use-property-inheritance nil
3075 "Non-nil means properties apply also for sublevels.
3077 This setting is chiefly used during property searches. Turning it on can
3078 cause significant overhead when doing a search, which is why it is not
3079 on by default.
3081 When nil, only the properties directly given in the current entry count.
3082 When t, every property is inherited. The value may also be a list of
3083 properties that should have inheritance, or a regular expression matching
3084 properties that should be inherited.
3086 However, note that some special properties use inheritance under special
3087 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3088 and the properties ending in \"_ALL\" when they are used as descriptor
3089 for valid values of a property.
3091 Note for programmers:
3092 When querying an entry with `org-entry-get', you can control if inheritance
3093 should be used. By default, `org-entry-get' looks only at the local
3094 properties. You can request inheritance by setting the inherit argument
3095 to t (to force inheritance) or to `selective' (to respect the setting
3096 in this variable)."
3097 :group 'org-properties
3098 :type '(choice
3099 (const :tag "Not" nil)
3100 (const :tag "Always" t)
3101 (repeat :tag "Specific properties" (string :tag "Property"))
3102 (regexp :tag "Properties matched by regexp")))
3104 (defun org-property-inherit-p (property)
3105 "Check if PROPERTY is one that should be inherited."
3106 (cond
3107 ((eq org-use-property-inheritance t) t)
3108 ((not org-use-property-inheritance) nil)
3109 ((stringp org-use-property-inheritance)
3110 (string-match org-use-property-inheritance property))
3111 ((listp org-use-property-inheritance)
3112 (member property org-use-property-inheritance))
3113 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3115 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3116 "The default column format, if no other format has been defined.
3117 This variable can be set on the per-file basis by inserting a line
3119 #+COLUMNS: %25ITEM ....."
3120 :group 'org-properties
3121 :type 'string)
3123 (defcustom org-columns-ellipses ".."
3124 "The ellipses to be used when a field in column view is truncated.
3125 When this is the empty string, as many characters as possible are shown,
3126 but then there will be no visual indication that the field has been truncated.
3127 When this is a string of length N, the last N characters of a truncated
3128 field are replaced by this string. If the column is narrower than the
3129 ellipses string, only part of the ellipses string will be shown."
3130 :group 'org-properties
3131 :type 'string)
3133 (defcustom org-columns-modify-value-for-display-function nil
3134 "Function that modifies values for display in column view.
3135 For example, it can be used to cut out a certain part from a time stamp.
3136 The function must take 2 arguments:
3138 column-title The title of the column (*not* the property name)
3139 value The value that should be modified.
3141 The function should return the value that should be displayed,
3142 or nil if the normal value should be used."
3143 :group 'org-properties
3144 :type 'function)
3146 (defcustom org-effort-property "Effort"
3147 "The property that is being used to keep track of effort estimates.
3148 Effort estimates given in this property need to have the format H:MM."
3149 :group 'org-properties
3150 :group 'org-progress
3151 :type '(string :tag "Property"))
3153 (defconst org-global-properties-fixed
3154 '(("VISIBILITY_ALL" . "folded children content all")
3155 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3156 "List of property/value pairs that can be inherited by any entry.
3158 These are fixed values, for the preset properties. The user variable
3159 that can be used to add to this list is `org-global-properties'.
3161 The entries in this list are cons cells where the car is a property
3162 name and cdr is a string with the value. If the value represents
3163 multiple items like an \"_ALL\" property, separate the items by
3164 spaces.")
3166 (defcustom org-global-properties nil
3167 "List of property/value pairs that can be inherited by any entry.
3169 This list will be combined with the constant `org-global-properties-fixed'.
3171 The entries in this list are cons cells where the car is a property
3172 name and cdr is a string with the value.
3174 You can set buffer-local values for the same purpose in the variable
3175 `org-file-properties' this by adding lines like
3177 #+PROPERTY: NAME VALUE"
3178 :group 'org-properties
3179 :type '(repeat
3180 (cons (string :tag "Property")
3181 (string :tag "Value"))))
3183 (defvar org-file-properties nil
3184 "List of property/value pairs that can be inherited by any entry.
3185 Valid for the current buffer.
3186 This variable is populated from #+PROPERTY lines.")
3187 (make-variable-buffer-local 'org-file-properties)
3189 (defgroup org-agenda nil
3190 "Options concerning agenda views in Org-mode."
3191 :tag "Org Agenda"
3192 :group 'org)
3194 (defvar org-category nil
3195 "Variable used by org files to set a category for agenda display.
3196 Such files should use a file variable to set it, for example
3198 # -*- mode: org; org-category: \"ELisp\"
3200 or contain a special line
3202 #+CATEGORY: ELisp
3204 If the file does not specify a category, then file's base name
3205 is used instead.")
3206 (make-variable-buffer-local 'org-category)
3207 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3209 (defcustom org-agenda-files nil
3210 "The files to be used for agenda display.
3211 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3212 \\[org-remove-file]. You can also use customize to edit the list.
3214 If an entry is a directory, all files in that directory that are matched by
3215 `org-agenda-file-regexp' will be part of the file list.
3217 If the value of the variable is not a list but a single file name, then
3218 the list of agenda files is actually stored and maintained in that file, one
3219 agenda file per line. In this file paths can be given relative to
3220 `org-directory'. Tilde expansion and environment variable substitution
3221 are also made."
3222 :group 'org-agenda
3223 :type '(choice
3224 (repeat :tag "List of files and directories" file)
3225 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3227 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3228 "Regular expression to match files for `org-agenda-files'.
3229 If any element in the list in that variable contains a directory instead
3230 of a normal file, all files in that directory that are matched by this
3231 regular expression will be included."
3232 :group 'org-agenda
3233 :type 'regexp)
3235 (defcustom org-agenda-text-search-extra-files nil
3236 "List of extra files to be searched by text search commands.
3237 These files will be search in addition to the agenda files by the
3238 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3239 Note that these files will only be searched for text search commands,
3240 not for the other agenda views like todo lists, tag searches or the weekly
3241 agenda. This variable is intended to list notes and possibly archive files
3242 that should also be searched by these two commands.
3243 In fact, if the first element in the list is the symbol `agenda-archives',
3244 than all archive files of all agenda files will be added to the search
3245 scope."
3246 :group 'org-agenda
3247 :type '(set :greedy t
3248 (const :tag "Agenda Archives" agenda-archives)
3249 (repeat :inline t (file))))
3251 (if (fboundp 'defvaralias)
3252 (defvaralias 'org-agenda-multi-occur-extra-files
3253 'org-agenda-text-search-extra-files))
3255 (defcustom org-agenda-skip-unavailable-files nil
3256 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3257 A nil value means to remove them, after a query, from the list."
3258 :group 'org-agenda
3259 :type 'boolean)
3261 (defcustom org-calendar-to-agenda-key [?c]
3262 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3263 The command `org-calendar-goto-agenda' will be bound to this key. The
3264 default is the character `c' because then `c' can be used to switch back and
3265 forth between agenda and calendar."
3266 :group 'org-agenda
3267 :type 'sexp)
3269 (defcustom org-calendar-insert-diary-entry-key [?i]
3270 "The key to be installed in `calendar-mode-map' for adding diary entries.
3271 This option is irrelevant until `org-agenda-diary-file' has been configured
3272 to point to an Org-mode file. When that is the case, the command
3273 `org-agenda-diary-entry' will be bound to the key given here, by default
3274 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3275 if you want to continue doing this, you need to change this to a different
3276 key."
3277 :group 'org-agenda
3278 :type 'sexp)
3280 (defcustom org-agenda-diary-file 'diary-file
3281 "File to which to add new entries with the `i' key in agenda and calendar.
3282 When this is the symbol `diary-file', the functionality in the Emacs
3283 calendar will be used to add entries to the `diary-file'. But when this
3284 points to a file, `org-agenda-diary-entry' will be used instead."
3285 :group 'org-agenda
3286 :type '(choice
3287 (const :tag "The standard Emacs diary file" diary-file)
3288 (file :tag "Special Org file diary entries")))
3290 (eval-after-load "calendar"
3291 '(progn
3292 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3293 'org-calendar-goto-agenda)
3294 (add-hook 'calendar-mode-hook
3295 (lambda ()
3296 (unless (eq org-agenda-diary-file 'diary-file)
3297 (define-key calendar-mode-map
3298 org-calendar-insert-diary-entry-key
3299 'org-agenda-diary-entry))))))
3301 (defgroup org-latex nil
3302 "Options for embedding LaTeX code into Org-mode."
3303 :tag "Org LaTeX"
3304 :group 'org)
3306 (defcustom org-format-latex-options
3307 '(:foreground default :background default :scale 1.0
3308 :html-foreground "Black" :html-background "Transparent"
3309 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3310 "Options for creating images from LaTeX fragments.
3311 This is a property list with the following properties:
3312 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3313 `default' means use the foreground of the default face.
3314 :background the background color, or \"Transparent\".
3315 `default' means use the background of the default face.
3316 :scale a scaling factor for the size of the images, to get more pixels
3317 :html-foreground, :html-background, :html-scale
3318 the same numbers for HTML export.
3319 :matchers a list indicating which matchers should be used to
3320 find LaTeX fragments. Valid members of this list are:
3321 \"begin\" find environments
3322 \"$1\" find single characters surrounded by $.$
3323 \"$\" find math expressions surrounded by $...$
3324 \"$$\" find math expressions surrounded by $$....$$
3325 \"\\(\" find math expressions surrounded by \\(...\\)
3326 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3327 :group 'org-latex
3328 :type 'plist)
3330 (defcustom org-format-latex-signal-error t
3331 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3332 When nil, just push out a message."
3333 :group 'org-latex
3334 :version "24.1"
3335 :type 'boolean)
3337 (defcustom org-latex-to-mathml-jar-file nil
3338 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3339 Use this to specify additional executable file say a jar file.
3341 When using MathToWeb as the converter, specify the full-path to
3342 your mathtoweb.jar file."
3343 :group 'org-latex
3344 :version "24.1"
3345 :type '(choice
3346 (const :tag "None" nil)
3347 (file :tag "JAR file" :must-match t)))
3349 (defcustom org-latex-to-mathml-convert-command nil
3350 "Command to convert LaTeX fragments to MathML.
3351 Replace format-specifiers in the command as noted below and use
3352 `shell-command' to convert LaTeX to MathML.
3353 %j: Executable file in fully expanded form as specified by
3354 `org-latex-to-mathml-jar-file'.
3355 %I: Input LaTeX file in fully expanded form
3356 %o: Output MathML file
3357 This command is used by `org-create-math-formula'.
3359 When using MathToWeb as the converter, set this to
3360 \"java -jar %j -unicode -force -df %o %I\"."
3361 :group 'org-latex
3362 :version "24.1"
3363 :type '(choice
3364 (const :tag "None" nil)
3365 (string :tag "\nShell command")))
3367 (defcustom org-latex-create-formula-image-program 'dvipng
3368 "Program to convert LaTeX fragments with.
3370 dvipng Process the LaTeX fragments to dvi file, then convert
3371 dvi files to png files using dvipng.
3372 This will also include processing of non-math environments.
3373 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3374 to convert pdf files to png files"
3375 :group 'org-latex
3376 :version "24.1"
3377 :type '(choice
3378 (const :tag "dvipng" dvipng)
3379 (const :tag "imagemagick" imagemagick)))
3381 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3382 "Path to store latex preview images. A relative path here creates many
3383 directories relative to the processed org files paths. An absolute path
3384 puts all preview images at the same place."
3385 :group 'org-latex
3386 :version "24.3"
3387 :type 'string)
3389 (defun org-format-latex-mathml-available-p ()
3390 "Return t if `org-latex-to-mathml-convert-command' is usable."
3391 (save-match-data
3392 (when (and (boundp 'org-latex-to-mathml-convert-command)
3393 org-latex-to-mathml-convert-command)
3394 (let ((executable (car (split-string
3395 org-latex-to-mathml-convert-command))))
3396 (when (executable-find executable)
3397 (if (string-match
3398 "%j" org-latex-to-mathml-convert-command)
3399 (file-readable-p org-latex-to-mathml-jar-file)
3400 t))))))
3402 (defcustom org-format-latex-header "\\documentclass{article}
3403 \\usepackage[usenames]{color}
3404 \\usepackage{amsmath}
3405 \\usepackage[mathscr]{eucal}
3406 \\pagestyle{empty} % do not remove
3407 \[PACKAGES]
3408 \[DEFAULT-PACKAGES]
3409 % The settings below are copied from fullpage.sty
3410 \\setlength{\\textwidth}{\\paperwidth}
3411 \\addtolength{\\textwidth}{-3cm}
3412 \\setlength{\\oddsidemargin}{1.5cm}
3413 \\addtolength{\\oddsidemargin}{-2.54cm}
3414 \\setlength{\\evensidemargin}{\\oddsidemargin}
3415 \\setlength{\\textheight}{\\paperheight}
3416 \\addtolength{\\textheight}{-\\headheight}
3417 \\addtolength{\\textheight}{-\\headsep}
3418 \\addtolength{\\textheight}{-\\footskip}
3419 \\addtolength{\\textheight}{-3cm}
3420 \\setlength{\\topmargin}{1.5cm}
3421 \\addtolength{\\topmargin}{-2.54cm}"
3422 "The document header used for processing LaTeX fragments.
3423 It is imperative that this header make sure that no page number
3424 appears on the page. The package defined in the variables
3425 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3426 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3427 will be appended."
3428 :group 'org-latex
3429 :type 'string)
3431 (defvar org-format-latex-header-extra nil)
3433 (defun org-set-packages-alist (var val)
3434 "Set the packages alist and make sure it has 3 elements per entry."
3435 (set var (mapcar (lambda (x)
3436 (if (and (consp x) (= (length x) 2))
3437 (list (car x) (nth 1 x) t)
3439 val)))
3441 (defun org-get-packages-alist (var)
3443 "Get the packages alist and make sure it has 3 elements per entry."
3444 (mapcar (lambda (x)
3445 (if (and (consp x) (= (length x) 2))
3446 (list (car x) (nth 1 x) t)
3448 (default-value var)))
3450 ;; The following variables are defined here because is it also used
3451 ;; when formatting latex fragments. Originally it was part of the
3452 ;; LaTeX exporter, which is why the name includes "export".
3453 (defcustom org-export-latex-default-packages-alist
3454 '(("AUTO" "inputenc" t)
3455 ("T1" "fontenc" t)
3456 ("" "fixltx2e" nil)
3457 ("" "graphicx" t)
3458 ("" "longtable" nil)
3459 ("" "float" nil)
3460 ("" "wrapfig" nil)
3461 ("" "soul" t)
3462 ("" "textcomp" t)
3463 ("" "marvosym" t)
3464 ("" "wasysym" t)
3465 ("" "latexsym" t)
3466 ("" "amssymb" t)
3467 ("" "hyperref" nil)
3468 "\\tolerance=1000"
3470 "Alist of default packages to be inserted in the header.
3471 Change this only if one of the packages here causes an incompatibility
3472 with another package you are using.
3473 The packages in this list are needed by one part or another of Org-mode
3474 to function properly.
3476 - inputenc, fontenc: for basic font and character selection
3477 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3478 for interpreting the entities in `org-entities'. You can skip some of these
3479 packages if you don't use any of the symbols in it.
3480 - graphicx: for including images
3481 - float, wrapfig: for figure placement
3482 - longtable: for long tables
3483 - hyperref: for cross references
3485 Therefore you should not modify this variable unless you know what you
3486 are doing. The one reason to change it anyway is that you might be loading
3487 some other package that conflicts with one of the default packages.
3488 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3489 If SNIPPET-FLAG is t, the package also needs to be included when
3490 compiling LaTeX snippets into images for inclusion into HTML."
3491 :group 'org-export-latex
3492 :set 'org-set-packages-alist
3493 :get 'org-get-packages-alist
3494 :version "24.1"
3495 :type '(repeat
3496 (choice
3497 (list :tag "options/package pair"
3498 (string :tag "options")
3499 (string :tag "package")
3500 (boolean :tag "Snippet"))
3501 (string :tag "A line of LaTeX"))))
3503 (defcustom org-export-latex-packages-alist nil
3504 "Alist of packages to be inserted in every LaTeX header.
3505 These will be inserted after `org-export-latex-default-packages-alist'.
3506 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3507 SNIPPET-FLAG, when t, indicates that this package is also needed when
3508 turning LaTeX snippets into images for inclusion into HTML.
3509 Make sure that you only list packages here which:
3510 - you want in every file
3511 - do not conflict with the default packages in
3512 `org-export-latex-default-packages-alist'
3513 - do not conflict with the setup in `org-format-latex-header'."
3514 :group 'org-export-latex
3515 :set 'org-set-packages-alist
3516 :get 'org-get-packages-alist
3517 :type '(repeat
3518 (choice
3519 (list :tag "options/package pair"
3520 (string :tag "options")
3521 (string :tag "package")
3522 (boolean :tag "Snippet"))
3523 (string :tag "A line of LaTeX"))))
3526 (defgroup org-appearance nil
3527 "Settings for Org-mode appearance."
3528 :tag "Org Appearance"
3529 :group 'org)
3531 (defcustom org-level-color-stars-only nil
3532 "Non-nil means fontify only the stars in each headline.
3533 When nil, the entire headline is fontified.
3534 Changing it requires restart of `font-lock-mode' to become effective
3535 also in regions already fontified."
3536 :group 'org-appearance
3537 :type 'boolean)
3539 (defcustom org-hide-leading-stars nil
3540 "Non-nil means hide the first N-1 stars in a headline.
3541 This works by using the face `org-hide' for these stars. This
3542 face is white for a light background, and black for a dark
3543 background. You may have to customize the face `org-hide' to
3544 make this work.
3545 Changing it requires restart of `font-lock-mode' to become effective
3546 also in regions already fontified.
3547 You may also set this on a per-file basis by adding one of the following
3548 lines to the buffer:
3550 #+STARTUP: hidestars
3551 #+STARTUP: showstars"
3552 :group 'org-appearance
3553 :type 'boolean)
3555 (defcustom org-hidden-keywords nil
3556 "List of symbols corresponding to keywords to be hidden the org buffer.
3557 For example, a value '(title) for this list will make the document's title
3558 appear in the buffer without the initial #+TITLE: keyword."
3559 :group 'org-appearance
3560 :version "24.1"
3561 :type '(set (const :tag "#+AUTHOR" author)
3562 (const :tag "#+DATE" date)
3563 (const :tag "#+EMAIL" email)
3564 (const :tag "#+TITLE" title)))
3566 (defcustom org-custom-properties nil
3567 "List of properties (as strings) with a special meaning.
3568 The default use of these custom properties is to let the user
3569 hide them with `org-toggle-custom-properties-visibility'."
3570 :group 'org-properties
3571 :group 'org-appearance
3572 :version "24.3"
3573 :type '(repeat (string :tag "Property Name")))
3575 (defcustom org-fontify-done-headline nil
3576 "Non-nil means change the face of a headline if it is marked DONE.
3577 Normally, only the TODO/DONE keyword indicates the state of a headline.
3578 When this is non-nil, the headline after the keyword is set to the
3579 `org-headline-done' as an additional indication."
3580 :group 'org-appearance
3581 :type 'boolean)
3583 (defcustom org-fontify-emphasized-text t
3584 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3585 Changing this variable requires a restart of Emacs to take effect."
3586 :group 'org-appearance
3587 :type 'boolean)
3589 (defcustom org-fontify-whole-heading-line nil
3590 "Non-nil means fontify the whole line for headings.
3591 This is useful when setting a background color for the
3592 org-level-* faces."
3593 :group 'org-appearance
3594 :type 'boolean)
3596 (defcustom org-highlight-latex-fragments-and-specials nil
3597 "Non-nil means fontify what is treated specially by the exporters."
3598 :group 'org-appearance
3599 :type 'boolean)
3601 (defcustom org-hide-emphasis-markers nil
3602 "Non-nil mean font-lock should hide the emphasis marker characters."
3603 :group 'org-appearance
3604 :type 'boolean)
3606 (defcustom org-pretty-entities nil
3607 "Non-nil means show entities as UTF8 characters.
3608 When nil, the \\name form remains in the buffer."
3609 :group 'org-appearance
3610 :version "24.1"
3611 :type 'boolean)
3613 (defcustom org-pretty-entities-include-sub-superscripts t
3614 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3615 :group 'org-appearance
3616 :version "24.1"
3617 :type 'boolean)
3619 (defvar org-emph-re nil
3620 "Regular expression for matching emphasis.
3621 After a match, the match groups contain these elements:
3622 0 The match of the full regular expression, including the characters
3623 before and after the proper match
3624 1 The character before the proper match, or empty at beginning of line
3625 2 The proper match, including the leading and trailing markers
3626 3 The leading marker like * or /, indicating the type of highlighting
3627 4 The text between the emphasis markers, not including the markers
3628 5 The character after the match, empty at the end of a line")
3629 (defvar org-verbatim-re nil
3630 "Regular expression for matching verbatim text.")
3631 (defvar org-emphasis-regexp-components) ; defined just below
3632 (defvar org-emphasis-alist) ; defined just below
3633 (defun org-set-emph-re (var val)
3634 "Set variable and compute the emphasis regular expression."
3635 (set var val)
3636 (when (and (boundp 'org-emphasis-alist)
3637 (boundp 'org-emphasis-regexp-components)
3638 org-emphasis-alist org-emphasis-regexp-components)
3639 (let* ((e org-emphasis-regexp-components)
3640 (pre (car e))
3641 (post (nth 1 e))
3642 (border (nth 2 e))
3643 (body (nth 3 e))
3644 (nl (nth 4 e))
3645 (body1 (concat body "*?"))
3646 (markers (mapconcat 'car org-emphasis-alist ""))
3647 (vmarkers (mapconcat
3648 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3649 org-emphasis-alist "")))
3650 ;; make sure special characters appear at the right position in the class
3651 (if (string-match "\\^" markers)
3652 (setq markers (concat (replace-match "" t t markers) "^")))
3653 (if (string-match "-" markers)
3654 (setq markers (concat (replace-match "" t t markers) "-")))
3655 (if (string-match "\\^" vmarkers)
3656 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3657 (if (string-match "-" vmarkers)
3658 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3659 (if (> nl 0)
3660 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3661 (int-to-string nl) "\\}")))
3662 ;; Make the regexp
3663 (setq org-emph-re
3664 (concat "\\([" pre "]\\|^\\)"
3665 "\\("
3666 "\\([" markers "]\\)"
3667 "\\("
3668 "[^" border "]\\|"
3669 "[^" border "]"
3670 body1
3671 "[^" border "]"
3672 "\\)"
3673 "\\3\\)"
3674 "\\([" post "]\\|$\\)"))
3675 (setq org-verbatim-re
3676 (concat "\\([" pre "]\\|^\\)"
3677 "\\("
3678 "\\([" vmarkers "]\\)"
3679 "\\("
3680 "[^" border "]\\|"
3681 "[^" border "]"
3682 body1
3683 "[^" border "]"
3684 "\\)"
3685 "\\3\\)"
3686 "\\([" post "]\\|$\\)")))))
3688 (defcustom org-emphasis-regexp-components
3689 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3690 "Components used to build the regular expression for emphasis.
3691 This is a list with five entries. Terminology: In an emphasis string
3692 like \" *strong word* \", we call the initial space PREMATCH, the final
3693 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3694 and \"trong wor\" is the body. The different components in this variable
3695 specify what is allowed/forbidden in each part:
3697 pre Chars allowed as prematch. Beginning of line will be allowed too.
3698 post Chars allowed as postmatch. End of line will be allowed too.
3699 border The chars *forbidden* as border characters.
3700 body-regexp A regexp like \".\" to match a body character. Don't use
3701 non-shy groups here, and don't allow newline here.
3702 newline The maximum number of newlines allowed in an emphasis exp.
3704 Use customize to modify this, or restart Emacs after changing it."
3705 :group 'org-appearance
3706 :set 'org-set-emph-re
3707 :type '(list
3708 (sexp :tag "Allowed chars in pre ")
3709 (sexp :tag "Allowed chars in post ")
3710 (sexp :tag "Forbidden chars in border ")
3711 (sexp :tag "Regexp for body ")
3712 (integer :tag "number of newlines allowed")
3713 (option (boolean :tag "Please ignore this button"))))
3715 (defcustom org-emphasis-alist
3716 `(("*" bold "<b>" "</b>")
3717 ("/" italic "<i>" "</i>")
3718 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3719 ("=" org-code "<code>" "</code>" verbatim)
3720 ("~" org-verbatim "<code>" "</code>" verbatim)
3721 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3722 "<del>" "</del>")
3724 "Special syntax for emphasized text.
3725 Text starting and ending with a special character will be emphasized, for
3726 example *bold*, _underlined_ and /italic/. This variable sets the marker
3727 characters, the face to be used by font-lock for highlighting in Org-mode
3728 Emacs buffers, and the HTML tags to be used for this.
3729 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3730 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3731 Use customize to modify this, or restart Emacs after changing it."
3732 :group 'org-appearance
3733 :set 'org-set-emph-re
3734 :type '(repeat
3735 (list
3736 (string :tag "Marker character")
3737 (choice
3738 (face :tag "Font-lock-face")
3739 (plist :tag "Face property list"))
3740 (string :tag "HTML start tag")
3741 (string :tag "HTML end tag")
3742 (option (const verbatim)))))
3744 (defvar org-protecting-blocks
3745 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3746 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3747 This is needed for font-lock setup.")
3749 ;;; Miscellaneous options
3751 (defgroup org-completion nil
3752 "Completion in Org-mode."
3753 :tag "Org Completion"
3754 :group 'org)
3756 (defcustom org-completion-use-ido nil
3757 "Non-nil means use ido completion wherever possible.
3758 Note that `ido-mode' must be active for this variable to be relevant.
3759 If you decide to turn this variable on, you might well want to turn off
3760 `org-outline-path-complete-in-steps'.
3761 See also `org-completion-use-iswitchb'."
3762 :group 'org-completion
3763 :type 'boolean)
3765 (defcustom org-completion-use-iswitchb nil
3766 "Non-nil means use iswitchb completion wherever possible.
3767 Note that `iswitchb-mode' must be active for this variable to be relevant.
3768 If you decide to turn this variable on, you might well want to turn off
3769 `org-outline-path-complete-in-steps'.
3770 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3771 :group 'org-completion
3772 :type 'boolean)
3774 (defcustom org-completion-fallback-command 'hippie-expand
3775 "The expansion command called by \\[pcomplete] in normal context.
3776 Normal means, no org-mode-specific context."
3777 :group 'org-completion
3778 :type 'function)
3780 ;;; Functions and variables from their packages
3781 ;; Declared here to avoid compiler warnings
3783 ;; XEmacs only
3784 (defvar outline-mode-menu-heading)
3785 (defvar outline-mode-menu-show)
3786 (defvar outline-mode-menu-hide)
3787 (defvar zmacs-regions) ; XEmacs regions
3789 ;; Emacs only
3790 (defvar mark-active)
3792 ;; Various packages
3793 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3794 (declare-function calendar-forward-day "cal-move" (arg))
3795 (declare-function calendar-goto-date "cal-move" (date))
3796 (declare-function calendar-goto-today "cal-move" ())
3797 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3798 (defvar calc-embedded-close-formula)
3799 (defvar calc-embedded-open-formula)
3800 (declare-function cdlatex-tab "ext:cdlatex" ())
3801 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3802 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3803 (defvar font-lock-unfontify-region-function)
3804 (declare-function iswitchb-read-buffer "iswitchb"
3805 (prompt &optional default require-match start matches-set))
3806 (defvar iswitchb-temp-buflist)
3807 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3808 (defvar org-agenda-tags-todo-honor-ignore-options)
3809 (declare-function org-agenda-skip "org-agenda" ())
3810 (declare-function
3811 org-agenda-format-item "org-agenda"
3812 (extra txt &optional category tags dotime noprefix remove-re habitp))
3813 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3814 (declare-function org-agenda-change-all-lines "org-agenda"
3815 (newhead hdmarker &optional fixface just-this))
3816 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3817 (declare-function org-agenda-maybe-redo "org-agenda" ())
3818 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3819 (beg end))
3820 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3821 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3822 "org-agenda" (&optional end))
3823 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3824 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3825 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3826 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3827 (declare-function org-indent-mode "org-indent" (&optional arg))
3828 (declare-function parse-time-string "parse-time" (string))
3829 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3830 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3831 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3832 (defvar remember-data-file)
3833 (defvar texmathp-why)
3834 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3835 (declare-function table--at-cell-p "table" (position &optional object at-column))
3837 (defvar w3m-current-url)
3838 (defvar w3m-current-title)
3840 (defvar org-latex-regexps)
3842 ;;; Autoload and prepare some org modules
3844 ;; Some table stuff that needs to be defined here, because it is used
3845 ;; by the functions setting up org-mode or checking for table context.
3847 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3848 "Detect an org-type or table-type table.")
3849 (defconst org-table-line-regexp "^[ \t]*|"
3850 "Detect an org-type table line.")
3851 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3852 "Detect an org-type table line.")
3853 (defconst org-table-hline-regexp "^[ \t]*|-"
3854 "Detect an org-type table hline.")
3855 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3856 "Detect a table-type table hline.")
3857 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3858 "Detect the first line outside a table when searching from within it.
3859 This works for both table types.")
3861 ;; Autoload the functions in org-table.el that are needed by functions here.
3863 (eval-and-compile
3864 (org-autoload "org-table"
3865 '(org-table-align org-table-begin org-table-blank-field
3866 org-table-convert org-table-convert-region org-table-copy-down
3867 org-table-copy-region org-table-create
3868 org-table-create-or-convert-from-region
3869 org-table-create-with-table.el org-table-current-dline
3870 org-table-cut-region org-table-delete-column org-table-edit-field
3871 org-table-edit-formulas org-table-end org-table-eval-formula
3872 org-table-export org-table-field-info
3873 org-table-get-stored-formulas org-table-goto-column
3874 org-table-hline-and-move org-table-import org-table-insert-column
3875 org-table-insert-hline org-table-insert-row org-table-iterate
3876 org-table-justify-field-maybe org-table-kill-row
3877 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3878 org-table-move-column org-table-move-column-left
3879 org-table-move-column-right org-table-move-row
3880 org-table-move-row-down org-table-move-row-up
3881 org-table-next-field org-table-next-row org-table-paste-rectangle
3882 org-table-previous-field org-table-recalculate
3883 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3884 org-table-toggle-coordinate-overlays
3885 org-table-toggle-formula-debugger org-table-wrap-region
3886 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3887 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3888 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3890 (defun org-at-table-p (&optional table-type)
3891 "Return t if the cursor is inside an org-type table.
3892 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3893 (if org-enable-table-editor
3894 (save-excursion
3895 (beginning-of-line 1)
3896 (looking-at (if table-type org-table-any-line-regexp
3897 org-table-line-regexp)))
3898 nil))
3899 (defsubst org-table-p () (org-at-table-p))
3901 (defun org-at-table.el-p ()
3902 "Return t if and only if we are at a table.el table."
3903 (and (org-at-table-p 'any)
3904 (save-excursion
3905 (goto-char (org-table-begin 'any))
3906 (looking-at org-table1-hline-regexp))))
3907 (defun org-table-recognize-table.el ()
3908 "If there is a table.el table nearby, recognize it and move into it."
3909 (if org-table-tab-recognizes-table.el
3910 (if (org-at-table.el-p)
3911 (progn
3912 (beginning-of-line 1)
3913 (if (looking-at org-table-dataline-regexp)
3915 (if (looking-at org-table1-hline-regexp)
3916 (progn
3917 (beginning-of-line 2)
3918 (if (looking-at org-table-any-border-regexp)
3919 (beginning-of-line -1)))))
3920 (if (re-search-forward "|" (org-table-end t) t)
3921 (progn
3922 (require 'table)
3923 (if (table--at-cell-p (point))
3925 (message "recognizing table.el table...")
3926 (table-recognize-table)
3927 (message "recognizing table.el table...done")))
3928 (error "This should not happen"))
3930 nil)
3931 nil))
3933 (defun org-at-table-hline-p ()
3934 "Return t if the cursor is inside a hline in a table."
3935 (if org-enable-table-editor
3936 (save-excursion
3937 (beginning-of-line 1)
3938 (looking-at org-table-hline-regexp))
3939 nil))
3941 (defvar org-table-clean-did-remove-column nil)
3943 (defun org-table-map-tables (function &optional quietly)
3944 "Apply FUNCTION to the start of all tables in the buffer."
3945 (save-excursion
3946 (save-restriction
3947 (widen)
3948 (goto-char (point-min))
3949 (while (re-search-forward org-table-any-line-regexp nil t)
3950 (unless quietly
3951 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3952 (beginning-of-line 1)
3953 (when (and (looking-at org-table-line-regexp)
3954 ;; Exclude tables in src/example/verbatim/clocktable blocks
3955 (not (org-in-block-p '("src" "example"))))
3956 (save-excursion (funcall function))
3957 (or (looking-at org-table-line-regexp)
3958 (forward-char 1)))
3959 (re-search-forward org-table-any-border-regexp nil 1))))
3960 (unless quietly (message "Mapping tables: done")))
3962 ;; Declare and autoload functions from org-exp.el & Co
3964 (declare-function org-default-export-plist "org-exp")
3965 (declare-function org-infile-export-plist "org-exp")
3966 (declare-function org-get-current-options "org-exp")
3967 (eval-and-compile
3968 (org-autoload "org-exp"
3969 '(org-export org-export-visible
3970 org-insert-export-options-template
3971 org-table-clean-before-export))
3972 (org-autoload "org-ascii"
3973 '(org-export-as-ascii org-export-ascii-preprocess
3974 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3975 org-export-region-as-ascii))
3976 (org-autoload "org-latex"
3977 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3978 org-replace-region-by-latex org-export-region-as-latex
3979 org-export-as-latex org-export-as-pdf
3980 org-export-as-pdf-and-open))
3981 (org-autoload "org-html"
3982 '(org-export-as-html-and-open
3983 org-export-as-html-batch org-export-as-html-to-buffer
3984 org-replace-region-by-html org-export-region-as-html
3985 org-export-as-html))
3986 (org-autoload "org-docbook"
3987 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3988 org-replace-region-by-docbook org-export-region-as-docbook
3989 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3990 org-export-as-docbook))
3991 (org-autoload "org-icalendar"
3992 '(org-export-icalendar-this-file
3993 org-export-icalendar-all-agenda-files
3994 org-export-icalendar-combine-agenda-files))
3995 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3996 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3998 ;; Declare and autoload functions from org-agenda.el
4000 (eval-and-compile
4001 (org-autoload "org-agenda"
4002 '(org-agenda org-agenda-list org-search-view
4003 org-todo-list org-tags-view org-agenda-list-stuck-projects
4004 org-diary org-agenda-to-appt
4005 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4007 ;; Autoload org-remember
4009 (eval-and-compile
4010 (org-autoload "org-remember"
4011 '(org-remember-insinuate org-remember-annotation
4012 org-remember-apply-template org-remember org-remember-handler)))
4014 (eval-and-compile
4015 (org-autoload "org-capture"
4016 '(org-capture org-capture-insert-template-here
4017 org-capture-import-remember-templates)))
4019 ;; Autoload org-clock.el
4021 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4022 (beg end))
4023 (declare-function org-clock-update-mode-line "org-clock" ())
4024 (declare-function org-resolve-clocks "org-clock"
4025 (&optional also-non-dangling-p prompt last-valid))
4026 (defvar org-clock-start-time)
4027 (defvar org-clock-marker (make-marker)
4028 "Marker recording the last clock-in.")
4029 (defvar org-clock-hd-marker (make-marker)
4030 "Marker recording the last clock-in, but the headline position.")
4031 (defvar org-clock-heading ""
4032 "The heading of the current clock entry.")
4033 (defun org-clock-is-active ()
4034 "Return non-nil if clock is currently running.
4035 The return value is actually the clock marker."
4036 (marker-buffer org-clock-marker))
4038 (eval-and-compile
4039 (org-autoload
4040 "org-clock"
4041 '(org-clock-in org-clock-out org-clock-cancel
4042 org-clock-goto org-clock-sum org-clock-display
4043 org-clock-remove-overlays org-clock-report
4044 org-clocktable-shift org-dblock-write:clocktable
4045 org-get-clocktable org-resolve-clocks)))
4047 (defun org-clock-update-time-maybe ()
4048 "If this is a CLOCK line, update it and return t.
4049 Otherwise, return nil."
4050 (interactive)
4051 (save-excursion
4052 (beginning-of-line 1)
4053 (skip-chars-forward " \t")
4054 (when (looking-at org-clock-string)
4055 (let ((re (concat "[ \t]*" org-clock-string
4056 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4057 "\\([ \t]*=>.*\\)?\\)?"))
4058 ts te h m s neg)
4059 (cond
4060 ((not (looking-at re))
4061 nil)
4062 ((not (match-end 2))
4063 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4064 (> org-clock-marker (point))
4065 (<= org-clock-marker (point-at-eol)))
4066 ;; The clock is running here
4067 (setq org-clock-start-time
4068 (apply 'encode-time
4069 (org-parse-time-string (match-string 1))))
4070 (org-clock-update-mode-line)))
4072 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4073 (end-of-line 1)
4074 (setq ts (match-string 1)
4075 te (match-string 3))
4076 (setq s (- (org-float-time
4077 (apply 'encode-time (org-parse-time-string te)))
4078 (org-float-time
4079 (apply 'encode-time (org-parse-time-string ts))))
4080 neg (< s 0)
4081 s (abs s)
4082 h (floor (/ s 3600))
4083 s (- s (* 3600 h))
4084 m (floor (/ s 60))
4085 s (- s (* 60 s)))
4086 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4087 t))))))
4089 (defun org-check-running-clock ()
4090 "Check if the current buffer contains the running clock.
4091 If yes, offer to stop it and to save the buffer with the changes."
4092 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4093 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4094 (buffer-name))))
4095 (org-clock-out)
4096 (when (y-or-n-p "Save changed buffer?")
4097 (save-buffer))))
4099 (defun org-clocktable-try-shift (dir n)
4100 "Check if this line starts a clock table, if yes, shift the time block."
4101 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4102 (org-clocktable-shift dir n)))
4104 ;; Autoload org-timer.el
4106 (eval-and-compile
4107 (org-autoload
4108 "org-timer"
4109 '(org-timer-start org-timer org-timer-item
4110 org-timer-change-times-in-region
4111 org-timer-set-timer
4112 org-timer-reset-timers
4113 org-timer-show-remaining-time)))
4115 ;; Autoload org-feed.el
4117 (eval-and-compile
4118 (org-autoload
4119 "org-feed"
4120 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4123 ;; Autoload org-indent.el
4125 ;; Define the variable already here, to make sure we have it.
4126 (defvar org-indent-mode nil
4127 "Non-nil if Org-Indent mode is enabled.
4128 Use the command `org-indent-mode' to change this variable.")
4130 (eval-and-compile
4131 (org-autoload
4132 "org-indent"
4133 '(org-indent-mode)))
4135 ;; Autoload org-mobile.el
4137 (eval-and-compile
4138 (org-autoload
4139 "org-mobile"
4140 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4142 ;; Autoload archiving code
4143 ;; The stuff that is needed for cycling and tags has to be defined here.
4145 (defgroup org-archive nil
4146 "Options concerning archiving in Org-mode."
4147 :tag "Org Archive"
4148 :group 'org-structure)
4150 (defcustom org-archive-location "%s_archive::"
4151 "The location where subtrees should be archived.
4153 The value of this variable is a string, consisting of two parts,
4154 separated by a double-colon. The first part is a filename and
4155 the second part is a headline.
4157 When the filename is omitted, archiving happens in the same file.
4158 %s in the filename will be replaced by the current file
4159 name (without the directory part). Archiving to a different file
4160 is useful to keep archived entries from contributing to the
4161 Org-mode Agenda.
4163 The archived entries will be filed as subtrees of the specified
4164 headline. When the headline is omitted, the subtrees are simply
4165 filed away at the end of the file, as top-level entries. Also in
4166 the heading you can use %s to represent the file name, this can be
4167 useful when using the same archive for a number of different files.
4169 Here are a few examples:
4170 \"%s_archive::\"
4171 If the current file is Projects.org, archive in file
4172 Projects.org_archive, as top-level trees. This is the default.
4174 \"::* Archived Tasks\"
4175 Archive in the current file, under the top-level headline
4176 \"* Archived Tasks\".
4178 \"~/org/archive.org::\"
4179 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4181 \"~/org/archive.org::* From %s\"
4182 Archive in file ~/org/archive.org (absolute path), under headlines
4183 \"From FILENAME\" where file name is the current file name.
4185 \"~/org/datetree.org::datetree/* Finished Tasks\"
4186 The \"datetree/\" string is special, signifying to archive
4187 items to the datetree. Items are placed in either the CLOSED
4188 date of the item, or the current date if there is no CLOSED date.
4189 The heading will be a subentry to the current date. There doesn't
4190 need to be a heading, but there always needs to be a slash after
4191 datetree. For example, to store archived items directly in the
4192 datetree, use \"~/org/datetree.org::datetree/\".
4194 \"basement::** Finished Tasks\"
4195 Archive in file ./basement (relative path), as level 3 trees
4196 below the level 2 heading \"** Finished Tasks\".
4198 You may set this option on a per-file basis by adding to the buffer a
4199 line like
4201 #+ARCHIVE: basement::** Finished Tasks
4203 You may also define it locally for a subtree by setting an ARCHIVE property
4204 in the entry. If such a property is found in an entry, or anywhere up
4205 the hierarchy, it will be used."
4206 :group 'org-archive
4207 :type 'string)
4209 (defcustom org-archive-tag "ARCHIVE"
4210 "The tag that marks a subtree as archived.
4211 An archived subtree does not open during visibility cycling, and does
4212 not contribute to the agenda listings.
4213 After changing this, font-lock must be restarted in the relevant buffers to
4214 get the proper fontification."
4215 :group 'org-archive
4216 :group 'org-keywords
4217 :type 'string)
4219 (defcustom org-agenda-skip-archived-trees t
4220 "Non-nil means the agenda will skip any items located in archived trees.
4221 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4222 variable is no longer recommended, you should leave it at the value t.
4223 Instead, use the key `v' to cycle the archives-mode in the agenda."
4224 :group 'org-archive
4225 :group 'org-agenda-skip
4226 :type 'boolean)
4228 (defcustom org-columns-skip-archived-trees t
4229 "Non-nil means ignore archived trees when creating column view."
4230 :group 'org-archive
4231 :group 'org-properties
4232 :type 'boolean)
4234 (defcustom org-cycle-open-archived-trees nil
4235 "Non-nil means `org-cycle' will open archived trees.
4236 An archived tree is a tree marked with the tag ARCHIVE.
4237 When nil, archived trees will stay folded. You can still open them with
4238 normal outline commands like `show-all', but not with the cycling commands."
4239 :group 'org-archive
4240 :group 'org-cycle
4241 :type 'boolean)
4243 (defcustom org-sparse-tree-open-archived-trees nil
4244 "Non-nil means sparse tree construction shows matches in archived trees.
4245 When nil, matches in these trees are highlighted, but the trees are kept in
4246 collapsed state."
4247 :group 'org-archive
4248 :group 'org-sparse-trees
4249 :type 'boolean)
4251 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4252 "The default date type when building a sparse tree.
4253 When this is nil, a date is a scheduled or a deadline timestamp.
4254 Otherwise, these types are allowed:
4256 all: all timestamps
4257 active: only active timestamps (<...>)
4258 inactive: only inactive timestamps (<...)
4259 scheduled: only scheduled timestamps
4260 deadline: only deadline timestamps"
4261 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4262 (const :tag "All timestamps" all)
4263 (const :tag "Only active timestamps" active)
4264 (const :tag "Only inactive timestamps" inactive)
4265 (const :tag "Only scheduled timestamps" scheduled)
4266 (const :tag "Only deadline timestamps" deadline))
4267 :version "24.3"
4268 :group 'org-sparse-trees)
4270 (defun org-cycle-hide-archived-subtrees (state)
4271 "Re-hide all archived subtrees after a visibility state change."
4272 (when (and (not org-cycle-open-archived-trees)
4273 (not (memq state '(overview folded))))
4274 (save-excursion
4275 (let* ((globalp (memq state '(contents all)))
4276 (beg (if globalp (point-min) (point)))
4277 (end (if globalp (point-max) (org-end-of-subtree t))))
4278 (org-hide-archived-subtrees beg end)
4279 (goto-char beg)
4280 (if (looking-at (concat ".*:" org-archive-tag ":"))
4281 (message "%s" (substitute-command-keys
4282 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4284 (defun org-force-cycle-archived ()
4285 "Cycle subtree even if it is archived."
4286 (interactive)
4287 (setq this-command 'org-cycle)
4288 (let ((org-cycle-open-archived-trees t))
4289 (call-interactively 'org-cycle)))
4291 (defun org-hide-archived-subtrees (beg end)
4292 "Re-hide all archived subtrees after a visibility state change."
4293 (save-excursion
4294 (let* ((re (concat ":" org-archive-tag ":")))
4295 (goto-char beg)
4296 (while (re-search-forward re end t)
4297 (when (org-at-heading-p)
4298 (org-flag-subtree t)
4299 (org-end-of-subtree t))))))
4301 (declare-function outline-end-of-heading "outline" ())
4302 (declare-function outline-flag-region "outline" (from to flag))
4303 (defun org-flag-subtree (flag)
4304 (save-excursion
4305 (org-back-to-heading t)
4306 (outline-end-of-heading)
4307 (outline-flag-region (point)
4308 (progn (org-end-of-subtree t) (point))
4309 flag)))
4311 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4313 (eval-and-compile
4314 (org-autoload "org-archive"
4315 '(org-add-archive-files org-archive-subtree
4316 org-archive-to-archive-sibling org-toggle-archive-tag
4317 org-archive-subtree-default
4318 org-archive-subtree-default-with-confirmation)))
4320 ;; Autoload Column View Code
4322 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4323 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4324 (declare-function org-columns-compute "org-colview" (property))
4326 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4327 '(org-columns-number-to-string org-columns-get-format-and-top-level
4328 org-columns-compute org-agenda-columns org-columns-remove-overlays
4329 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4331 ;; Autoload ID code
4333 (declare-function org-id-store-link "org-id")
4334 (declare-function org-id-locations-load "org-id")
4335 (declare-function org-id-locations-save "org-id")
4336 (defvar org-id-track-globally)
4337 (org-autoload "org-id"
4338 '(org-id-get-create org-id-new org-id-copy org-id-get
4339 org-id-get-with-outline-path-completion
4340 org-id-get-with-outline-drilling org-id-store-link
4341 org-id-goto org-id-find org-id-store-link))
4343 ;; Autoload Plotting Code
4345 (org-autoload "org-plot"
4346 '(org-plot/gnuplot))
4348 ;;; Variables for pre-computed regular expressions, all buffer local
4350 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4351 "Matches first line of a hidden block.")
4352 (make-variable-buffer-local 'org-drawer-regexp)
4353 (defvar org-todo-regexp nil
4354 "Matches any of the TODO state keywords.")
4355 (make-variable-buffer-local 'org-todo-regexp)
4356 (defvar org-not-done-regexp nil
4357 "Matches any of the TODO state keywords except the last one.")
4358 (make-variable-buffer-local 'org-not-done-regexp)
4359 (defvar org-not-done-heading-regexp nil
4360 "Matches a TODO headline that is not done.")
4361 (make-variable-buffer-local 'org-not-done-regexp)
4362 (defvar org-todo-line-regexp nil
4363 "Matches a headline and puts TODO state into group 2 if present.")
4364 (make-variable-buffer-local 'org-todo-line-regexp)
4365 (defvar org-complex-heading-regexp nil
4366 "Matches a headline and puts everything into groups:
4367 group 1: the stars
4368 group 2: The todo keyword, maybe
4369 group 3: Priority cookie
4370 group 4: True headline
4371 group 5: Tags")
4372 (make-variable-buffer-local 'org-complex-heading-regexp)
4373 (defvar org-complex-heading-regexp-format nil
4374 "Printf format to make regexp to match an exact headline.
4375 This regexp will match the headline of any node which has the
4376 exact headline text that is put into the format, but may have any
4377 TODO state, priority and tags.")
4378 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4379 (defvar org-todo-line-tags-regexp nil
4380 "Matches a headline and puts TODO state into group 2 if present.
4381 Also put tags into group 4 if tags are present.")
4382 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4383 (defvar org-ds-keyword-length 12
4384 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4385 (make-variable-buffer-local 'org-ds-keyword-length)
4386 (defvar org-deadline-regexp nil
4387 "Matches the DEADLINE keyword.")
4388 (make-variable-buffer-local 'org-deadline-regexp)
4389 (defvar org-deadline-time-regexp nil
4390 "Matches the DEADLINE keyword together with a time stamp.")
4391 (make-variable-buffer-local 'org-deadline-time-regexp)
4392 (defvar org-deadline-line-regexp nil
4393 "Matches the DEADLINE keyword and the rest of the line.")
4394 (make-variable-buffer-local 'org-deadline-line-regexp)
4395 (defvar org-scheduled-regexp nil
4396 "Matches the SCHEDULED keyword.")
4397 (make-variable-buffer-local 'org-scheduled-regexp)
4398 (defvar org-scheduled-time-regexp nil
4399 "Matches the SCHEDULED keyword together with a time stamp.")
4400 (make-variable-buffer-local 'org-scheduled-time-regexp)
4401 (defvar org-closed-time-regexp nil
4402 "Matches the CLOSED keyword together with a time stamp.")
4403 (make-variable-buffer-local 'org-closed-time-regexp)
4405 (defvar org-keyword-time-regexp nil
4406 "Matches any of the 4 keywords, together with the time stamp.")
4407 (make-variable-buffer-local 'org-keyword-time-regexp)
4408 (defvar org-keyword-time-not-clock-regexp nil
4409 "Matches any of the 3 keywords, together with the time stamp.")
4410 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4411 (defvar org-maybe-keyword-time-regexp nil
4412 "Matches a timestamp, possibly preceded by a keyword.")
4413 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4414 (defvar org-all-time-keywords nil
4415 "List of time keywords.")
4416 (make-variable-buffer-local 'org-all-time-keywords)
4418 (defconst org-plain-time-of-day-regexp
4419 (concat
4420 "\\(\\<[012]?[0-9]"
4421 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4422 "\\(--?"
4423 "\\(\\<[012]?[0-9]"
4424 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4425 "\\)?")
4426 "Regular expression to match a plain time or time range.
4427 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4428 groups carry important information:
4429 0 the full match
4430 1 the first time, range or not
4431 8 the second time, if it is a range.")
4433 (defconst org-plain-time-extension-regexp
4434 (concat
4435 "\\(\\<[012]?[0-9]"
4436 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4437 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4438 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4439 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4440 groups carry important information:
4441 0 the full match
4442 7 hours of duration
4443 9 minutes of duration")
4445 (defconst org-stamp-time-of-day-regexp
4446 (concat
4447 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4448 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4449 "\\(--?"
4450 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4451 "Regular expression to match a timestamp time or time range.
4452 After a match, the following groups carry important information:
4453 0 the full match
4454 1 date plus weekday, for back referencing to make sure both times are on the same day
4455 2 the first time, range or not
4456 4 the second time, if it is a range.")
4458 (defconst org-startup-options
4459 '(("fold" org-startup-folded t)
4460 ("overview" org-startup-folded t)
4461 ("nofold" org-startup-folded nil)
4462 ("showall" org-startup-folded nil)
4463 ("showeverything" org-startup-folded showeverything)
4464 ("content" org-startup-folded content)
4465 ("indent" org-startup-indented t)
4466 ("noindent" org-startup-indented nil)
4467 ("hidestars" org-hide-leading-stars t)
4468 ("showstars" org-hide-leading-stars nil)
4469 ("odd" org-odd-levels-only t)
4470 ("oddeven" org-odd-levels-only nil)
4471 ("align" org-startup-align-all-tables t)
4472 ("noalign" org-startup-align-all-tables nil)
4473 ("inlineimages" org-startup-with-inline-images t)
4474 ("noinlineimages" org-startup-with-inline-images nil)
4475 ("customtime" org-display-custom-times t)
4476 ("logdone" org-log-done time)
4477 ("lognotedone" org-log-done note)
4478 ("nologdone" org-log-done nil)
4479 ("lognoteclock-out" org-log-note-clock-out t)
4480 ("nolognoteclock-out" org-log-note-clock-out nil)
4481 ("logrepeat" org-log-repeat state)
4482 ("lognoterepeat" org-log-repeat note)
4483 ("nologrepeat" org-log-repeat nil)
4484 ("logreschedule" org-log-reschedule time)
4485 ("lognotereschedule" org-log-reschedule note)
4486 ("nologreschedule" org-log-reschedule nil)
4487 ("logredeadline" org-log-redeadline time)
4488 ("lognoteredeadline" org-log-redeadline note)
4489 ("nologredeadline" org-log-redeadline nil)
4490 ("logrefile" org-log-refile time)
4491 ("lognoterefile" org-log-refile note)
4492 ("nologrefile" org-log-refile nil)
4493 ("fninline" org-footnote-define-inline t)
4494 ("nofninline" org-footnote-define-inline nil)
4495 ("fnlocal" org-footnote-section nil)
4496 ("fnauto" org-footnote-auto-label t)
4497 ("fnprompt" org-footnote-auto-label nil)
4498 ("fnconfirm" org-footnote-auto-label confirm)
4499 ("fnplain" org-footnote-auto-label plain)
4500 ("fnadjust" org-footnote-auto-adjust t)
4501 ("nofnadjust" org-footnote-auto-adjust nil)
4502 ("constcgs" constants-unit-system cgs)
4503 ("constSI" constants-unit-system SI)
4504 ("noptag" org-tag-persistent-alist nil)
4505 ("hideblocks" org-hide-block-startup t)
4506 ("nohideblocks" org-hide-block-startup nil)
4507 ("beamer" org-startup-with-beamer-mode t)
4508 ("entitiespretty" org-pretty-entities t)
4509 ("entitiesplain" org-pretty-entities nil))
4510 "Variable associated with STARTUP options for org-mode.
4511 Each element is a list of three items: the startup options (as written
4512 in the #+STARTUP line), the corresponding variable, and the value to set
4513 this variable to if the option is found. An optional forth element PUSH
4514 means to push this value onto the list in the variable.")
4516 (defun org-update-property-plist (key val props)
4517 "Update PROPS with KEY and VAL."
4518 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4519 (key (if appending (substring key 0 (- (length key) 1)) key))
4520 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4521 (previous (cdr (assoc key props))))
4522 (if appending
4523 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4524 (cons (cons key val) remainder))))
4526 (defconst org-block-regexp
4527 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4528 "Regular expression for hiding blocks.")
4529 (defconst org-heading-keyword-regexp-format
4530 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4531 "Printf format for a regexp matching an headline with some keyword.
4532 This regexp will match the headline of any node which has the
4533 exact keyword that is put into the format. The keyword isn't in
4534 any group by default, but the stars and the body are.")
4535 (defconst org-heading-keyword-maybe-regexp-format
4536 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4537 "Printf format for a regexp matching an headline, possibly with some keyword.
4538 This regexp can match any headline with the specified keyword, or
4539 without a keyword. The keyword isn't in any group by default,
4540 but the stars and the body are.")
4542 (defun org-set-regexps-and-options ()
4543 "Precompute regular expressions for current buffer."
4544 (when (derived-mode-p 'org-mode)
4545 (org-set-local 'org-todo-kwd-alist nil)
4546 (org-set-local 'org-todo-key-alist nil)
4547 (org-set-local 'org-todo-key-trigger nil)
4548 (org-set-local 'org-todo-keywords-1 nil)
4549 (org-set-local 'org-done-keywords nil)
4550 (org-set-local 'org-todo-heads nil)
4551 (org-set-local 'org-todo-sets nil)
4552 (org-set-local 'org-todo-log-states nil)
4553 (org-set-local 'org-file-properties nil)
4554 (org-set-local 'org-file-tags nil)
4555 (let ((re (org-make-options-regexp
4556 '("CATEGORY" "TODO" "COLUMNS"
4557 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4558 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4559 "OPTIONS")
4560 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4561 (splitre "[ \t]+")
4562 (scripts org-use-sub-superscripts)
4563 kwds kws0 kwsa key log value cat arch tags const links hw dws
4564 tail sep kws1 prio props ftags drawers beamer-p
4565 ext-setup-or-nil setup-contents (start 0))
4566 (save-excursion
4567 (save-restriction
4568 (widen)
4569 (goto-char (point-min))
4570 (while (or (and ext-setup-or-nil
4571 (string-match re ext-setup-or-nil start)
4572 (setq start (match-end 0)))
4573 (and (setq ext-setup-or-nil nil start 0)
4574 (re-search-forward re nil t)))
4575 (setq key (upcase (match-string 1 ext-setup-or-nil))
4576 value (org-match-string-no-properties 2 ext-setup-or-nil))
4577 (if (stringp value) (setq value (org-trim value)))
4578 (cond
4579 ((equal key "CATEGORY")
4580 (setq cat value))
4581 ((member key '("SEQ_TODO" "TODO"))
4582 (push (cons 'sequence (org-split-string value splitre)) kwds))
4583 ((equal key "TYP_TODO")
4584 (push (cons 'type (org-split-string value splitre)) kwds))
4585 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4586 ;; general TODO-like setup
4587 (push (cons (intern (downcase (match-string 1 key)))
4588 (org-split-string value splitre)) kwds))
4589 ((equal key "TAGS")
4590 (setq tags (append tags (if tags '("\\n") nil)
4591 (org-split-string value splitre))))
4592 ((equal key "COLUMNS")
4593 (org-set-local 'org-columns-default-format value))
4594 ((equal key "LINK")
4595 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4596 (push (cons (match-string 1 value)
4597 (org-trim (match-string 2 value)))
4598 links)))
4599 ((equal key "PRIORITIES")
4600 (setq prio (org-split-string value " +")))
4601 ((equal key "PROPERTY")
4602 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4603 (setq props (org-update-property-plist (match-string 1 value)
4604 (match-string 2 value)
4605 props))))
4606 ((equal key "FILETAGS")
4607 (when (string-match "\\S-" value)
4608 (setq ftags
4609 (append
4610 ftags
4611 (apply 'append
4612 (mapcar (lambda (x) (org-split-string x ":"))
4613 (org-split-string value)))))))
4614 ((equal key "DRAWERS")
4615 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4616 ((equal key "CONSTANTS")
4617 (setq const (append const (org-split-string value splitre))))
4618 ((equal key "STARTUP")
4619 (let ((opts (org-split-string value splitre))
4620 l var val)
4621 (while (setq l (pop opts))
4622 (when (setq l (assoc l org-startup-options))
4623 (setq var (nth 1 l) val (nth 2 l))
4624 (if (not (nth 3 l))
4625 (set (make-local-variable var) val)
4626 (if (not (listp (symbol-value var)))
4627 (set (make-local-variable var) nil))
4628 (set (make-local-variable var) (symbol-value var))
4629 (add-to-list var val))))))
4630 ((equal key "ARCHIVE")
4631 (setq arch value)
4632 (remove-text-properties 0 (length arch)
4633 '(face t fontified t) arch))
4634 ((equal key "LATEX_CLASS")
4635 (setq beamer-p (equal value "beamer")))
4636 ((equal key "OPTIONS")
4637 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4638 (setq scripts (read (match-string 2 value)))))
4639 ((equal key "SETUPFILE")
4640 (setq setup-contents (org-file-contents
4641 (expand-file-name
4642 (org-remove-double-quotes value))
4643 'noerror))
4644 (if (not ext-setup-or-nil)
4645 (setq ext-setup-or-nil setup-contents start 0)
4646 (setq ext-setup-or-nil
4647 (concat (substring ext-setup-or-nil 0 start)
4648 "\n" setup-contents "\n"
4649 (substring ext-setup-or-nil start)))))))
4650 ;; search for property blocks
4651 (goto-char (point-min))
4652 (while (re-search-forward org-block-regexp nil t)
4653 (when (equal "PROPERTY" (upcase (match-string 1)))
4654 (setq value (replace-regexp-in-string
4655 "[\n\r]" " " (match-string 4)))
4656 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4657 (setq props (org-update-property-plist (match-string 1 value)
4658 (match-string 2 value)
4659 props)))))))
4660 (org-set-local 'org-use-sub-superscripts scripts)
4661 (when cat
4662 (org-set-local 'org-category (intern cat))
4663 (push (cons "CATEGORY" cat) props))
4664 (when prio
4665 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4666 (setq prio (mapcar 'string-to-char prio))
4667 (org-set-local 'org-highest-priority (nth 0 prio))
4668 (org-set-local 'org-lowest-priority (nth 1 prio))
4669 (org-set-local 'org-default-priority (nth 2 prio)))
4670 (and props (org-set-local 'org-file-properties (nreverse props)))
4671 (and ftags (org-set-local 'org-file-tags
4672 (mapcar 'org-add-prop-inherited ftags)))
4673 (and drawers (org-set-local 'org-drawers drawers))
4674 (and arch (org-set-local 'org-archive-location arch))
4675 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4676 ;; Process the TODO keywords
4677 (unless kwds
4678 ;; Use the global values as if they had been given locally.
4679 (setq kwds (default-value 'org-todo-keywords))
4680 (if (stringp (car kwds))
4681 (setq kwds (list (cons org-todo-interpretation
4682 (default-value 'org-todo-keywords)))))
4683 (setq kwds (reverse kwds)))
4684 (setq kwds (nreverse kwds))
4685 (let (inter kws kw)
4686 (while (setq kws (pop kwds))
4687 (let ((kws (or
4688 (run-hook-with-args-until-success
4689 'org-todo-setup-filter-hook kws)
4690 kws)))
4691 (setq inter (pop kws) sep (member "|" kws)
4692 kws0 (delete "|" (copy-sequence kws))
4693 kwsa nil
4694 kws1 (mapcar
4695 (lambda (x)
4696 ;; 1 2
4697 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4698 (progn
4699 (setq kw (match-string 1 x)
4700 key (and (match-end 2) (match-string 2 x))
4701 log (org-extract-log-state-settings x))
4702 (push (cons kw (and key (string-to-char key))) kwsa)
4703 (and log (push log org-todo-log-states))
4705 (error "Invalid TODO keyword %s" x)))
4706 kws0)
4707 kwsa (if kwsa (append '((:startgroup))
4708 (nreverse kwsa)
4709 '((:endgroup))))
4710 hw (car kws1)
4711 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4712 tail (list inter hw (car dws) (org-last dws))))
4713 (add-to-list 'org-todo-heads hw 'append)
4714 (push kws1 org-todo-sets)
4715 (setq org-done-keywords (append org-done-keywords dws nil))
4716 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4717 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4718 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4719 (setq org-todo-sets (nreverse org-todo-sets)
4720 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4721 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4722 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4723 ;; Process the constants
4724 (when const
4725 (let (e cst)
4726 (while (setq e (pop const))
4727 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4728 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4729 (setq org-table-formula-constants-local cst)))
4731 ;; Process the tags.
4732 (when tags
4733 (let (e tgs)
4734 (while (setq e (pop tags))
4735 (cond
4736 ((equal e "{") (push '(:startgroup) tgs))
4737 ((equal e "}") (push '(:endgroup) tgs))
4738 ((equal e "\\n") (push '(:newline) tgs))
4739 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4740 (push (cons (match-string 1 e)
4741 (string-to-char (match-string 2 e)))
4742 tgs))
4743 (t (push (list e) tgs))))
4744 (org-set-local 'org-tag-alist nil)
4745 (while (setq e (pop tgs))
4746 (or (and (stringp (car e))
4747 (assoc (car e) org-tag-alist))
4748 (push e org-tag-alist)))))
4750 ;; Compute the regular expressions and other local variables.
4751 ;; Using `org-outline-regexp-bol' would complicate them much,
4752 ;; because of the fixed white space at the end of that string.
4753 (if (not org-done-keywords)
4754 (setq org-done-keywords (and org-todo-keywords-1
4755 (list (org-last org-todo-keywords-1)))))
4756 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4757 (length org-scheduled-string)
4758 (length org-clock-string)
4759 (length org-closed-string)))
4760 org-drawer-regexp
4761 (concat "^[ \t]*:\\("
4762 (mapconcat 'regexp-quote org-drawers "\\|")
4763 "\\):[ \t]*$")
4764 org-not-done-keywords
4765 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4766 org-todo-regexp
4767 (concat "\\("
4768 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4769 "\\)")
4770 org-not-done-regexp
4771 (concat "\\("
4772 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4773 "\\)")
4774 org-not-done-heading-regexp
4775 (format org-heading-keyword-regexp-format org-not-done-regexp)
4776 org-todo-line-regexp
4777 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4778 org-complex-heading-regexp
4779 (concat "^\\(\\*+\\)"
4780 "\\(?: +" org-todo-regexp "\\)?"
4781 "\\(?: +\\(\\[#.\\]\\)\\)?"
4782 "\\(?: +\\(.*?\\)\\)??"
4783 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4784 "[ \t]*$")
4785 org-complex-heading-regexp-format
4786 (concat "^\\(\\*+\\)"
4787 "\\(?: +" org-todo-regexp "\\)?"
4788 "\\(?: +\\(\\[#.\\]\\)\\)?"
4789 "\\(?: +"
4790 ;; Stats cookies can be stuck to body.
4791 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4792 "\\(%s\\)"
4793 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4794 "\\)"
4795 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4796 "[ \t]*$")
4797 org-todo-line-tags-regexp
4798 (concat "^\\(\\*+\\)"
4799 "\\(?: +" org-todo-regexp "\\)?"
4800 "\\(?: +\\(.*?\\)\\)??"
4801 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4802 "[ \t]*$")
4803 org-deadline-regexp (concat "\\<" org-deadline-string)
4804 org-deadline-time-regexp
4805 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4806 org-deadline-line-regexp
4807 (concat "\\<\\(" org-deadline-string "\\).*")
4808 org-scheduled-regexp
4809 (concat "\\<" org-scheduled-string)
4810 org-scheduled-time-regexp
4811 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4812 org-closed-time-regexp
4813 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4814 org-keyword-time-regexp
4815 (concat "\\<\\(" org-scheduled-string
4816 "\\|" org-deadline-string
4817 "\\|" org-closed-string
4818 "\\|" org-clock-string "\\)"
4819 " *[[<]\\([^]>]+\\)[]>]")
4820 org-keyword-time-not-clock-regexp
4821 (concat "\\<\\(" org-scheduled-string
4822 "\\|" org-deadline-string
4823 "\\|" org-closed-string
4824 "\\)"
4825 " *[[<]\\([^]>]+\\)[]>]")
4826 org-maybe-keyword-time-regexp
4827 (concat "\\(\\<\\(" org-scheduled-string
4828 "\\|" org-deadline-string
4829 "\\|" org-closed-string
4830 "\\|" org-clock-string "\\)\\)?"
4831 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4832 org-all-time-keywords
4833 (mapcar (lambda (w) (substring w 0 -1))
4834 (list org-scheduled-string org-deadline-string
4835 org-clock-string org-closed-string))
4837 (org-compute-latex-and-specials-regexp)
4838 (org-set-font-lock-defaults))))
4840 (defun org-file-contents (file &optional noerror)
4841 "Return the contents of FILE, as a string."
4842 (if (or (not file)
4843 (not (file-readable-p file)))
4844 (if noerror
4845 (progn
4846 (message "Cannot read file \"%s\"" file)
4847 (ding) (sit-for 2)
4849 (error "Cannot read file \"%s\"" file))
4850 (with-temp-buffer
4851 (insert-file-contents file)
4852 (buffer-string))))
4854 (defun org-extract-log-state-settings (x)
4855 "Extract the log state setting from a TODO keyword string.
4856 This will extract info from a string like \"WAIT(w@/!)\"."
4857 (let (kw key log1 log2)
4858 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4859 (setq kw (match-string 1 x)
4860 key (and (match-end 2) (match-string 2 x))
4861 log1 (and (match-end 3) (match-string 3 x))
4862 log2 (and (match-end 4) (match-string 4 x)))
4863 (and (or log1 log2)
4864 (list kw
4865 (and log1 (if (equal log1 "!") 'time 'note))
4866 (and log2 (if (equal log2 "!") 'time 'note)))))))
4868 (defun org-remove-keyword-keys (list)
4869 "Remove a pair of parenthesis at the end of each string in LIST."
4870 (mapcar (lambda (x)
4871 (if (string-match "(.*)$" x)
4872 (substring x 0 (match-beginning 0))
4874 list))
4876 (defun org-assign-fast-keys (alist)
4877 "Assign fast keys to a keyword-key alist.
4878 Respect keys that are already there."
4879 (let (new e (alt ?0))
4880 (while (setq e (pop alist))
4881 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4882 (cdr e)) ;; Key already assigned.
4883 (push e new)
4884 (let ((clist (string-to-list (downcase (car e))))
4885 (used (append new alist)))
4886 (when (= (car clist) ?@)
4887 (pop clist))
4888 (while (and clist (rassoc (car clist) used))
4889 (pop clist))
4890 (unless clist
4891 (while (rassoc alt used)
4892 (incf alt)))
4893 (push (cons (car e) (or (car clist) alt)) new))))
4894 (nreverse new)))
4896 ;;; Some variables used in various places
4898 (defvar org-window-configuration nil
4899 "Used in various places to store a window configuration.")
4900 (defvar org-selected-window nil
4901 "Used in various places to store a window configuration.")
4902 (defvar org-finish-function nil
4903 "Function to be called when `C-c C-c' is used.
4904 This is for getting out of special buffers like capture.")
4907 ;; FIXME: Occasionally check by commenting these, to make sure
4908 ;; no other functions uses these, forgetting to let-bind them.
4909 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4910 (defvar org-last-state)
4911 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4913 ;; Defined somewhere in this file, but used before definition.
4914 (defvar org-entities) ;; defined in org-entities.el
4915 (defvar org-struct-menu)
4916 (defvar org-org-menu)
4917 (defvar org-tbl-menu)
4919 ;;;; Define the Org-mode
4921 ;; We use a before-change function to check if a table might need
4922 ;; an update.
4923 (defvar org-table-may-need-update t
4924 "Indicates that a table might need an update.
4925 This variable is set by `org-before-change-function'.
4926 `org-table-align' sets it back to nil.")
4927 (defun org-before-change-function (beg end)
4928 "Every change indicates that a table might need an update."
4929 (setq org-table-may-need-update t))
4930 (defvar org-mode-map)
4931 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4932 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4933 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4934 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4935 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4936 (defvar org-table-buffer-is-an nil)
4938 (defvar bidi-paragraph-direction)
4939 (defvar buffer-face-mode-face)
4941 (require 'outline)
4942 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4943 (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"))
4944 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4946 ;; Other stuff we need.
4947 (require 'time-date)
4948 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4949 (require 'easymenu)
4950 (require 'overlay)
4952 (require 'org-macs)
4953 (require 'org-entities)
4954 ;; (require 'org-compat) moved higher up in the file before it is first used
4955 (require 'org-faces)
4956 (require 'org-list)
4957 (require 'org-pcomplete)
4958 (require 'org-src)
4959 (require 'org-footnote)
4961 ;; babel
4962 (require 'ob)
4963 (require 'ob-table)
4964 (require 'ob-lob)
4965 (require 'ob-ref)
4966 (require 'ob-tangle)
4967 (require 'ob-comint)
4968 (require 'ob-keys)
4970 ;;;###autoload
4971 (define-derived-mode org-mode outline-mode "Org"
4972 "Outline-based notes management and organizer, alias
4973 \"Carsten's outline-mode for keeping track of everything.\"
4975 Org-mode develops organizational tasks around a NOTES file which
4976 contains information about projects as plain text. Org-mode is
4977 implemented on top of outline-mode, which is ideal to keep the content
4978 of large files well structured. It supports ToDo items, deadlines and
4979 time stamps, which magically appear in the diary listing of the Emacs
4980 calendar. Tables are easily created with a built-in table editor.
4981 Plain text URL-like links connect to websites, emails (VM), Usenet
4982 messages (Gnus), BBDB entries, and any files related to the project.
4983 For printing and sharing of notes, an Org-mode file (or a part of it)
4984 can be exported as a structured ASCII or HTML file.
4986 The following commands are available:
4988 \\{org-mode-map}"
4990 ;; Get rid of Outline menus, they are not needed
4991 ;; Need to do this here because define-derived-mode sets up
4992 ;; the keymap so late. Still, it is a waste to call this each time
4993 ;; we switch another buffer into org-mode.
4994 (if (featurep 'xemacs)
4995 (when (boundp 'outline-mode-menu-heading)
4996 ;; Assume this is Greg's port, it uses easymenu
4997 (easy-menu-remove outline-mode-menu-heading)
4998 (easy-menu-remove outline-mode-menu-show)
4999 (easy-menu-remove outline-mode-menu-hide))
5000 (define-key org-mode-map [menu-bar headings] 'undefined)
5001 (define-key org-mode-map [menu-bar hide] 'undefined)
5002 (define-key org-mode-map [menu-bar show] 'undefined))
5004 (org-load-modules-maybe)
5005 (easy-menu-add org-org-menu)
5006 (easy-menu-add org-tbl-menu)
5007 (org-install-agenda-files-menu)
5008 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5009 (add-to-invisibility-spec '(org-cwidth))
5010 (add-to-invisibility-spec '(org-hide-block . t))
5011 (when (featurep 'xemacs)
5012 (org-set-local 'line-move-ignore-invisible t))
5013 (org-set-local 'outline-regexp org-outline-regexp)
5014 (org-set-local 'outline-level 'org-outline-level)
5015 (setq bidi-paragraph-direction 'left-to-right)
5016 (when (and org-ellipsis
5017 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5018 (fboundp 'make-glyph-code))
5019 (unless org-display-table
5020 (setq org-display-table (make-display-table)))
5021 (set-display-table-slot
5022 org-display-table 4
5023 (vconcat (mapcar
5024 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5025 org-ellipsis)))
5026 (if (stringp org-ellipsis) org-ellipsis "..."))))
5027 (setq buffer-display-table org-display-table))
5028 (org-set-regexps-and-options)
5029 (when (and org-tag-faces (not org-tags-special-faces-re))
5030 ;; tag faces set outside customize.... force initialization.
5031 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5032 ;; Calc embedded
5033 (org-set-local 'calc-embedded-open-mode "# ")
5034 (modify-syntax-entry ?@ "w")
5035 (if org-startup-truncated (setq truncate-lines t))
5036 (org-set-local 'font-lock-unfontify-region-function
5037 'org-unfontify-region)
5038 ;; Activate before-change-function
5039 (org-set-local 'org-table-may-need-update t)
5040 (org-add-hook 'before-change-functions 'org-before-change-function nil
5041 'local)
5042 ;; Check for running clock before killing a buffer
5043 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5044 ;; Indentation.
5045 (org-set-local 'indent-line-function 'org-indent-line)
5046 (org-set-local 'indent-region-function 'org-indent-region)
5047 ;; Initialize radio targets.
5048 (org-update-radio-target-regexp)
5049 ;; Filling and auto-filling.
5050 (org-setup-filling)
5051 ;; Comments.
5052 (org-setup-comments-handling)
5053 ;; Beginning/end of defun
5054 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5055 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5056 ;; Next error for sparse trees
5057 (org-set-local 'next-error-function 'org-occur-next-match)
5058 ;; Make sure dependence stuff works reliably, even for users who set it
5059 ;; too late :-(
5060 (if org-enforce-todo-dependencies
5061 (add-hook 'org-blocker-hook
5062 'org-block-todo-from-children-or-siblings-or-parent)
5063 (remove-hook 'org-blocker-hook
5064 'org-block-todo-from-children-or-siblings-or-parent))
5065 (if org-enforce-todo-checkbox-dependencies
5066 (add-hook 'org-blocker-hook
5067 'org-block-todo-from-checkboxes)
5068 (remove-hook 'org-blocker-hook
5069 'org-block-todo-from-checkboxes))
5071 ;; Align options lines
5072 (org-set-local
5073 'align-mode-rules-list
5074 '((org-in-buffer-settings
5075 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5076 (modes . '(org-mode)))))
5078 ;; Imenu
5079 (org-set-local 'imenu-create-index-function
5080 'org-imenu-get-tree)
5082 ;; Make isearch reveal context
5083 (if (or (featurep 'xemacs)
5084 (not (boundp 'outline-isearch-open-invisible-function)))
5085 ;; Emacs 21 and XEmacs make use of the hook
5086 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5087 ;; Emacs 22 deals with this through a special variable
5088 (org-set-local 'outline-isearch-open-invisible-function
5089 (lambda (&rest ignore) (org-show-context 'isearch))))
5091 ;; Turn on org-beamer-mode?
5092 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5094 ;; Setup the pcomplete hooks
5095 (set (make-local-variable 'pcomplete-command-completion-function)
5096 'org-pcomplete-initial)
5097 (set (make-local-variable 'pcomplete-command-name-function)
5098 'org-command-at-point)
5099 (set (make-local-variable 'pcomplete-default-completion-function)
5100 'ignore)
5101 (set (make-local-variable 'pcomplete-parse-arguments-function)
5102 'org-parse-arguments)
5103 (set (make-local-variable 'pcomplete-termination-string) "")
5104 (when (>= emacs-major-version 23)
5105 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5107 ;; If empty file that did not turn on org-mode automatically, make it to.
5108 (if (and org-insert-mode-line-in-empty-file
5109 (org-called-interactively-p 'any)
5110 (= (point-min) (point-max)))
5111 (insert "# -*- mode: org -*-\n\n"))
5112 (unless org-inhibit-startup
5113 (when org-startup-align-all-tables
5114 (let ((bmp (buffer-modified-p)))
5115 (org-table-map-tables 'org-table-align 'quietly)
5116 (set-buffer-modified-p bmp)))
5117 (when org-startup-with-inline-images
5118 (org-display-inline-images))
5119 (when org-startup-indented
5120 (require 'org-indent)
5121 (org-indent-mode 1))
5122 (unless org-inhibit-startup-visibility-stuff
5123 (org-set-startup-visibility)))
5124 ;; Try to set org-hide correctly
5125 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5127 (when (fboundp 'abbrev-table-put)
5128 (abbrev-table-put org-mode-abbrev-table
5129 :parents (list text-mode-abbrev-table)))
5131 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5134 (defun org-find-invisible-foreground ()
5135 (let ((candidates (remove
5136 "unspecified-bg"
5137 (list
5138 (face-background 'default)
5139 (face-background 'org-default)
5140 (cdr (assoc 'background-color default-frame-alist))
5141 (cdr (assoc 'background-color initial-frame-alist))
5142 (cdr (assoc 'background-color window-system-default-frame-alist))
5143 (face-foreground 'org-hide)))))
5144 (car (remove nil candidates))))
5146 (defun org-current-time ()
5147 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5148 (if (> (car org-time-stamp-rounding-minutes) 1)
5149 (let ((r (car org-time-stamp-rounding-minutes))
5150 (time (decode-time)))
5151 (apply 'encode-time
5152 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5153 (nthcdr 2 time))))
5154 (current-time)))
5156 (defun org-today ()
5157 "Return today date, considering `org-extend-today-until'."
5158 (time-to-days
5159 (time-subtract (current-time)
5160 (list 0 (* 3600 org-extend-today-until) 0))))
5162 ;;;; Font-Lock stuff, including the activators
5164 (defvar org-mouse-map (make-sparse-keymap))
5165 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5166 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5167 (when org-mouse-1-follows-link
5168 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5169 (when org-tab-follows-link
5170 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5171 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5173 (require 'font-lock)
5175 (defconst org-non-link-chars "]\t\n\r<>")
5176 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5177 "shell" "elisp" "doi" "message"))
5178 (defvar org-link-types-re nil
5179 "Matches a link that has a url-like prefix like \"http:\"")
5180 (defvar org-link-re-with-space nil
5181 "Matches a link with spaces, optional angular brackets around it.")
5182 (defvar org-link-re-with-space2 nil
5183 "Matches a link with spaces, optional angular brackets around it.")
5184 (defvar org-link-re-with-space3 nil
5185 "Matches a link with spaces, only for internal part in bracket links.")
5186 (defvar org-angle-link-re nil
5187 "Matches link with angular brackets, spaces are allowed.")
5188 (defvar org-plain-link-re nil
5189 "Matches plain link, without spaces.")
5190 (defvar org-bracket-link-regexp nil
5191 "Matches a link in double brackets.")
5192 (defvar org-bracket-link-analytic-regexp nil
5193 "Regular expression used to analyze links.
5194 Here is what the match groups contain after a match:
5195 1: http:
5196 2: http
5197 3: path
5198 4: [desc]
5199 5: desc")
5200 (defvar org-bracket-link-analytic-regexp++ nil
5201 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5202 (defvar org-any-link-re nil
5203 "Regular expression matching any link.")
5205 (defcustom org-match-sexp-depth 3
5206 "Number of stacked braces for sub/superscript matching.
5207 This has to be set before loading org.el to be effective."
5208 :group 'org-export-translation ; ??????????????????????????/
5209 :type 'integer)
5211 (defun org-create-multibrace-regexp (left right n)
5212 "Create a regular expression which will match a balanced sexp.
5213 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5214 as single character strings.
5215 The regexp returned will match the entire expression including the
5216 delimiters. It will also define a single group which contains the
5217 match except for the outermost delimiters. The maximum depth of
5218 stacked delimiters is N. Escaping delimiters is not possible."
5219 (let* ((nothing (concat "[^" left right "]*?"))
5220 (or "\\|")
5221 (re nothing)
5222 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5223 (while (> n 1)
5224 (setq n (1- n)
5225 re (concat re or next)
5226 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5227 (concat left "\\(" re "\\)" right)))
5229 (defvar org-match-substring-regexp
5230 (concat
5231 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5232 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5233 "\\|"
5234 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5235 "\\|"
5236 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5237 "The regular expression matching a sub- or superscript.")
5239 (defvar org-match-substring-with-braces-regexp
5240 (concat
5241 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5242 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5243 "\\)")
5244 "The regular expression matching a sub- or superscript, forcing braces.")
5246 (defun org-make-link-regexps ()
5247 "Update the link regular expressions.
5248 This should be called after the variable `org-link-types' has changed."
5249 (setq org-link-types-re
5250 (concat
5251 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5252 org-link-re-with-space
5253 (concat
5254 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5255 "\\([^" org-non-link-chars " ]"
5256 "[^" org-non-link-chars "]*"
5257 "[^" org-non-link-chars " ]\\)>?")
5258 org-link-re-with-space2
5259 (concat
5260 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5261 "\\([^" org-non-link-chars " ]"
5262 "[^\t\n\r]*"
5263 "[^" org-non-link-chars " ]\\)>?")
5264 org-link-re-with-space3
5265 (concat
5266 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5267 "\\([^" org-non-link-chars " ]"
5268 "[^\t\n\r]*\\)")
5269 org-angle-link-re
5270 (concat
5271 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5272 "\\([^" org-non-link-chars " ]"
5273 "[^" org-non-link-chars "]*"
5274 "\\)>")
5275 org-plain-link-re
5276 (concat
5277 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5278 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5279 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5280 org-bracket-link-regexp
5281 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5282 org-bracket-link-analytic-regexp
5283 (concat
5284 "\\[\\["
5285 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5286 "\\([^]]+\\)"
5287 "\\]"
5288 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5289 "\\]")
5290 org-bracket-link-analytic-regexp++
5291 (concat
5292 "\\[\\["
5293 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5294 "\\([^]]+\\)"
5295 "\\]"
5296 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5297 "\\]")
5298 org-any-link-re
5299 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5300 org-angle-link-re "\\)\\|\\("
5301 org-plain-link-re "\\)")))
5303 (org-make-link-regexps)
5305 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5306 "Regular expression for fast time stamp matching.")
5307 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5308 "Regular expression for fast time stamp matching.")
5309 (defconst org-ts-regexp0
5310 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5311 "Regular expression matching time strings for analysis.
5312 This one does not require the space after the date, so it can be used
5313 on a string that terminates immediately after the date.")
5314 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5315 "Regular expression matching time strings for analysis.")
5316 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5317 "Regular expression matching time stamps, with groups.")
5318 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5319 "Regular expression matching time stamps (also [..]), with groups.")
5320 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5321 "Regular expression matching a time stamp range.")
5322 (defconst org-tr-regexp-both
5323 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5324 "Regular expression matching a time stamp range.")
5325 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5326 org-ts-regexp "\\)?")
5327 "Regular expression matching a time stamp or time stamp range.")
5328 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5329 org-ts-regexp-both "\\)?")
5330 "Regular expression matching a time stamp or time stamp range.
5331 The time stamps may be either active or inactive.")
5333 (defvar org-emph-face nil)
5335 (defun org-do-emphasis-faces (limit)
5336 "Run through the buffer and add overlays to emphasized strings."
5337 (let (rtn a)
5338 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5339 (if (not (= (char-after (match-beginning 3))
5340 (char-after (match-beginning 4))))
5341 (progn
5342 (setq rtn t)
5343 (setq a (assoc (match-string 3) org-emphasis-alist))
5344 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5345 'face
5346 (nth 1 a))
5347 (and (nth 4 a)
5348 (org-remove-flyspell-overlays-in
5349 (match-beginning 0) (match-end 0)))
5350 (add-text-properties (match-beginning 2) (match-end 2)
5351 '(font-lock-multiline t org-emphasis t))
5352 (when org-hide-emphasis-markers
5353 (add-text-properties (match-end 4) (match-beginning 5)
5354 '(invisible org-link))
5355 (add-text-properties (match-beginning 3) (match-end 3)
5356 '(invisible org-link)))))
5357 (backward-char 1))
5358 rtn))
5360 (defun org-emphasize (&optional char)
5361 "Insert or change an emphasis, i.e. a font like bold or italic.
5362 If there is an active region, change that region to a new emphasis.
5363 If there is no region, just insert the marker characters and position
5364 the cursor between them.
5365 CHAR should be either the marker character, or the first character of the
5366 HTML tag associated with that emphasis. If CHAR is a space, the means
5367 to remove the emphasis of the selected region.
5368 If char is not given (for example in an interactive call) it
5369 will be prompted for."
5370 (interactive)
5371 (let ((eal org-emphasis-alist) e det
5372 (erc org-emphasis-regexp-components)
5373 (prompt "")
5374 (string "") beg end move tag c s)
5375 (if (org-region-active-p)
5376 (setq beg (region-beginning) end (region-end)
5377 string (buffer-substring beg end))
5378 (setq move t))
5380 (while (setq e (pop eal))
5381 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5382 c (aref tag 0))
5383 (push (cons c (string-to-char (car e))) det)
5384 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5385 (substring tag 1)))))
5386 (setq det (nreverse det))
5387 (unless char
5388 (message "%s" (concat "Emphasis marker or tag:" prompt))
5389 (setq char (read-char-exclusive)))
5390 (setq char (or (cdr (assoc char det)) char))
5391 (if (equal char ?\ )
5392 (setq s "" move nil)
5393 (unless (assoc (char-to-string char) org-emphasis-alist)
5394 (error "No such emphasis marker: \"%c\"" char))
5395 (setq s (char-to-string char)))
5396 (while (and (> (length string) 1)
5397 (equal (substring string 0 1) (substring string -1))
5398 (assoc (substring string 0 1) org-emphasis-alist))
5399 (setq string (substring string 1 -1)))
5400 (setq string (concat s string s))
5401 (if beg (delete-region beg end))
5402 (unless (or (bolp)
5403 (string-match (concat "[" (nth 0 erc) "\n]")
5404 (char-to-string (char-before (point)))))
5405 (insert " "))
5406 (unless (or (eobp)
5407 (string-match (concat "[" (nth 1 erc) "\n]")
5408 (char-to-string (char-after (point)))))
5409 (insert " ") (backward-char 1))
5410 (insert string)
5411 (and move (backward-char 1))))
5413 (defconst org-nonsticky-props
5414 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5416 (defsubst org-rear-nonsticky-at (pos)
5417 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5419 (defun org-activate-plain-links (limit)
5420 "Run through the buffer and add overlays to links."
5421 (catch 'exit
5422 (let (f)
5423 (when (re-search-forward (concat org-plain-link-re) limit t)
5424 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5425 (setq f (get-text-property (match-beginning 0) 'face))
5426 (if (or (eq f 'org-tag)
5427 (and (listp f) (memq 'org-tag f)))
5429 (add-text-properties (match-beginning 0) (match-end 0)
5430 (list 'mouse-face 'highlight
5431 'face 'org-link
5432 'keymap org-mouse-map))
5433 (org-rear-nonsticky-at (match-end 0)))
5434 t))))
5436 (defun org-activate-code (limit)
5437 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5438 (progn
5439 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5440 (remove-text-properties (match-beginning 0) (match-end 0)
5441 '(display t invisible t intangible t))
5442 t)))
5444 (defcustom org-src-fontify-natively nil
5445 "When non-nil, fontify code in code blocks."
5446 :type 'boolean
5447 :version "24.1"
5448 :group 'org-appearance
5449 :group 'org-babel)
5451 (defcustom org-allow-promoting-top-level-subtree nil
5452 "When non-nil, allow promoting a top level subtree.
5453 The leading star of the top level headline will be replaced
5454 by a #."
5455 :type 'boolean
5456 :version "24.1"
5457 :group 'org-appearance)
5459 (defun org-fontify-meta-lines-and-blocks (limit)
5460 (condition-case nil
5461 (org-fontify-meta-lines-and-blocks-1 limit)
5462 (error (message "org-mode fontification error"))))
5464 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5465 "Fontify #+ lines and blocks, in the correct ways."
5466 (let ((case-fold-search t))
5467 (if (re-search-forward
5468 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5469 limit t)
5470 (let ((beg (match-beginning 0))
5471 (block-start (match-end 0))
5472 (block-end nil)
5473 (lang (match-string 7))
5474 (beg1 (line-beginning-position 2))
5475 (dc1 (downcase (match-string 2)))
5476 (dc3 (downcase (match-string 3)))
5477 end end1 quoting block-type ovl)
5478 (cond
5479 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5480 ;; a single line of backend-specific content
5481 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5482 (remove-text-properties (match-beginning 0) (match-end 0)
5483 '(display t invisible t intangible t))
5484 (add-text-properties (match-beginning 1) (match-end 3)
5485 '(font-lock-fontified t face org-meta-line))
5486 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5487 '(font-lock-fontified t face org-block))
5488 ; for backend-specific code
5490 ((and (match-end 4) (equal dc3 "+begin"))
5491 ;; Truly a block
5492 (setq block-type (downcase (match-string 5))
5493 quoting (member block-type org-protecting-blocks))
5494 (when (re-search-forward
5495 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5496 nil t) ;; on purpose, we look further than LIMIT
5497 (setq end (min (point-max) (match-end 0))
5498 end1 (min (point-max) (1- (match-beginning 0))))
5499 (setq block-end (match-beginning 0))
5500 (when quoting
5501 (remove-text-properties beg end
5502 '(display t invisible t intangible t)))
5503 (add-text-properties
5504 beg end
5505 '(font-lock-fontified t font-lock-multiline t))
5506 (add-text-properties beg beg1 '(face org-meta-line))
5507 (add-text-properties end1 (min (point-max) (1+ end))
5508 '(face org-meta-line)) ; for end_src
5509 (cond
5510 ((and lang (not (string= lang "")) org-src-fontify-natively)
5511 (org-src-font-lock-fontify-block lang block-start block-end)
5512 ;; remove old background overlays
5513 (mapc (lambda (ov)
5514 (if (eq (overlay-get ov 'face) 'org-block-background)
5515 (delete-overlay ov)))
5516 (overlays-at (/ (+ beg1 block-end) 2)))
5517 ;; add a background overlay
5518 (setq ovl (make-overlay beg1 block-end))
5519 (overlay-put ovl 'face 'org-block-background)
5520 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5521 (quoting
5522 (add-text-properties beg1 (min (point-max) (1+ end1))
5523 '(face org-block))) ; end of source block
5524 ((not org-fontify-quote-and-verse-blocks))
5525 ((string= block-type "quote")
5526 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5527 ((string= block-type "verse")
5528 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5529 (add-text-properties beg beg1 '(face org-block-begin-line))
5530 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5531 '(face org-block-end-line))
5533 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5534 (add-text-properties
5535 beg (match-end 3)
5536 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5537 '(font-lock-fontified t invisible t)
5538 '(font-lock-fontified t face org-document-info-keyword)))
5539 (add-text-properties
5540 (match-beginning 6) (match-end 6)
5541 (if (string-equal dc1 "+title:")
5542 '(font-lock-fontified t face org-document-title)
5543 '(font-lock-fontified t face org-document-info))))
5544 ((or (equal dc1 "+results")
5545 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5546 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5547 "+call:" "+header:" "+headers:" "+name:"))
5548 (and (match-end 4) (equal dc3 "+attr")))
5549 (add-text-properties
5550 beg (match-end 0)
5551 '(font-lock-fontified t face org-meta-line))
5553 ((member dc3 '(" " ""))
5554 (add-text-properties
5555 beg (match-end 0)
5556 '(font-lock-fontified t face font-lock-comment-face)))
5557 ((not (member (char-after beg) '(?\ ?\t)))
5558 ;; just any other in-buffer setting, but not indented
5559 (add-text-properties
5560 beg (match-end 0)
5561 '(font-lock-fontified t face org-meta-line))
5563 (t nil))))))
5565 (defun org-activate-angle-links (limit)
5566 "Run through the buffer and add overlays to links."
5567 (if (re-search-forward org-angle-link-re limit t)
5568 (progn
5569 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5570 (add-text-properties (match-beginning 0) (match-end 0)
5571 (list 'mouse-face 'highlight
5572 'keymap org-mouse-map))
5573 (org-rear-nonsticky-at (match-end 0))
5574 t)))
5576 (defun org-activate-footnote-links (limit)
5577 "Run through the buffer and add overlays to footnotes."
5578 (let ((fn (org-footnote-next-reference-or-definition limit)))
5579 (when fn
5580 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5581 (org-remove-flyspell-overlays-in beg end)
5582 (add-text-properties beg end
5583 (list 'mouse-face 'highlight
5584 'keymap org-mouse-map
5585 'help-echo
5586 (if (= (point-at-bol) beg)
5587 "Footnote definition"
5588 "Footnote reference")
5589 'font-lock-fontified t
5590 'font-lock-multiline t
5591 'face 'org-footnote))))))
5593 (defun org-activate-bracket-links (limit)
5594 "Run through the buffer and add overlays to bracketed links."
5595 (if (re-search-forward org-bracket-link-regexp limit t)
5596 (let* ((help (concat "LINK: "
5597 (org-match-string-no-properties 1)))
5598 ;; FIXME: above we should remove the escapes.
5599 ;; but that requires another match, protecting match data,
5600 ;; a lot of overhead for font-lock.
5601 (ip (org-maybe-intangible
5602 (list 'invisible 'org-link
5603 'keymap org-mouse-map 'mouse-face 'highlight
5604 'font-lock-multiline t 'help-echo help)))
5605 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5606 'font-lock-multiline t 'help-echo help)))
5607 ;; We need to remove the invisible property here. Table narrowing
5608 ;; may have made some of this invisible.
5609 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5610 (remove-text-properties (match-beginning 0) (match-end 0)
5611 '(invisible nil))
5612 (if (match-end 3)
5613 (progn
5614 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5615 (org-rear-nonsticky-at (match-beginning 3))
5616 (add-text-properties (match-beginning 3) (match-end 3) vp)
5617 (org-rear-nonsticky-at (match-end 3))
5618 (add-text-properties (match-end 3) (match-end 0) ip)
5619 (org-rear-nonsticky-at (match-end 0)))
5620 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5621 (org-rear-nonsticky-at (match-beginning 1))
5622 (add-text-properties (match-beginning 1) (match-end 1) vp)
5623 (org-rear-nonsticky-at (match-end 1))
5624 (add-text-properties (match-end 1) (match-end 0) ip)
5625 (org-rear-nonsticky-at (match-end 0)))
5626 t)))
5628 (defun org-activate-dates (limit)
5629 "Run through the buffer and add overlays to dates."
5630 (if (re-search-forward org-tsr-regexp-both limit t)
5631 (progn
5632 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5633 (add-text-properties (match-beginning 0) (match-end 0)
5634 (list 'mouse-face 'highlight
5635 'keymap org-mouse-map))
5636 (org-rear-nonsticky-at (match-end 0))
5637 (when org-display-custom-times
5638 (if (match-end 3)
5639 (org-display-custom-time (match-beginning 3) (match-end 3)))
5640 (org-display-custom-time (match-beginning 1) (match-end 1)))
5641 t)))
5643 (defvar org-target-link-regexp nil
5644 "Regular expression matching radio targets in plain text.")
5645 (make-variable-buffer-local 'org-target-link-regexp)
5646 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5647 "Regular expression matching a link target.")
5648 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5649 "Regular expression matching a radio target.")
5650 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5651 "Regular expression matching any target.")
5653 (defun org-activate-target-links (limit)
5654 "Run through the buffer and add overlays to target matches."
5655 (when org-target-link-regexp
5656 (let ((case-fold-search t))
5657 (if (re-search-forward org-target-link-regexp limit t)
5658 (progn
5659 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5660 (add-text-properties (match-beginning 0) (match-end 0)
5661 (list 'mouse-face 'highlight
5662 'keymap org-mouse-map
5663 'help-echo "Radio target link"
5664 'org-linked-text t))
5665 (org-rear-nonsticky-at (match-end 0))
5666 t)))))
5668 (defun org-update-radio-target-regexp ()
5669 "Find all radio targets in this file and update the regular expression."
5670 (interactive)
5671 (when (memq 'radio org-activate-links)
5672 (setq org-target-link-regexp
5673 (org-make-target-link-regexp (org-all-targets 'radio)))
5674 (org-restart-font-lock)))
5676 (defun org-hide-wide-columns (limit)
5677 (let (s e)
5678 (setq s (text-property-any (point) (or limit (point-max))
5679 'org-cwidth t))
5680 (when s
5681 (setq e (next-single-property-change s 'org-cwidth))
5682 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5683 (goto-char e)
5684 t)))
5686 (defvar org-latex-and-specials-regexp nil
5687 "Regular expression for highlighting export special stuff.")
5688 (defvar org-match-substring-regexp)
5689 (defvar org-match-substring-with-braces-regexp)
5691 ;; This should be with the exporter code, but we also use if for font-locking
5692 (defconst org-export-html-special-string-regexps
5693 '(("\\\\-" . "&shy;")
5694 ("---\\([^-]\\)" . "&mdash;\\1")
5695 ("--\\([^-]\\)" . "&ndash;\\1")
5696 ("\\.\\.\\." . "&hellip;"))
5697 "Regular expressions for special string conversion.")
5700 (defun org-compute-latex-and-specials-regexp ()
5701 "Compute regular expression for stuff treated specially by exporters."
5702 (if (not org-highlight-latex-fragments-and-specials)
5703 (org-set-local 'org-latex-and-specials-regexp nil)
5704 (require 'org-exp)
5705 (let*
5706 ((matchers (plist-get org-format-latex-options :matchers))
5707 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5708 org-latex-regexps)))
5709 (org-export-allow-BIND nil)
5710 (options (org-combine-plists (org-default-export-plist)
5711 (org-infile-export-plist)))
5712 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5713 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5714 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5715 (org-export-html-expand (plist-get options :expand-quoted-html))
5716 (org-export-with-special-strings (plist-get options :special-strings))
5717 (re-sub
5718 (cond
5719 ((equal org-export-with-sub-superscripts '{})
5720 (list org-match-substring-with-braces-regexp))
5721 (org-export-with-sub-superscripts
5722 (list org-match-substring-regexp))))
5723 (re-latex
5724 (if org-export-with-LaTeX-fragments
5725 (mapcar (lambda (x) (nth 1 x)) latexs)))
5726 (re-macros
5727 (if org-export-with-TeX-macros
5728 (list (concat "\\\\"
5729 (regexp-opt
5730 (append
5732 (delq nil
5733 (mapcar 'car-safe
5734 (append org-entities-user
5735 org-entities)))
5736 (if (boundp 'org-latex-entities)
5737 (mapcar (lambda (x)
5738 (or (car-safe x) x))
5739 org-latex-entities)
5740 nil))
5741 'words))) ; FIXME
5743 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5744 (re-special (if org-export-with-special-strings
5745 (mapcar (lambda (x) (car x))
5746 org-export-html-special-string-regexps)))
5747 (re-rest
5748 (delq nil
5749 (list
5750 (if org-export-html-expand "@<[^>\n]+>")
5751 ))))
5752 (org-set-local
5753 'org-latex-and-specials-regexp
5754 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5755 re-rest) "\\|")))))
5757 (defun org-do-latex-and-special-faces (limit)
5758 "Run through the buffer and add overlays to links."
5759 (when org-latex-and-specials-regexp
5760 (let (rtn d)
5761 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5762 limit t))
5763 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5764 'face))
5765 '(org-code org-verbatim underline)))
5766 (progn
5767 (setq rtn t
5768 d (cond ((member (char-after (1+ (match-beginning 0)))
5769 '(?_ ?^)) 1)
5770 (t 0)))
5771 (font-lock-prepend-text-property
5772 (+ d (match-beginning 0)) (match-end 0)
5773 'face 'org-latex-and-export-specials)
5774 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5775 '(font-lock-multiline t)))))
5776 rtn)))
5778 (defun org-restart-font-lock ()
5779 "Restart `font-lock-mode', to force refontification."
5780 (when (and (boundp 'font-lock-mode) font-lock-mode)
5781 (font-lock-mode -1)
5782 (font-lock-mode 1)))
5784 (defun org-all-targets (&optional radio)
5785 "Return a list of all targets in this file.
5786 With optional argument RADIO, only find radio targets."
5787 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5788 rtn)
5789 (save-excursion
5790 (goto-char (point-min))
5791 (while (re-search-forward re nil t)
5792 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5793 rtn)))
5795 (defun org-make-target-link-regexp (targets)
5796 "Make regular expression matching all strings in TARGETS.
5797 The regular expression finds the targets also if there is a line break
5798 between words."
5799 (and targets
5800 (concat
5801 "\\<\\("
5802 (mapconcat
5803 (lambda (x)
5804 (setq x (regexp-quote x))
5805 (while (string-match " +" x)
5806 (setq x (replace-match "\\s-+" t t x)))
5808 targets
5809 "\\|")
5810 "\\)\\>")))
5812 (defun org-activate-tags (limit)
5813 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5814 (progn
5815 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5816 (add-text-properties (match-beginning 1) (match-end 1)
5817 (list 'mouse-face 'highlight
5818 'keymap org-mouse-map))
5819 (org-rear-nonsticky-at (match-end 1))
5820 t)))
5822 (defun org-outline-level ()
5823 "Compute the outline level of the heading at point.
5824 This function assumes that the cursor is at the beginning of a line matched
5825 by `outline-regexp'. Otherwise it returns garbage.
5826 If this is called at a normal headline, the level is the number of stars.
5827 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5828 (save-excursion
5829 (looking-at org-outline-regexp)
5830 (1- (- (match-end 0) (match-beginning 0)))))
5832 (defvar org-font-lock-keywords nil)
5834 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5835 "Regular expression matching a property line.")
5837 (defvar org-font-lock-hook nil
5838 "Functions to be called for special font lock stuff.")
5840 (defvar org-font-lock-set-keywords-hook nil
5841 "Functions that can manipulate `org-font-lock-extra-keywords'.
5842 This is called after `org-font-lock-extra-keywords' is defined, but before
5843 it is installed to be used by font lock. This can be useful if something
5844 needs to be inserted at a specific position in the font-lock sequence.")
5846 (defun org-font-lock-hook (limit)
5847 "Run `org-font-lock-hook' within LIMIT."
5848 (run-hook-with-args 'org-font-lock-hook limit))
5850 (defun org-set-font-lock-defaults ()
5851 "Set font lock defaults for the current buffer."
5852 (let* ((em org-fontify-emphasized-text)
5853 (lk org-activate-links)
5854 (org-font-lock-extra-keywords
5855 (list
5856 ;; Call the hook
5857 '(org-font-lock-hook)
5858 ;; Headlines
5859 `(,(if org-fontify-whole-heading-line
5860 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5861 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5862 (1 (org-get-level-face 1))
5863 (2 (org-get-level-face 2))
5864 (3 (org-get-level-face 3)))
5865 ;; Table lines
5866 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5867 (1 'org-table t))
5868 ;; Table internals
5869 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5870 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5871 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5872 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5873 ;; Drawers
5874 (list org-drawer-regexp '(0 'org-special-keyword t))
5875 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5876 ;; Properties
5877 (list org-property-re
5878 '(1 'org-special-keyword t)
5879 '(3 'org-property-value t))
5880 ;; Links
5881 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5882 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5883 (if (memq 'plain lk) '(org-activate-plain-links))
5884 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5885 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5886 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5887 (if (memq 'footnote lk) '(org-activate-footnote-links))
5888 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5889 '(org-hide-wide-columns (0 nil append))
5890 ;; TODO keyword
5891 (list (format org-heading-keyword-regexp-format
5892 org-todo-regexp)
5893 '(2 (org-get-todo-face 2) t))
5894 ;; DONE
5895 (if org-fontify-done-headline
5896 (list (format org-heading-keyword-regexp-format
5897 (concat
5898 "\\(?:"
5899 (mapconcat 'regexp-quote org-done-keywords "\\|")
5900 "\\)"))
5901 '(2 'org-headline-done t))
5902 nil)
5903 ;; Priorities
5904 '(org-font-lock-add-priority-faces)
5905 ;; Tags
5906 '(org-font-lock-add-tag-faces)
5907 ;; Special keywords
5908 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5909 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5910 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5911 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5912 ;; Emphasis
5913 (if em
5914 (if (featurep 'xemacs)
5915 '(org-do-emphasis-faces (0 nil append))
5916 '(org-do-emphasis-faces)))
5917 ;; Checkboxes
5918 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5919 1 'org-checkbox prepend)
5920 (if (cdr (assq 'checkbox org-list-automatic-rules))
5921 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5922 (0 (org-get-checkbox-statistics-face) t)))
5923 ;; Description list items
5924 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5925 1 'org-list-dt prepend)
5926 ;; ARCHIVEd headings
5927 (list (concat
5928 org-outline-regexp-bol
5929 "\\(.*:" org-archive-tag ":.*\\)")
5930 '(1 'org-archived prepend))
5931 ;; Specials
5932 '(org-do-latex-and-special-faces)
5933 '(org-fontify-entities)
5934 '(org-raise-scripts)
5935 ;; Code
5936 '(org-activate-code (1 'org-code t))
5937 ;; COMMENT
5938 (list (format org-heading-keyword-regexp-format
5939 (concat "\\("
5940 org-comment-string "\\|" org-quote-string
5941 "\\)"))
5942 '(2 'org-special-keyword t))
5943 ;; Blocks and meta lines
5944 '(org-fontify-meta-lines-and-blocks)
5946 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5947 (run-hooks 'org-font-lock-set-keywords-hook)
5948 ;; Now set the full font-lock-keywords
5949 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5950 (org-set-local 'font-lock-defaults
5951 '(org-font-lock-keywords t nil nil backward-paragraph))
5952 (kill-local-variable 'font-lock-keywords) nil))
5954 (defun org-toggle-pretty-entities ()
5955 "Toggle the composition display of entities as UTF8 characters."
5956 (interactive)
5957 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5958 (org-restart-font-lock)
5959 (if org-pretty-entities
5960 (message "Entities are displayed as UTF8 characters")
5961 (save-restriction
5962 (widen)
5963 (org-decompose-region (point-min) (point-max))
5964 (message "Entities are displayed plain"))))
5966 (defvar org-custom-properties-overlays nil
5967 "List of overlays used for custom properties.")
5968 (make-variable-buffer-local 'org-custom-properties-overlays)
5970 (defun org-toggle-custom-properties-visibility ()
5971 "Display or hide properties in `org-custom-properties'."
5972 (interactive)
5973 (if org-custom-properties-overlays
5974 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5975 (setq org-custom-properties-overlays nil))
5976 (unless (not org-custom-properties)
5977 (save-excursion
5978 (save-restriction
5979 (widen)
5980 (goto-char (point-min))
5981 (while (re-search-forward org-property-re nil t)
5982 (mapc (lambda(p)
5983 (when (equal p (substring (match-string 1) 1 -1))
5984 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5985 (overlay-put o 'invisible t)
5986 (overlay-put o 'org-custom-property t)
5987 (push o org-custom-properties-overlays))))
5988 org-custom-properties)))))))
5990 (defun org-fontify-entities (limit)
5991 "Find an entity to fontify."
5992 (let (ee)
5993 (when org-pretty-entities
5994 (catch 'match
5995 (while (re-search-forward
5996 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5997 limit t)
5998 (if (and (not (org-in-indented-comment-line))
5999 (setq ee (org-entity-get (match-string 1)))
6000 (= (length (nth 6 ee)) 1))
6001 (let*
6002 ((end (if (equal (match-string 2) "{}")
6003 (match-end 2)
6004 (match-end 1))))
6005 (add-text-properties
6006 (match-beginning 0) end
6007 (list 'font-lock-fontified t))
6008 (compose-region (match-beginning 0) end
6009 (nth 6 ee) nil)
6010 (backward-char 1)
6011 (throw 'match t))))
6012 nil))))
6014 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6015 "Fontify string S like in Org-mode."
6016 (with-temp-buffer
6017 (insert s)
6018 (let ((org-odd-levels-only odd-levels))
6019 (org-mode)
6020 (font-lock-fontify-buffer)
6021 (buffer-string))))
6023 (defvar org-m nil)
6024 (defvar org-l nil)
6025 (defvar org-f nil)
6026 (defun org-get-level-face (n)
6027 "Get the right face for match N in font-lock matching of headlines."
6028 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6029 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6030 (if org-cycle-level-faces
6031 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6032 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6033 (cond
6034 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6035 ((eq n 2) org-f)
6036 (t (if org-level-color-stars-only nil org-f))))
6039 (defun org-get-todo-face (kwd)
6040 "Get the right face for a TODO keyword KWD.
6041 If KWD is a number, get the corresponding match group."
6042 (if (numberp kwd) (setq kwd (match-string kwd)))
6043 (or (org-face-from-face-or-color
6044 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6045 (and (member kwd org-done-keywords) 'org-done)
6046 'org-todo))
6048 (defun org-face-from-face-or-color (context inherit face-or-color)
6049 "Create a face list that inherits INHERIT, but sets the foreground color.
6050 When FACE-OR-COLOR is not a string, just return it."
6051 (if (stringp face-or-color)
6052 (list :inherit inherit
6053 (cdr (assoc context org-faces-easy-properties))
6054 face-or-color)
6055 face-or-color))
6057 (defun org-font-lock-add-tag-faces (limit)
6058 "Add the special tag faces."
6059 (when (and org-tag-faces org-tags-special-faces-re)
6060 (while (re-search-forward org-tags-special-faces-re limit t)
6061 (add-text-properties (match-beginning 1) (match-end 1)
6062 (list 'face (org-get-tag-face 1)
6063 'font-lock-fontified t))
6064 (backward-char 1))))
6066 (defun org-font-lock-add-priority-faces (limit)
6067 "Add the special priority faces."
6068 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6069 (when (save-match-data (org-at-heading-p))
6070 (add-text-properties
6071 (match-beginning 0) (match-end 0)
6072 (list 'face (or (org-face-from-face-or-color
6073 'priority 'org-special-keyword
6074 (cdr (assoc (char-after (match-beginning 1))
6075 org-priority-faces)))
6076 'org-special-keyword)
6077 'font-lock-fontified t)))))
6079 (defun org-get-tag-face (kwd)
6080 "Get the right face for a TODO keyword KWD.
6081 If KWD is a number, get the corresponding match group."
6082 (if (numberp kwd) (setq kwd (match-string kwd)))
6083 (or (org-face-from-face-or-color
6084 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6085 'org-tag))
6087 (defun org-unfontify-region (beg end &optional maybe_loudly)
6088 "Remove fontification and activation overlays from links."
6089 (font-lock-default-unfontify-region beg end)
6090 (let* ((buffer-undo-list t)
6091 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6092 (inhibit-modification-hooks t)
6093 deactivate-mark buffer-file-name buffer-file-truename)
6094 (org-decompose-region beg end)
6095 (remove-text-properties beg end
6096 '(mouse-face t keymap t org-linked-text t
6097 invisible t intangible t
6098 org-no-flyspell t org-emphasis t))
6099 (org-remove-font-lock-display-properties beg end)))
6101 (defconst org-script-display '(((raise -0.3) (height 0.7))
6102 ((raise 0.3) (height 0.7))
6103 ((raise -0.5))
6104 ((raise 0.5)))
6105 "Display properties for showing superscripts and subscripts.")
6107 (defun org-remove-font-lock-display-properties (beg end)
6108 "Remove specific display properties that have been added by font lock.
6109 The will remove the raise properties that are used to show superscripts
6110 and subscripts."
6111 (let (next prop)
6112 (while (< beg end)
6113 (setq next (next-single-property-change beg 'display nil end)
6114 prop (get-text-property beg 'display))
6115 (if (member prop org-script-display)
6116 (put-text-property beg next 'display nil))
6117 (setq beg next))))
6119 (defun org-raise-scripts (limit)
6120 "Add raise properties to sub/superscripts."
6121 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6122 (if (re-search-forward
6123 (if (eq org-use-sub-superscripts t)
6124 org-match-substring-regexp
6125 org-match-substring-with-braces-regexp)
6126 limit t)
6127 (let* ((pos (point)) table-p comment-p
6128 (mpos (match-beginning 3))
6129 (emph-p (get-text-property mpos 'org-emphasis))
6130 (link-p (get-text-property mpos 'mouse-face))
6131 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6132 (goto-char (point-at-bol))
6133 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6134 comment-p (org-looking-at-p "[ \t]*#"))
6135 (goto-char pos)
6136 ;; FIXME: Should we go back one character here, for a_b^c
6137 ;; (goto-char (1- pos)) ;????????????????????
6138 (if (or comment-p emph-p link-p keyw-p)
6140 (put-text-property (match-beginning 3) (match-end 0)
6141 'display
6142 (if (equal (char-after (match-beginning 2)) ?^)
6143 (nth (if table-p 3 1) org-script-display)
6144 (nth (if table-p 2 0) org-script-display)))
6145 (add-text-properties (match-beginning 2) (match-end 2)
6146 (list 'invisible t
6147 'org-dwidth t 'org-dwidth-n 1))
6148 (if (and (eq (char-after (match-beginning 3)) ?{)
6149 (eq (char-before (match-end 3)) ?}))
6150 (progn
6151 (add-text-properties
6152 (match-beginning 3) (1+ (match-beginning 3))
6153 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6154 (add-text-properties
6155 (1- (match-end 3)) (match-end 3)
6156 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6157 t)))))
6159 ;;;; Visibility cycling, including org-goto and indirect buffer
6161 ;;; Cycling
6163 (defvar org-cycle-global-status nil)
6164 (make-variable-buffer-local 'org-cycle-global-status)
6165 (defvar org-cycle-subtree-status nil)
6166 (make-variable-buffer-local 'org-cycle-subtree-status)
6168 (defvar org-inlinetask-min-level)
6170 ;;;###autoload
6171 (defun org-cycle (&optional arg)
6172 "TAB-action and visibility cycling for Org-mode.
6174 This is the command invoked in Org-mode by the TAB key. Its main purpose
6175 is outline visibility cycling, but it also invokes other actions
6176 in special contexts.
6178 - When this function is called with a prefix argument, rotate the entire
6179 buffer through 3 states (global cycling)
6180 1. OVERVIEW: Show only top-level headlines.
6181 2. CONTENTS: Show all headlines of all levels, but no body text.
6182 3. SHOW ALL: Show everything.
6183 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6184 determined by the variable `org-startup-folded', and by any VISIBILITY
6185 properties in the buffer.
6186 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6187 including any drawers.
6189 - When inside a table, re-align the table and move to the next field.
6191 - When point is at the beginning of a headline, rotate the subtree started
6192 by this line through 3 different states (local cycling)
6193 1. FOLDED: Only the main headline is shown.
6194 2. CHILDREN: The main headline and the direct children are shown.
6195 From this state, you can move to one of the children
6196 and zoom in further.
6197 3. SUBTREE: Show the entire subtree, including body text.
6198 If there is no subtree, switch directly from CHILDREN to FOLDED.
6200 - When point is at the beginning of an empty headline and the variable
6201 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6202 of the headline by demoting and promoting it to likely levels. This
6203 speeds up creation document structure by pressing TAB once or several
6204 times right after creating a new headline.
6206 - When there is a numeric prefix, go up to a heading with level ARG, do
6207 a `show-subtree' and return to the previous cursor position. If ARG
6208 is negative, go up that many levels.
6210 - When point is not at the beginning of a headline, execute the global
6211 binding for TAB, which is re-indenting the line. See the option
6212 `org-cycle-emulate-tab' for details.
6214 - Special case: if point is at the beginning of the buffer and there is
6215 no headline in line 1, this function will act as if called with prefix arg
6216 (C-u TAB, same as S-TAB) also when called without prefix arg.
6217 But only if also the variable `org-cycle-global-at-bob' is t."
6218 (interactive "P")
6219 (org-load-modules-maybe)
6220 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6221 (and org-cycle-level-after-item/entry-creation
6222 (or (org-cycle-level)
6223 (org-cycle-item-indentation))))
6224 (let* ((limit-level
6225 (or org-cycle-max-level
6226 (and (boundp 'org-inlinetask-min-level)
6227 org-inlinetask-min-level
6228 (1- org-inlinetask-min-level))))
6229 (nstars (and limit-level
6230 (if org-odd-levels-only
6231 (and limit-level (1- (* limit-level 2)))
6232 limit-level)))
6233 (org-outline-regexp
6234 (if (not (derived-mode-p 'org-mode))
6235 outline-regexp
6236 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6237 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6238 (not (looking-at org-outline-regexp))))
6239 (org-cycle-hook
6240 (if bob-special
6241 (delq 'org-optimize-window-after-visibility-change
6242 (copy-sequence org-cycle-hook))
6243 org-cycle-hook))
6244 (pos (point)))
6246 (if (or bob-special (equal arg '(4)))
6247 ;; special case: use global cycling
6248 (setq arg t))
6250 (cond
6252 ((equal arg '(16))
6253 (setq last-command 'dummy)
6254 (org-set-startup-visibility)
6255 (message "Startup visibility, plus VISIBILITY properties"))
6257 ((equal arg '(64))
6258 (show-all)
6259 (message "Entire buffer visible, including drawers"))
6261 ;; Table: enter it or move to the next field.
6262 ((org-at-table-p 'any)
6263 (if (org-at-table.el-p)
6264 (message "Use C-c ' to edit table.el tables")
6265 (if arg (org-table-edit-field t)
6266 (org-table-justify-field-maybe)
6267 (call-interactively 'org-table-next-field))))
6269 ((run-hook-with-args-until-success
6270 'org-tab-after-check-for-table-hook))
6272 ;; Global cycling: delegate to `org-cycle-internal-global'.
6273 ((eq arg t) (org-cycle-internal-global))
6275 ;; Drawers: delegate to `org-flag-drawer'.
6276 ((and org-drawers org-drawer-regexp
6277 (save-excursion
6278 (beginning-of-line 1)
6279 (looking-at org-drawer-regexp)))
6280 (org-flag-drawer ; toggle block visibility
6281 (not (get-char-property (match-end 0) 'invisible))))
6283 ;; Show-subtree, ARG levels up from here.
6284 ((integerp arg)
6285 (save-excursion
6286 (org-back-to-heading)
6287 (outline-up-heading (if (< arg 0) (- arg)
6288 (- (funcall outline-level) arg)))
6289 (org-show-subtree)))
6291 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6292 ((and (featurep 'org-inlinetask)
6293 (org-inlinetask-at-task-p)
6294 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6295 (org-inlinetask-toggle-visibility))
6297 ((org-try-cdlatex-tab))
6299 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6300 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6301 (save-excursion (beginning-of-line 1)
6302 (looking-at org-outline-regexp)))
6303 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6304 (org-cycle-internal-local))
6306 ;; From there: TAB emulation and template completion.
6307 (buffer-read-only (org-back-to-heading))
6309 ((run-hook-with-args-until-success
6310 'org-tab-after-check-for-cycling-hook))
6312 ((org-try-structure-completion))
6314 ((run-hook-with-args-until-success
6315 'org-tab-before-tab-emulation-hook))
6317 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6318 (or (not (bolp))
6319 (not (looking-at org-outline-regexp))))
6320 (call-interactively (global-key-binding "\t")))
6322 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6323 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6324 (or (and (eq org-cycle-emulate-tab 'white)
6325 (= (match-end 0) (point-at-eol)))
6326 (and (eq org-cycle-emulate-tab 'whitestart)
6327 (>= (match-end 0) pos))))
6329 (eq org-cycle-emulate-tab t))
6330 (call-interactively (global-key-binding "\t")))
6332 (t (save-excursion
6333 (org-back-to-heading)
6334 (org-cycle)))))))
6336 (defun org-cycle-internal-global ()
6337 "Do the global cycling action."
6338 ;; Hack to avoid display of messages for .org attachments in Gnus
6339 (let ((ga (string-match "\\*fontification" (buffer-name))))
6340 (cond
6341 ((and (eq last-command this-command)
6342 (eq org-cycle-global-status 'overview))
6343 ;; We just created the overview - now do table of contents
6344 ;; This can be slow in very large buffers, so indicate action
6345 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6346 (unless ga (message "CONTENTS..."))
6347 (org-content)
6348 (unless ga (message "CONTENTS...done"))
6349 (setq org-cycle-global-status 'contents)
6350 (run-hook-with-args 'org-cycle-hook 'contents))
6352 ((and (eq last-command this-command)
6353 (eq org-cycle-global-status 'contents))
6354 ;; We just showed the table of contents - now show everything
6355 (run-hook-with-args 'org-pre-cycle-hook 'all)
6356 (show-all)
6357 (unless ga (message "SHOW ALL"))
6358 (setq org-cycle-global-status 'all)
6359 (run-hook-with-args 'org-cycle-hook 'all))
6362 ;; Default action: go to overview
6363 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6364 (org-overview)
6365 (unless ga (message "OVERVIEW"))
6366 (setq org-cycle-global-status 'overview)
6367 (run-hook-with-args 'org-cycle-hook 'overview)))))
6369 (defun org-cycle-internal-local ()
6370 "Do the local cycling action."
6371 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6372 ;; First, determine end of headline (EOH), end of subtree or item
6373 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6374 (save-excursion
6375 (if (org-at-item-p)
6376 (progn
6377 (beginning-of-line)
6378 (setq struct (org-list-struct))
6379 (setq eoh (point-at-eol))
6380 (setq eos (org-list-get-item-end-before-blank (point) struct))
6381 (setq has-children (org-list-has-child-p (point) struct)))
6382 (org-back-to-heading)
6383 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6384 (setq eos (save-excursion
6385 (org-end-of-subtree t)
6386 (unless (eobp)
6387 (skip-chars-forward " \t\n"))
6388 (if (eobp) (point) (1- (point)))))
6389 (setq has-children
6390 (or (save-excursion
6391 (let ((level (funcall outline-level)))
6392 (outline-next-heading)
6393 (and (org-at-heading-p t)
6394 (> (funcall outline-level) level))))
6395 (save-excursion
6396 (org-list-search-forward (org-item-beginning-re) eos t)))))
6397 ;; Determine end invisible part of buffer (EOL)
6398 (beginning-of-line 2)
6399 ;; XEmacs doesn't have `next-single-char-property-change'
6400 (if (featurep 'xemacs)
6401 (while (and (not (eobp)) ;; this is like `next-line'
6402 (get-char-property (1- (point)) 'invisible))
6403 (beginning-of-line 2))
6404 (while (and (not (eobp)) ;; this is like `next-line'
6405 (get-char-property (1- (point)) 'invisible))
6406 (goto-char (next-single-char-property-change (point) 'invisible))
6407 (and (eolp) (beginning-of-line 2))))
6408 (setq eol (point)))
6409 ;; Find out what to do next and set `this-command'
6410 (cond
6411 ((= eos eoh)
6412 ;; Nothing is hidden behind this heading
6413 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6414 (message "EMPTY ENTRY")
6415 (setq org-cycle-subtree-status nil)
6416 (save-excursion
6417 (goto-char eos)
6418 (outline-next-heading)
6419 (if (outline-invisible-p) (org-flag-heading nil))))
6420 ((and (or (>= eol eos)
6421 (not (string-match "\\S-" (buffer-substring eol eos))))
6422 (or has-children
6423 (not (setq children-skipped
6424 org-cycle-skip-children-state-if-no-children))))
6425 ;; Entire subtree is hidden in one line: children view
6426 (run-hook-with-args 'org-pre-cycle-hook 'children)
6427 (if (org-at-item-p)
6428 (org-list-set-item-visibility (point-at-bol) struct 'children)
6429 (org-show-entry)
6430 (org-with-limited-levels (show-children))
6431 ;; FIXME: This slows down the func way too much.
6432 ;; How keep drawers hidden in subtree anyway?
6433 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6434 ;; (org-cycle-hide-drawers 'subtree))
6436 ;; Fold every list in subtree to top-level items.
6437 (when (eq org-cycle-include-plain-lists 'integrate)
6438 (save-excursion
6439 (org-back-to-heading)
6440 (while (org-list-search-forward (org-item-beginning-re) eos t)
6441 (beginning-of-line 1)
6442 (let* ((struct (org-list-struct))
6443 (prevs (org-list-prevs-alist struct))
6444 (end (org-list-get-bottom-point struct)))
6445 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6446 (org-list-get-all-items (point) struct prevs))
6447 (goto-char end))))))
6448 (message "CHILDREN")
6449 (save-excursion
6450 (goto-char eos)
6451 (outline-next-heading)
6452 (if (outline-invisible-p) (org-flag-heading nil)))
6453 (setq org-cycle-subtree-status 'children)
6454 (run-hook-with-args 'org-cycle-hook 'children))
6455 ((or children-skipped
6456 (and (eq last-command this-command)
6457 (eq org-cycle-subtree-status 'children)))
6458 ;; We just showed the children, or no children are there,
6459 ;; now show everything.
6460 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6461 (outline-flag-region eoh eos nil)
6462 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6463 (setq org-cycle-subtree-status 'subtree)
6464 (run-hook-with-args 'org-cycle-hook 'subtree))
6466 ;; Default action: hide the subtree.
6467 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6468 (outline-flag-region eoh eos t)
6469 (message "FOLDED")
6470 (setq org-cycle-subtree-status 'folded)
6471 (run-hook-with-args 'org-cycle-hook 'folded)))))
6473 ;;;###autoload
6474 (defun org-global-cycle (&optional arg)
6475 "Cycle the global visibility. For details see `org-cycle'.
6476 With \\[universal-argument] prefix arg, switch to startup visibility.
6477 With a numeric prefix, show all headlines up to that level."
6478 (interactive "P")
6479 (let ((org-cycle-include-plain-lists
6480 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6481 (cond
6482 ((integerp arg)
6483 (show-all)
6484 (hide-sublevels arg)
6485 (setq org-cycle-global-status 'contents))
6486 ((equal arg '(4))
6487 (org-set-startup-visibility)
6488 (message "Startup visibility, plus VISIBILITY properties."))
6490 (org-cycle '(4))))))
6492 (defun org-set-startup-visibility ()
6493 "Set the visibility required by startup options and properties."
6494 (cond
6495 ((eq org-startup-folded t)
6496 (org-cycle '(4)))
6497 ((eq org-startup-folded 'content)
6498 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6499 (org-cycle '(4)) (org-cycle '(4)))))
6500 (unless (eq org-startup-folded 'showeverything)
6501 (if org-hide-block-startup (org-hide-block-all))
6502 (org-set-visibility-according-to-property 'no-cleanup)
6503 (org-cycle-hide-archived-subtrees 'all)
6504 (org-cycle-hide-drawers 'all)
6505 (org-cycle-show-empty-lines t)))
6507 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6508 "Switch subtree visibilities according to :VISIBILITY: property."
6509 (interactive)
6510 (let (org-show-entry-below state)
6511 (save-excursion
6512 (goto-char (point-min))
6513 (while (re-search-forward
6514 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6515 nil t)
6516 (setq state (match-string 1))
6517 (save-excursion
6518 (org-back-to-heading t)
6519 (hide-subtree)
6520 (org-reveal)
6521 (cond
6522 ((equal state '("fold" "folded"))
6523 (hide-subtree))
6524 ((equal state "children")
6525 (org-show-hidden-entry)
6526 (show-children))
6527 ((equal state "content")
6528 (save-excursion
6529 (save-restriction
6530 (org-narrow-to-subtree)
6531 (org-content))))
6532 ((member state '("all" "showall"))
6533 (show-subtree)))))
6534 (unless no-cleanup
6535 (org-cycle-hide-archived-subtrees 'all)
6536 (org-cycle-hide-drawers 'all)
6537 (org-cycle-show-empty-lines 'all)))))
6539 ;; This function uses outline-regexp instead of the more fundamental
6540 ;; org-outline-regexp so that org-cycle-global works outside of Org
6541 ;; buffers, where outline-regexp is needed.
6542 (defun org-overview ()
6543 "Switch to overview mode, showing only top-level headlines.
6544 Really, this shows all headlines with level equal or greater than the level
6545 of the first headline in the buffer. This is important, because if the
6546 first headline is not level one, then (hide-sublevels 1) gives confusing
6547 results."
6548 (interactive)
6549 (let ((level (save-excursion
6550 (goto-char (point-min))
6551 (if (re-search-forward (concat "^" outline-regexp) nil t)
6552 (progn
6553 (goto-char (match-beginning 0))
6554 (funcall outline-level))))))
6555 (and level (hide-sublevels level))))
6557 (defun org-content (&optional arg)
6558 "Show all headlines in the buffer, like a table of contents.
6559 With numerical argument N, show content up to level N."
6560 (interactive "P")
6561 (save-excursion
6562 ;; Visit all headings and show their offspring
6563 (and (integerp arg) (org-overview))
6564 (goto-char (point-max))
6565 (catch 'exit
6566 (while (and (progn (condition-case nil
6567 (outline-previous-visible-heading 1)
6568 (error (goto-char (point-min))))
6570 (looking-at org-outline-regexp))
6571 (if (integerp arg)
6572 (show-children (1- arg))
6573 (show-branches))
6574 (if (bobp) (throw 'exit nil))))))
6577 (defun org-optimize-window-after-visibility-change (state)
6578 "Adjust the window after a change in outline visibility.
6579 This function is the default value of the hook `org-cycle-hook'."
6580 (when (get-buffer-window (current-buffer))
6581 (cond
6582 ((eq state 'content) nil)
6583 ((eq state 'all) nil)
6584 ((eq state 'folded) nil)
6585 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6586 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6588 (defun org-remove-empty-overlays-at (pos)
6589 "Remove outline overlays that do not contain non-white stuff."
6590 (mapc
6591 (lambda (o)
6592 (and (eq 'outline (overlay-get o 'invisible))
6593 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6594 (overlay-end o))))
6595 (delete-overlay o)))
6596 (overlays-at pos)))
6598 (defun org-clean-visibility-after-subtree-move ()
6599 "Fix visibility issues after moving a subtree."
6600 ;; First, find a reasonable region to look at:
6601 ;; Start two siblings above, end three below
6602 (let* ((beg (save-excursion
6603 (and (org-get-last-sibling)
6604 (org-get-last-sibling))
6605 (point)))
6606 (end (save-excursion
6607 (and (org-get-next-sibling)
6608 (org-get-next-sibling)
6609 (org-get-next-sibling))
6610 (if (org-at-heading-p)
6611 (point-at-eol)
6612 (point))))
6613 (level (looking-at "\\*+"))
6614 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6615 (save-excursion
6616 (save-restriction
6617 (narrow-to-region beg end)
6618 (when re
6619 ;; Properly fold already folded siblings
6620 (goto-char (point-min))
6621 (while (re-search-forward re nil t)
6622 (if (and (not (outline-invisible-p))
6623 (save-excursion
6624 (goto-char (point-at-eol)) (outline-invisible-p)))
6625 (hide-entry))))
6626 (org-cycle-show-empty-lines 'overview)
6627 (org-cycle-hide-drawers 'overview)))))
6629 (defun org-cycle-show-empty-lines (state)
6630 "Show empty lines above all visible headlines.
6631 The region to be covered depends on STATE when called through
6632 `org-cycle-hook'. Lisp program can use t for STATE to get the
6633 entire buffer covered. Note that an empty line is only shown if there
6634 are at least `org-cycle-separator-lines' empty lines before the headline."
6635 (when (not (= org-cycle-separator-lines 0))
6636 (save-excursion
6637 (let* ((n (abs org-cycle-separator-lines))
6638 (re (cond
6639 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6640 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6641 (t (let ((ns (number-to-string (- n 2))))
6642 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6643 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6644 beg end b e)
6645 (cond
6646 ((memq state '(overview contents t))
6647 (setq beg (point-min) end (point-max)))
6648 ((memq state '(children folded))
6649 (setq beg (point) end (progn (org-end-of-subtree t t)
6650 (beginning-of-line 2)
6651 (point)))))
6652 (when beg
6653 (goto-char beg)
6654 (while (re-search-forward re end t)
6655 (unless (get-char-property (match-end 1) 'invisible)
6656 (setq e (match-end 1))
6657 (if (< org-cycle-separator-lines 0)
6658 (setq b (save-excursion
6659 (goto-char (match-beginning 0))
6660 (org-back-over-empty-lines)
6661 (if (save-excursion
6662 (goto-char (max (point-min) (1- (point))))
6663 (org-at-heading-p))
6664 (1- (point))
6665 (point))))
6666 (setq b (match-beginning 1)))
6667 (outline-flag-region b e nil)))))))
6668 ;; Never hide empty lines at the end of the file.
6669 (save-excursion
6670 (goto-char (point-max))
6671 (outline-previous-heading)
6672 (outline-end-of-heading)
6673 (if (and (looking-at "[ \t\n]+")
6674 (= (match-end 0) (point-max)))
6675 (outline-flag-region (point) (match-end 0) nil))))
6677 (defun org-show-empty-lines-in-parent ()
6678 "Move to the parent and re-show empty lines before visible headlines."
6679 (save-excursion
6680 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6681 (org-cycle-show-empty-lines context))))
6683 (defun org-files-list ()
6684 "Return `org-agenda-files' list, plus all open org-mode files.
6685 This is useful for operations that need to scan all of a user's
6686 open and agenda-wise Org files."
6687 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6688 (dolist (buf (buffer-list))
6689 (with-current-buffer buf
6690 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6691 (let ((file (expand-file-name (buffer-file-name))))
6692 (unless (member file files)
6693 (push file files))))))
6694 files))
6696 (defsubst org-entry-beginning-position ()
6697 "Return the beginning position of the current entry."
6698 (save-excursion (outline-back-to-heading t) (point)))
6700 (defsubst org-entry-end-position ()
6701 "Return the end position of the current entry."
6702 (save-excursion (outline-next-heading) (point)))
6704 (defun org-cycle-hide-drawers (state)
6705 "Re-hide all drawers after a visibility state change."
6706 (when (and (derived-mode-p 'org-mode)
6707 (not (memq state '(overview folded contents))))
6708 (save-excursion
6709 (let* ((globalp (memq state '(contents all)))
6710 (beg (if globalp (point-min) (point)))
6711 (end (if globalp (point-max)
6712 (if (eq state 'children)
6713 (save-excursion (outline-next-heading) (point))
6714 (org-end-of-subtree t)))))
6715 (goto-char beg)
6716 (while (re-search-forward org-drawer-regexp end t)
6717 (org-flag-drawer t))))))
6719 (defun org-flag-drawer (flag)
6720 "When FLAG is non-nil, hide the drawer we are within.
6721 Otherwise make it visible."
6722 (save-excursion
6723 (beginning-of-line 1)
6724 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6725 (let ((b (match-end 0)))
6726 (if (re-search-forward
6727 "^[ \t]*:END:"
6728 (save-excursion (outline-next-heading) (point)) t)
6729 (outline-flag-region b (point-at-eol) flag)
6730 (error ":END: line missing at position %s" b))))))
6732 (defun org-subtree-end-visible-p ()
6733 "Is the end of the current subtree visible?"
6734 (pos-visible-in-window-p
6735 (save-excursion (org-end-of-subtree t) (point))))
6737 (defun org-first-headline-recenter (&optional N)
6738 "Move cursor to the first headline and recenter the headline.
6739 Optional argument N means put the headline into the Nth line of the window."
6740 (goto-char (point-min))
6741 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6742 (beginning-of-line)
6743 (recenter (prefix-numeric-value N))))
6745 ;;; Saving and restoring visibility
6747 (defun org-outline-overlay-data (&optional use-markers)
6748 "Return a list of the locations of all outline overlays.
6749 These are overlays with the `invisible' property value `outline'.
6750 The return value is a list of cons cells, with start and stop
6751 positions for each overlay.
6752 If USE-MARKERS is set, return the positions as markers."
6753 (let (beg end)
6754 (save-excursion
6755 (save-restriction
6756 (widen)
6757 (delq nil
6758 (mapcar (lambda (o)
6759 (when (eq (overlay-get o 'invisible) 'outline)
6760 (setq beg (overlay-start o)
6761 end (overlay-end o))
6762 (and beg end (> end beg)
6763 (if use-markers
6764 (cons (move-marker (make-marker) beg)
6765 (move-marker (make-marker) end))
6766 (cons beg end)))))
6767 (overlays-in (point-min) (point-max))))))))
6769 (defun org-set-outline-overlay-data (data)
6770 "Create visibility overlays for all positions in DATA.
6771 DATA should have been made by `org-outline-overlay-data'."
6772 (let (o)
6773 (save-excursion
6774 (save-restriction
6775 (widen)
6776 (show-all)
6777 (mapc (lambda (c)
6778 (outline-flag-region (car c) (cdr c) t))
6779 data)))))
6781 ;;; Folding of blocks
6783 (defvar org-hide-block-overlays nil
6784 "Overlays hiding blocks.")
6785 (make-variable-buffer-local 'org-hide-block-overlays)
6787 (defun org-block-map (function &optional start end)
6788 "Call FUNCTION at the head of all source blocks in the current buffer.
6789 Optional arguments START and END can be used to limit the range."
6790 (let ((start (or start (point-min)))
6791 (end (or end (point-max))))
6792 (save-excursion
6793 (goto-char start)
6794 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6795 (save-excursion
6796 (save-match-data
6797 (goto-char (match-beginning 0))
6798 (funcall function)))))))
6800 (defun org-hide-block-toggle-all ()
6801 "Toggle the visibility of all blocks in the current buffer."
6802 (org-block-map #'org-hide-block-toggle))
6804 (defun org-hide-block-all ()
6805 "Fold all blocks in the current buffer."
6806 (interactive)
6807 (org-show-block-all)
6808 (org-block-map #'org-hide-block-toggle-maybe))
6810 (defun org-show-block-all ()
6811 "Unfold all blocks in the current buffer."
6812 (interactive)
6813 (mapc 'delete-overlay org-hide-block-overlays)
6814 (setq org-hide-block-overlays nil))
6816 (defun org-hide-block-toggle-maybe ()
6817 "Toggle visibility of block at point."
6818 (interactive)
6819 (let ((case-fold-search t))
6820 (if (save-excursion
6821 (beginning-of-line 1)
6822 (looking-at org-block-regexp))
6823 (progn (org-hide-block-toggle)
6824 t) ;; to signal that we took action
6825 nil))) ;; to signal that we did not
6827 (defun org-hide-block-toggle (&optional force)
6828 "Toggle the visibility of the current block."
6829 (interactive)
6830 (save-excursion
6831 (beginning-of-line)
6832 (if (re-search-forward org-block-regexp nil t)
6833 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6834 (end (match-end 0)) ;; end of entire body
6836 (if (memq t (mapcar (lambda (overlay)
6837 (eq (overlay-get overlay 'invisible)
6838 'org-hide-block))
6839 (overlays-at start)))
6840 (if (or (not force) (eq force 'off))
6841 (mapc (lambda (ov)
6842 (when (member ov org-hide-block-overlays)
6843 (setq org-hide-block-overlays
6844 (delq ov org-hide-block-overlays)))
6845 (when (eq (overlay-get ov 'invisible)
6846 'org-hide-block)
6847 (delete-overlay ov)))
6848 (overlays-at start)))
6849 (setq ov (make-overlay start end))
6850 (overlay-put ov 'invisible 'org-hide-block)
6851 ;; make the block accessible to isearch
6852 (overlay-put
6853 ov 'isearch-open-invisible
6854 (lambda (ov)
6855 (when (member ov org-hide-block-overlays)
6856 (setq org-hide-block-overlays
6857 (delq ov org-hide-block-overlays)))
6858 (when (eq (overlay-get ov 'invisible)
6859 'org-hide-block)
6860 (delete-overlay ov))))
6861 (push ov org-hide-block-overlays)))
6862 (error "Not looking at a source block"))))
6864 ;; org-tab-after-check-for-cycling-hook
6865 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6866 ;; Remove overlays when changing major mode
6867 (add-hook 'org-mode-hook
6868 (lambda () (org-add-hook 'change-major-mode-hook
6869 'org-show-block-all 'append 'local)))
6871 ;;; Org-goto
6873 (defvar org-goto-window-configuration nil)
6874 (defvar org-goto-marker nil)
6875 (defvar org-goto-map
6876 (let ((map (make-sparse-keymap)))
6877 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6878 (while (setq cmd (pop cmds))
6879 (substitute-key-definition cmd cmd map global-map)))
6880 (suppress-keymap map)
6881 (org-defkey map "\C-m" 'org-goto-ret)
6882 (org-defkey map [(return)] 'org-goto-ret)
6883 (org-defkey map [(left)] 'org-goto-left)
6884 (org-defkey map [(right)] 'org-goto-right)
6885 (org-defkey map [(control ?g)] 'org-goto-quit)
6886 (org-defkey map "\C-i" 'org-cycle)
6887 (org-defkey map [(tab)] 'org-cycle)
6888 (org-defkey map [(down)] 'outline-next-visible-heading)
6889 (org-defkey map [(up)] 'outline-previous-visible-heading)
6890 (if org-goto-auto-isearch
6891 (if (fboundp 'define-key-after)
6892 (define-key-after map [t] 'org-goto-local-auto-isearch)
6893 nil)
6894 (org-defkey map "q" 'org-goto-quit)
6895 (org-defkey map "n" 'outline-next-visible-heading)
6896 (org-defkey map "p" 'outline-previous-visible-heading)
6897 (org-defkey map "f" 'outline-forward-same-level)
6898 (org-defkey map "b" 'outline-backward-same-level)
6899 (org-defkey map "u" 'outline-up-heading))
6900 (org-defkey map "/" 'org-occur)
6901 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6902 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6903 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6904 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6905 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6906 map))
6908 (defconst org-goto-help
6909 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6910 RET=jump to location [Q]uit and return to previous location
6911 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6913 (defvar org-goto-start-pos) ; dynamically scoped parameter
6915 ;; FIXME: Docstring does not mention both interfaces
6916 (defun org-goto (&optional alternative-interface)
6917 "Look up a different location in the current file, keeping current visibility.
6919 When you want look-up or go to a different location in a
6920 document, the fastest way is often to fold the entire buffer and
6921 then dive into the tree. This method has the disadvantage, that
6922 the previous location will be folded, which may not be what you
6923 want.
6925 This command works around this by showing a copy of the current
6926 buffer in an indirect buffer, in overview mode. You can dive
6927 into the tree in that copy, use org-occur and incremental search
6928 to find a location. When pressing RET or `Q', the command
6929 returns to the original buffer in which the visibility is still
6930 unchanged. After RET it will also jump to the location selected
6931 in the indirect buffer and expose the headline hierarchy above.
6933 With a prefix argument, use the alternative interface: e.g. if
6934 `org-goto-interface' is 'outline use 'outline-path-completion."
6935 (interactive "P")
6936 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6937 (org-refile-use-outline-path t)
6938 (org-refile-target-verify-function nil)
6939 (interface
6940 (if (not alternative-interface)
6941 org-goto-interface
6942 (if (eq org-goto-interface 'outline)
6943 'outline-path-completion
6944 'outline)))
6945 (org-goto-start-pos (point))
6946 (selected-point
6947 (if (eq interface 'outline)
6948 (car (org-get-location (current-buffer) org-goto-help))
6949 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6950 (org-refile-check-position pa)
6951 (nth 3 pa)))))
6952 (if selected-point
6953 (progn
6954 (org-mark-ring-push org-goto-start-pos)
6955 (goto-char selected-point)
6956 (if (or (outline-invisible-p) (org-invisible-p2))
6957 (org-show-context 'org-goto)))
6958 (message "Quit"))))
6960 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6961 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6962 (defvar org-goto-local-auto-isearch-map) ; defined below
6964 (defun org-get-location (buf help)
6965 "Let the user select a location in the Org-mode buffer BUF.
6966 This function uses a recursive edit. It returns the selected position
6967 or nil."
6968 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6969 (isearch-hide-immediately nil)
6970 (isearch-search-fun-function
6971 (lambda () 'org-goto-local-search-headings))
6972 (org-goto-selected-point org-goto-exit-command)
6973 (pop-up-frames nil)
6974 (special-display-buffer-names nil)
6975 (special-display-regexps nil)
6976 (special-display-function nil))
6977 (save-excursion
6978 (save-window-excursion
6979 (delete-other-windows)
6980 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6981 (org-pop-to-buffer-same-window
6982 (condition-case nil
6983 (make-indirect-buffer (current-buffer) "*org-goto*")
6984 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6985 (with-output-to-temp-buffer "*Help*"
6986 (princ help))
6987 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6988 (setq buffer-read-only nil)
6989 (let ((org-startup-truncated t)
6990 (org-startup-folded nil)
6991 (org-startup-align-all-tables nil))
6992 (org-mode)
6993 (org-overview))
6994 (setq buffer-read-only t)
6995 (if (and (boundp 'org-goto-start-pos)
6996 (integer-or-marker-p org-goto-start-pos))
6997 (let ((org-show-hierarchy-above t)
6998 (org-show-siblings t)
6999 (org-show-following-heading t))
7000 (goto-char org-goto-start-pos)
7001 (and (outline-invisible-p) (org-show-context)))
7002 (goto-char (point-min)))
7003 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7004 (message "Select location and press RET")
7005 (use-local-map org-goto-map)
7006 (recursive-edit)
7008 (kill-buffer "*org-goto*")
7009 (cons org-goto-selected-point org-goto-exit-command)))
7011 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7012 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7013 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7014 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7016 (defun org-goto-local-search-headings (string bound noerror)
7017 "Search and make sure that any matches are in headlines."
7018 (catch 'return
7019 (while (if isearch-forward
7020 (search-forward string bound noerror)
7021 (search-backward string bound noerror))
7022 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7023 (and (member :headline context)
7024 (not (member :tags context))))
7025 (throw 'return (point))))))
7027 (defun org-goto-local-auto-isearch ()
7028 "Start isearch."
7029 (interactive)
7030 (goto-char (point-min))
7031 (let ((keys (this-command-keys)))
7032 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7033 (isearch-mode t)
7034 (isearch-process-search-char (string-to-char keys)))))
7036 (defun org-goto-ret (&optional arg)
7037 "Finish `org-goto' by going to the new location."
7038 (interactive "P")
7039 (setq org-goto-selected-point (point)
7040 org-goto-exit-command 'return)
7041 (throw 'exit nil))
7043 (defun org-goto-left ()
7044 "Finish `org-goto' by going to the new location."
7045 (interactive)
7046 (if (org-at-heading-p)
7047 (progn
7048 (beginning-of-line 1)
7049 (setq org-goto-selected-point (point)
7050 org-goto-exit-command 'left)
7051 (throw 'exit nil))
7052 (error "Not on a heading")))
7054 (defun org-goto-right ()
7055 "Finish `org-goto' by going to the new location."
7056 (interactive)
7057 (if (org-at-heading-p)
7058 (progn
7059 (setq org-goto-selected-point (point)
7060 org-goto-exit-command 'right)
7061 (throw 'exit nil))
7062 (error "Not on a heading")))
7064 (defun org-goto-quit ()
7065 "Finish `org-goto' without cursor motion."
7066 (interactive)
7067 (setq org-goto-selected-point nil)
7068 (setq org-goto-exit-command 'quit)
7069 (throw 'exit nil))
7071 ;;; Indirect buffer display of subtrees
7073 (defvar org-indirect-dedicated-frame nil
7074 "This is the frame being used for indirect tree display.")
7075 (defvar org-last-indirect-buffer nil)
7077 (defun org-tree-to-indirect-buffer (&optional arg)
7078 "Create indirect buffer and narrow it to current subtree.
7079 With a numerical prefix ARG, go up to this level and then take that tree.
7080 If ARG is negative, go up that many levels.
7082 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7083 indirect buffer previously made with this command, to avoid proliferation of
7084 indirect buffers. However, when you call the command with a \
7085 \\[universal-argument] prefix, or
7086 when `org-indirect-buffer-display' is `new-frame', the last buffer
7087 is kept so that you can work with several indirect buffers at the same time.
7088 If `org-indirect-buffer-display' is `dedicated-frame', the \
7089 \\[universal-argument] prefix also
7090 requests that a new frame be made for the new buffer, so that the dedicated
7091 frame is not changed."
7092 (interactive "P")
7093 (let ((cbuf (current-buffer))
7094 (cwin (selected-window))
7095 (pos (point))
7096 beg end level heading ibuf)
7097 (save-excursion
7098 (org-back-to-heading t)
7099 (when (numberp arg)
7100 (setq level (org-outline-level))
7101 (if (< arg 0) (setq arg (+ level arg)))
7102 (while (> (setq level (org-outline-level)) arg)
7103 (org-up-heading-safe)))
7104 (setq beg (point)
7105 heading (org-get-heading))
7106 (org-end-of-subtree t t)
7107 (if (org-at-heading-p) (backward-char 1))
7108 (setq end (point)))
7109 (if (and (buffer-live-p org-last-indirect-buffer)
7110 (not (eq org-indirect-buffer-display 'new-frame))
7111 (not arg))
7112 (kill-buffer org-last-indirect-buffer))
7113 (setq ibuf (org-get-indirect-buffer cbuf)
7114 org-last-indirect-buffer ibuf)
7115 (cond
7116 ((or (eq org-indirect-buffer-display 'new-frame)
7117 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7118 (select-frame (make-frame))
7119 (delete-other-windows)
7120 (org-pop-to-buffer-same-window ibuf)
7121 (org-set-frame-title heading))
7122 ((eq org-indirect-buffer-display 'dedicated-frame)
7123 (raise-frame
7124 (select-frame (or (and org-indirect-dedicated-frame
7125 (frame-live-p org-indirect-dedicated-frame)
7126 org-indirect-dedicated-frame)
7127 (setq org-indirect-dedicated-frame (make-frame)))))
7128 (delete-other-windows)
7129 (org-pop-to-buffer-same-window ibuf)
7130 (org-set-frame-title (concat "Indirect: " heading)))
7131 ((eq org-indirect-buffer-display 'current-window)
7132 (org-pop-to-buffer-same-window ibuf))
7133 ((eq org-indirect-buffer-display 'other-window)
7134 (pop-to-buffer ibuf))
7135 (t (error "Invalid value")))
7136 (if (featurep 'xemacs)
7137 (save-excursion (org-mode) (turn-on-font-lock)))
7138 (narrow-to-region beg end)
7139 (show-all)
7140 (goto-char pos)
7141 (run-hook-with-args 'org-cycle-hook 'all)
7142 (and (window-live-p cwin) (select-window cwin))))
7144 (defun org-get-indirect-buffer (&optional buffer)
7145 (setq buffer (or buffer (current-buffer)))
7146 (let ((n 1) (base (buffer-name buffer)) bname)
7147 (while (buffer-live-p
7148 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7149 (setq n (1+ n)))
7150 (condition-case nil
7151 (make-indirect-buffer buffer bname 'clone)
7152 (error (make-indirect-buffer buffer bname)))))
7154 (defun org-set-frame-title (title)
7155 "Set the title of the current frame to the string TITLE."
7156 ;; FIXME: how to name a single frame in XEmacs???
7157 (unless (featurep 'xemacs)
7158 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7160 ;;;; Structure editing
7162 ;;; Inserting headlines
7164 (defun org-previous-line-empty-p ()
7165 (save-excursion
7166 (and (not (bobp))
7167 (or (beginning-of-line 0) t)
7168 (save-match-data
7169 (looking-at "[ \t]*$")))))
7171 (defun org-insert-heading (&optional force-heading invisible-ok)
7172 "Insert a new heading or item with same depth at point.
7173 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7174 If point is at the beginning of a headline, insert a sibling before the
7175 current headline. If point is not at the beginning, split the line,
7176 create the new headline with the text in the current line after point
7177 \(but see also the variable `org-M-RET-may-split-line').
7179 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7180 This is important for non-interactive uses of the command."
7181 (interactive "P")
7182 (if (or (= (buffer-size) 0)
7183 (and (not (save-excursion
7184 (and (ignore-errors (org-back-to-heading invisible-ok))
7185 (org-at-heading-p))))
7186 (or force-heading (not (org-in-item-p)))))
7187 (progn
7188 (insert "\n* ")
7189 (run-hooks 'org-insert-heading-hook))
7190 (when (or force-heading (not (org-insert-item)))
7191 (let* ((empty-line-p nil)
7192 (level nil)
7193 (on-heading (org-at-heading-p))
7194 (head (save-excursion
7195 (condition-case nil
7196 (progn
7197 (org-back-to-heading invisible-ok)
7198 (when (and (not on-heading)
7199 (featurep 'org-inlinetask)
7200 (integerp org-inlinetask-min-level)
7201 (>= (length (match-string 0))
7202 org-inlinetask-min-level))
7203 ;; Find a heading level before the inline task
7204 (while (and (setq level (org-up-heading-safe))
7205 (>= level org-inlinetask-min-level)))
7206 (if (org-at-heading-p)
7207 (org-back-to-heading invisible-ok)
7208 (error "This should not happen")))
7209 (setq empty-line-p (org-previous-line-empty-p))
7210 (match-string 0))
7211 (error "*"))))
7212 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7213 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7214 pos hide-previous previous-pos)
7215 (cond
7216 ((and (org-at-heading-p) (bolp)
7217 (or (bobp)
7218 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7219 ;; insert before the current line
7220 (open-line (if blank 2 1)))
7221 ((and (bolp)
7222 (not org-insert-heading-respect-content)
7223 (or (bobp)
7224 (save-excursion
7225 (backward-char 1) (not (outline-invisible-p)))))
7226 ;; insert right here
7227 nil)
7229 ;; somewhere in the line
7230 (save-excursion
7231 (setq previous-pos (point-at-bol))
7232 (end-of-line)
7233 (setq hide-previous (outline-invisible-p)))
7234 (and org-insert-heading-respect-content (org-show-subtree))
7235 (let ((split
7236 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7237 (save-excursion
7238 (let ((p (point)))
7239 (goto-char (point-at-bol))
7240 (and (looking-at org-complex-heading-regexp)
7241 (match-beginning 4)
7242 (> p (match-beginning 4)))))))
7243 tags pos)
7244 (cond
7245 (org-insert-heading-respect-content
7246 (org-end-of-subtree nil t)
7247 (when (featurep 'org-inlinetask)
7248 (while (and (not (eobp))
7249 (looking-at "\\(\\*+\\)[ \t]+")
7250 (>= (length (match-string 1))
7251 org-inlinetask-min-level))
7252 (org-end-of-subtree nil t)))
7253 (or (bolp) (newline))
7254 (or (org-previous-line-empty-p)
7255 (and blank (newline)))
7256 (open-line 1))
7257 ((org-at-heading-p)
7258 (when hide-previous
7259 (show-children)
7260 (org-show-entry))
7261 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7262 (setq tags (and (match-end 2) (match-string 2)))
7263 (and (match-end 1)
7264 (delete-region (match-beginning 1) (match-end 1)))
7265 (setq pos (point-at-bol))
7266 (or split (end-of-line 1))
7267 (delete-horizontal-space)
7268 (if (string-match "\\`\\*+\\'"
7269 (buffer-substring (point-at-bol) (point)))
7270 (insert " "))
7271 (newline (if blank 2 1))
7272 (when tags
7273 (save-excursion
7274 (goto-char pos)
7275 (end-of-line 1)
7276 (insert " " tags)
7277 (org-set-tags nil 'align))))
7279 (or split (end-of-line 1))
7280 (newline (if blank 2 1)))))))
7281 (insert head) (just-one-space)
7282 (setq pos (point))
7283 (end-of-line 1)
7284 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7285 (when (and org-insert-heading-respect-content hide-previous)
7286 (save-excursion
7287 (goto-char previous-pos)
7288 (hide-subtree)))
7289 (run-hooks 'org-insert-heading-hook)))))
7291 (defun org-get-heading (&optional no-tags no-todo)
7292 "Return the heading of the current entry, without the stars.
7293 When NO-TAGS is non-nil, don't include tags.
7294 When NO-TODO is non-nil, don't include TODO keywords."
7295 (save-excursion
7296 (org-back-to-heading t)
7297 (cond
7298 ((and no-tags no-todo)
7299 (looking-at org-complex-heading-regexp)
7300 (match-string 4))
7301 (no-tags
7302 (looking-at (concat org-outline-regexp
7303 "\\(.*?\\)"
7304 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7305 (match-string 1))
7306 (no-todo
7307 (looking-at org-todo-line-regexp)
7308 (match-string 3))
7309 (t (looking-at org-heading-regexp)
7310 (match-string 2)))))
7312 (defun org-heading-components ()
7313 "Return the components of the current heading.
7314 This is a list with the following elements:
7315 - the level as an integer
7316 - the reduced level, different if `org-odd-levels-only' is set.
7317 - the TODO keyword, or nil
7318 - the priority character, like ?A, or nil if no priority is given
7319 - the headline text itself, or the tags string if no headline text
7320 - the tags string, or nil."
7321 (save-excursion
7322 (org-back-to-heading t)
7323 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7324 (list (length (match-string 1))
7325 (org-reduced-level (length (match-string 1)))
7326 (org-match-string-no-properties 2)
7327 (and (match-end 3) (aref (match-string 3) 2))
7328 (org-match-string-no-properties 4)
7329 (org-match-string-no-properties 5)))))
7331 (defun org-get-entry ()
7332 "Get the entry text, after heading, entire subtree."
7333 (save-excursion
7334 (org-back-to-heading t)
7335 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7337 (defun org-insert-heading-after-current ()
7338 "Insert a new heading with same level as current, after current subtree."
7339 (interactive)
7340 (org-back-to-heading)
7341 (org-insert-heading)
7342 (org-move-subtree-down)
7343 (end-of-line 1))
7345 (defun org-insert-heading-respect-content ()
7346 (interactive)
7347 (let ((org-insert-heading-respect-content t))
7348 (org-insert-heading t)))
7350 (defun org-insert-todo-heading-respect-content (&optional force-state)
7351 (interactive "P")
7352 (let ((org-insert-heading-respect-content t))
7353 (org-insert-todo-heading force-state t)))
7355 (defun org-insert-todo-heading (arg &optional force-heading)
7356 "Insert a new heading with the same level and TODO state as current heading.
7357 If the heading has no TODO state, or if the state is DONE, use the first
7358 state (TODO by default). Also with prefix arg, force first state."
7359 (interactive "P")
7360 (when (or force-heading (not (org-insert-item 'checkbox)))
7361 (org-insert-heading force-heading)
7362 (save-excursion
7363 (org-back-to-heading)
7364 (outline-previous-heading)
7365 (looking-at org-todo-line-regexp))
7366 (let*
7367 ((new-mark-x
7368 (if (or arg
7369 (not (match-beginning 2))
7370 (member (match-string 2) org-done-keywords))
7371 (car org-todo-keywords-1)
7372 (match-string 2)))
7373 (new-mark
7375 (run-hook-with-args-until-success
7376 'org-todo-get-default-hook new-mark-x nil)
7377 new-mark-x)))
7378 (beginning-of-line 1)
7379 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7380 (if org-treat-insert-todo-heading-as-state-change
7381 (org-todo new-mark)
7382 (insert new-mark " "))))
7383 (when org-provide-todo-statistics
7384 (org-update-parent-todo-statistics))))
7386 (defun org-insert-subheading (arg)
7387 "Insert a new subheading and demote it.
7388 Works for outline headings and for plain lists alike."
7389 (interactive "P")
7390 (org-insert-heading arg)
7391 (cond
7392 ((org-at-heading-p) (org-do-demote))
7393 ((org-at-item-p) (org-indent-item))))
7395 (defun org-insert-todo-subheading (arg)
7396 "Insert a new subheading with TODO keyword or checkbox and demote it.
7397 Works for outline headings and for plain lists alike."
7398 (interactive "P")
7399 (org-insert-todo-heading arg)
7400 (cond
7401 ((org-at-heading-p) (org-do-demote))
7402 ((org-at-item-p) (org-indent-item))))
7404 ;;; Promotion and Demotion
7406 (defvar org-after-demote-entry-hook nil
7407 "Hook run after an entry has been demoted.
7408 The cursor will be at the beginning of the entry.
7409 When a subtree is being demoted, the hook will be called for each node.")
7411 (defvar org-after-promote-entry-hook nil
7412 "Hook run after an entry has been promoted.
7413 The cursor will be at the beginning of the entry.
7414 When a subtree is being promoted, the hook will be called for each node.")
7416 (defun org-promote-subtree ()
7417 "Promote the entire subtree.
7418 See also `org-promote'."
7419 (interactive)
7420 (save-excursion
7421 (org-with-limited-levels (org-map-tree 'org-promote)))
7422 (org-fix-position-after-promote))
7424 (defun org-demote-subtree ()
7425 "Demote the entire subtree. See `org-demote'.
7426 See also `org-promote'."
7427 (interactive)
7428 (save-excursion
7429 (org-with-limited-levels (org-map-tree 'org-demote)))
7430 (org-fix-position-after-promote))
7433 (defun org-do-promote ()
7434 "Promote the current heading higher up the tree.
7435 If the region is active in `transient-mark-mode', promote all headings
7436 in the region."
7437 (interactive)
7438 (save-excursion
7439 (if (org-region-active-p)
7440 (org-map-region 'org-promote (region-beginning) (region-end))
7441 (org-promote)))
7442 (org-fix-position-after-promote))
7444 (defun org-do-demote ()
7445 "Demote the current heading lower down the tree.
7446 If the region is active in `transient-mark-mode', demote all headings
7447 in the region."
7448 (interactive)
7449 (save-excursion
7450 (if (org-region-active-p)
7451 (org-map-region 'org-demote (region-beginning) (region-end))
7452 (org-demote)))
7453 (org-fix-position-after-promote))
7455 (defun org-fix-position-after-promote ()
7456 "Make sure that after pro/demotion cursor position is right."
7457 (let ((pos (point)))
7458 (when (save-excursion
7459 (beginning-of-line 1)
7460 (looking-at org-todo-line-regexp)
7461 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7462 (cond ((eobp) (insert " "))
7463 ((eolp) (insert " "))
7464 ((equal (char-after) ?\ ) (forward-char 1))))))
7466 (defun org-current-level ()
7467 "Return the level of the current entry, or nil if before the first headline.
7468 The level is the number of stars at the beginning of the headline."
7469 (save-excursion
7470 (org-with-limited-levels
7471 (if (ignore-errors (org-back-to-heading t))
7472 (funcall outline-level)))))
7474 (defun org-get-previous-line-level ()
7475 "Return the outline depth of the last headline before the current line.
7476 Returns 0 for the first headline in the buffer, and nil if before the
7477 first headline."
7478 (let ((current-level (org-current-level))
7479 (prev-level (when (> (line-number-at-pos) 1)
7480 (save-excursion
7481 (beginning-of-line 0)
7482 (org-current-level)))))
7483 (cond ((null current-level) nil) ; Before first headline
7484 ((null prev-level) 0) ; At first headline
7485 (prev-level))))
7487 (defun org-reduced-level (l)
7488 "Compute the effective level of a heading.
7489 This takes into account the setting of `org-odd-levels-only'."
7490 (cond
7491 ((zerop l) 0)
7492 (org-odd-levels-only (1+ (floor (/ l 2))))
7493 (t l)))
7495 (defun org-level-increment ()
7496 "Return the number of stars that will be added or removed at a
7497 time to headlines when structure editing, based on the value of
7498 `org-odd-levels-only'."
7499 (if org-odd-levels-only 2 1))
7501 (defun org-get-valid-level (level &optional change)
7502 "Rectify a level change under the influence of `org-odd-levels-only'
7503 LEVEL is a current level, CHANGE is by how much the level should be
7504 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7505 even level numbers will become the next higher odd number."
7506 (if org-odd-levels-only
7507 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7508 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7509 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7510 (max 1 (+ level (or change 0)))))
7512 (if (boundp 'define-obsolete-function-alias)
7513 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7514 (define-obsolete-function-alias 'org-get-legal-level
7515 'org-get-valid-level)
7516 (define-obsolete-function-alias 'org-get-legal-level
7517 'org-get-valid-level "23.1")))
7519 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7520 ;; ̀org-with-limited-levels'
7521 (defun org-promote ()
7522 "Promote the current heading higher up the tree.
7523 If the region is active in `transient-mark-mode', promote all headings
7524 in the region."
7525 (org-back-to-heading t)
7526 (let* ((level (save-match-data (funcall outline-level)))
7527 (after-change-functions (remove 'flyspell-after-change-function
7528 after-change-functions))
7529 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7530 (diff (abs (- level (length up-head) -1))))
7531 (cond ((and (= level 1) org-called-with-limited-levels
7532 org-allow-promoting-top-level-subtree)
7533 (replace-match "# " nil t))
7534 ((= level 1)
7535 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7536 (t (replace-match up-head nil t)))
7537 ;; Fixup tag positioning
7538 (unless (= level 1)
7539 (and org-auto-align-tags (org-set-tags nil t))
7540 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7541 (run-hooks 'org-after-promote-entry-hook)))
7543 (defun org-demote ()
7544 "Demote the current heading lower down the tree.
7545 If the region is active in `transient-mark-mode', demote all headings
7546 in the region."
7547 (org-back-to-heading t)
7548 (let* ((level (save-match-data (funcall outline-level)))
7549 (after-change-functions (remove 'flyspell-after-change-function
7550 after-change-functions))
7551 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7552 (diff (abs (- level (length down-head) -1))))
7553 (replace-match down-head nil t)
7554 ;; Fixup tag positioning
7555 (and org-auto-align-tags (org-set-tags nil t))
7556 (if org-adapt-indentation (org-fixup-indentation diff))
7557 (run-hooks 'org-after-demote-entry-hook)))
7559 (defun org-cycle-level ()
7560 "Cycle the level of an empty headline through possible states.
7561 This goes first to child, then to parent, level, then up the hierarchy.
7562 After top level, it switches back to sibling level."
7563 (interactive)
7564 (let ((org-adapt-indentation nil))
7565 (when (org-point-at-end-of-empty-headline)
7566 (setq this-command 'org-cycle-level) ; Only needed for caching
7567 (let ((cur-level (org-current-level))
7568 (prev-level (org-get-previous-line-level)))
7569 (cond
7570 ;; If first headline in file, promote to top-level.
7571 ((= prev-level 0)
7572 (loop repeat (/ (- cur-level 1) (org-level-increment))
7573 do (org-do-promote)))
7574 ;; If same level as prev, demote one.
7575 ((= prev-level cur-level)
7576 (org-do-demote))
7577 ;; If parent is top-level, promote to top level if not already.
7578 ((= prev-level 1)
7579 (loop repeat (/ (- cur-level 1) (org-level-increment))
7580 do (org-do-promote)))
7581 ;; If top-level, return to prev-level.
7582 ((= cur-level 1)
7583 (loop repeat (/ (- prev-level 1) (org-level-increment))
7584 do (org-do-demote)))
7585 ;; If less than prev-level, promote one.
7586 ((< cur-level prev-level)
7587 (org-do-promote))
7588 ;; If deeper than prev-level, promote until higher than
7589 ;; prev-level.
7590 ((> cur-level prev-level)
7591 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7592 do (org-do-promote))))
7593 t))))
7595 (defun org-map-tree (fun)
7596 "Call FUN for every heading underneath the current one."
7597 (org-back-to-heading)
7598 (let ((level (funcall outline-level)))
7599 (save-excursion
7600 (funcall fun)
7601 (while (and (progn
7602 (outline-next-heading)
7603 (> (funcall outline-level) level))
7604 (not (eobp)))
7605 (funcall fun)))))
7607 (defun org-map-region (fun beg end)
7608 "Call FUN for every heading between BEG and END."
7609 (let ((org-ignore-region t))
7610 (save-excursion
7611 (setq end (copy-marker end))
7612 (goto-char beg)
7613 (if (and (re-search-forward org-outline-regexp-bol nil t)
7614 (< (point) end))
7615 (funcall fun))
7616 (while (and (progn
7617 (outline-next-heading)
7618 (< (point) end))
7619 (not (eobp)))
7620 (funcall fun)))))
7622 (defvar org-property-end-re) ; silence byte-compiler
7623 (defun org-fixup-indentation (diff)
7624 "Change the indentation in the current entry by DIFF.
7625 However, if any line in the current entry has no indentation, or if it
7626 would end up with no indentation after the change, nothing at all is done."
7627 (save-excursion
7628 (let ((end (save-excursion (outline-next-heading)
7629 (point-marker)))
7630 (prohibit (if (> diff 0)
7631 "^\\S-"
7632 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7633 col)
7634 (unless (save-excursion (end-of-line 1)
7635 (re-search-forward prohibit end t))
7636 (while (and (< (point) end)
7637 (re-search-forward "^[ \t]+" end t))
7638 (goto-char (match-end 0))
7639 (setq col (current-column))
7640 (if (< diff 0) (replace-match ""))
7641 (org-indent-to-column (+ diff col))))
7642 (move-marker end nil))))
7644 (defun org-convert-to-odd-levels ()
7645 "Convert an org-mode file with all levels allowed to one with odd levels.
7646 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7647 level 5 etc."
7648 (interactive)
7649 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7650 (let ((outline-level 'org-outline-level)
7651 (org-odd-levels-only nil) n)
7652 (save-excursion
7653 (goto-char (point-min))
7654 (while (re-search-forward "^\\*\\*+ " nil t)
7655 (setq n (- (length (match-string 0)) 2))
7656 (while (>= (setq n (1- n)) 0)
7657 (org-demote))
7658 (end-of-line 1))))))
7660 (defun org-convert-to-oddeven-levels ()
7661 "Convert an org-mode file with only odd levels to one with odd/even levels.
7662 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7663 file contains a section with an even level, conversion would
7664 destroy the structure of the file. An error is signaled in this
7665 case."
7666 (interactive)
7667 (goto-char (point-min))
7668 ;; First check if there are no even levels
7669 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7670 (org-show-context t)
7671 (error "Not all levels are odd in this file. Conversion not possible"))
7672 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7673 (let ((outline-regexp org-outline-regexp)
7674 (outline-level 'org-outline-level)
7675 (org-odd-levels-only nil) n)
7676 (save-excursion
7677 (goto-char (point-min))
7678 (while (re-search-forward "^\\*\\*+ " nil t)
7679 (setq n (/ (1- (length (match-string 0))) 2))
7680 (while (>= (setq n (1- n)) 0)
7681 (org-promote))
7682 (end-of-line 1))))))
7684 (defun org-tr-level (n)
7685 "Make N odd if required."
7686 (if org-odd-levels-only (1+ (/ n 2)) n))
7688 ;;; Vertical tree motion, cutting and pasting of subtrees
7690 (defun org-move-subtree-up (&optional arg)
7691 "Move the current subtree up past ARG headlines of the same level."
7692 (interactive "p")
7693 (org-move-subtree-down (- (prefix-numeric-value arg))))
7695 (defun org-move-subtree-down (&optional arg)
7696 "Move the current subtree down past ARG headlines of the same level."
7697 (interactive "p")
7698 (setq arg (prefix-numeric-value arg))
7699 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7700 'org-get-last-sibling))
7701 (ins-point (make-marker))
7702 (cnt (abs arg))
7703 (col (current-column))
7704 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7705 ;; Select the tree
7706 (org-back-to-heading)
7707 (setq beg0 (point))
7708 (save-excursion
7709 (setq ne-beg (org-back-over-empty-lines))
7710 (setq beg (point)))
7711 (save-match-data
7712 (save-excursion (outline-end-of-heading)
7713 (setq folded (outline-invisible-p)))
7714 (outline-end-of-subtree))
7715 (outline-next-heading)
7716 (setq ne-end (org-back-over-empty-lines))
7717 (setq end (point))
7718 (goto-char beg0)
7719 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7720 ;; include less whitespace
7721 (save-excursion
7722 (goto-char beg)
7723 (forward-line (- ne-beg ne-end))
7724 (setq beg (point))))
7725 ;; Find insertion point, with error handling
7726 (while (> cnt 0)
7727 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7728 (progn (goto-char beg0)
7729 (error "Cannot move past superior level or buffer limit")))
7730 (setq cnt (1- cnt)))
7731 (if (> arg 0)
7732 ;; Moving forward - still need to move over subtree
7733 (progn (org-end-of-subtree t t)
7734 (save-excursion
7735 (org-back-over-empty-lines)
7736 (or (bolp) (newline)))))
7737 (setq ne-ins (org-back-over-empty-lines))
7738 (move-marker ins-point (point))
7739 (setq txt (buffer-substring beg end))
7740 (org-save-markers-in-region beg end)
7741 (delete-region beg end)
7742 (org-remove-empty-overlays-at beg)
7743 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7744 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7745 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7746 (let ((bbb (point)))
7747 (insert-before-markers txt)
7748 (org-reinstall-markers-in-region bbb)
7749 (move-marker ins-point bbb))
7750 (or (bolp) (insert "\n"))
7751 (setq ins-end (point))
7752 (goto-char ins-point)
7753 (org-skip-whitespace)
7754 (when (and (< arg 0)
7755 (org-first-sibling-p)
7756 (> ne-ins ne-beg))
7757 ;; Move whitespace back to beginning
7758 (save-excursion
7759 (goto-char ins-end)
7760 (let ((kill-whole-line t))
7761 (kill-line (- ne-ins ne-beg)) (point)))
7762 (insert (make-string (- ne-ins ne-beg) ?\n)))
7763 (move-marker ins-point nil)
7764 (if folded
7765 (hide-subtree)
7766 (org-show-entry)
7767 (show-children)
7768 (org-cycle-hide-drawers 'children))
7769 (org-clean-visibility-after-subtree-move)
7770 ;; move back to the initial column we were at
7771 (move-to-column col)))
7773 (defvar org-subtree-clip ""
7774 "Clipboard for cut and paste of subtrees.
7775 This is actually only a copy of the kill, because we use the normal kill
7776 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7778 (defvar org-subtree-clip-folded nil
7779 "Was the last copied subtree folded?
7780 This is used to fold the tree back after pasting.")
7782 (defun org-cut-subtree (&optional n)
7783 "Cut the current subtree into the clipboard.
7784 With prefix arg N, cut this many sequential subtrees.
7785 This is a short-hand for marking the subtree and then cutting it."
7786 (interactive "p")
7787 (org-copy-subtree n 'cut))
7789 (defun org-copy-subtree (&optional n cut force-store-markers)
7790 "Cut the current subtree into the clipboard.
7791 With prefix arg N, cut this many sequential subtrees.
7792 This is a short-hand for marking the subtree and then copying it.
7793 If CUT is non-nil, actually cut the subtree.
7794 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7795 of some markers in the region, even if CUT is non-nil. This is
7796 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7797 (interactive "p")
7798 (let (beg end folded (beg0 (point)))
7799 (if (org-called-interactively-p 'any)
7800 (org-back-to-heading nil) ; take what looks like a subtree
7801 (org-back-to-heading t)) ; take what is really there
7802 (org-back-over-empty-lines)
7803 (setq beg (point))
7804 (skip-chars-forward " \t\r\n")
7805 (save-match-data
7806 (save-excursion (outline-end-of-heading)
7807 (setq folded (outline-invisible-p)))
7808 (condition-case nil
7809 (org-forward-heading-same-level (1- n) t)
7810 (error nil))
7811 (org-end-of-subtree t t))
7812 (org-back-over-empty-lines)
7813 (setq end (point))
7814 (goto-char beg0)
7815 (when (> end beg)
7816 (setq org-subtree-clip-folded folded)
7817 (when (or cut force-store-markers)
7818 (org-save-markers-in-region beg end))
7819 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7820 (setq org-subtree-clip (current-kill 0))
7821 (message "%s: Subtree(s) with %d characters"
7822 (if cut "Cut" "Copied")
7823 (length org-subtree-clip)))))
7825 (defun org-paste-subtree (&optional level tree for-yank)
7826 "Paste the clipboard as a subtree, with modification of headline level.
7827 The entire subtree is promoted or demoted in order to match a new headline
7828 level.
7830 If the cursor is at the beginning of a headline, the same level as
7831 that headline is used to paste the tree
7833 If not, the new level is derived from the *visible* headings
7834 before and after the insertion point, and taken to be the inferior headline
7835 level of the two. So if the previous visible heading is level 3 and the
7836 next is level 4 (or vice versa), level 4 will be used for insertion.
7837 This makes sure that the subtree remains an independent subtree and does
7838 not swallow low level entries.
7840 You can also force a different level, either by using a numeric prefix
7841 argument, or by inserting the heading marker by hand. For example, if the
7842 cursor is after \"*****\", then the tree will be shifted to level 5.
7844 If optional TREE is given, use this text instead of the kill ring.
7846 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7847 move back over whitespace before inserting, and move point to the end of
7848 the inserted text when done."
7849 (interactive "P")
7850 (setq tree (or tree (and kill-ring (current-kill 0))))
7851 (unless (org-kill-is-subtree-p tree)
7852 (error "%s"
7853 (substitute-command-keys
7854 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7855 (org-with-limited-levels
7856 (let* ((visp (not (outline-invisible-p)))
7857 (txt tree)
7858 (^re_ "\\(\\*+\\)[ \t]*")
7859 (old-level (if (string-match org-outline-regexp-bol txt)
7860 (- (match-end 0) (match-beginning 0) 1)
7861 -1))
7862 (force-level (cond (level (prefix-numeric-value level))
7863 ((and (looking-at "[ \t]*$")
7864 (string-match
7865 "^\\*+$" (buffer-substring
7866 (point-at-bol) (point))))
7867 (- (match-end 1) (match-beginning 1)))
7868 ((and (bolp)
7869 (looking-at org-outline-regexp))
7870 (- (match-end 0) (point) 1))))
7871 (previous-level (save-excursion
7872 (condition-case nil
7873 (progn
7874 (outline-previous-visible-heading 1)
7875 (if (looking-at ^re_)
7876 (- (match-end 0) (match-beginning 0) 1)
7878 (error 1))))
7879 (next-level (save-excursion
7880 (condition-case nil
7881 (progn
7882 (or (looking-at org-outline-regexp)
7883 (outline-next-visible-heading 1))
7884 (if (looking-at ^re_)
7885 (- (match-end 0) (match-beginning 0) 1)
7887 (error 1))))
7888 (new-level (or force-level (max previous-level next-level)))
7889 (shift (if (or (= old-level -1)
7890 (= new-level -1)
7891 (= old-level new-level))
7893 (- new-level old-level)))
7894 (delta (if (> shift 0) -1 1))
7895 (func (if (> shift 0) 'org-demote 'org-promote))
7896 (org-odd-levels-only nil)
7897 beg end newend)
7898 ;; Remove the forced level indicator
7899 (if force-level
7900 (delete-region (point-at-bol) (point)))
7901 ;; Paste
7902 (beginning-of-line (if (bolp) 1 2))
7903 (unless for-yank (org-back-over-empty-lines))
7904 (setq beg (point))
7905 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7906 (insert-before-markers txt)
7907 (unless (string-match "\n\\'" txt) (insert "\n"))
7908 (setq newend (point))
7909 (org-reinstall-markers-in-region beg)
7910 (setq end (point))
7911 (goto-char beg)
7912 (skip-chars-forward " \t\n\r")
7913 (setq beg (point))
7914 (if (and (outline-invisible-p) visp)
7915 (save-excursion (outline-show-heading)))
7916 ;; Shift if necessary
7917 (unless (= shift 0)
7918 (save-restriction
7919 (narrow-to-region beg end)
7920 (while (not (= shift 0))
7921 (org-map-region func (point-min) (point-max))
7922 (setq shift (+ delta shift)))
7923 (goto-char (point-min))
7924 (setq newend (point-max))))
7925 (when (or (org-called-interactively-p 'interactive) for-yank)
7926 (message "Clipboard pasted as level %d subtree" new-level))
7927 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7928 kill-ring
7929 (eq org-subtree-clip (current-kill 0))
7930 org-subtree-clip-folded)
7931 ;; The tree was folded before it was killed/copied
7932 (hide-subtree))
7933 (and for-yank (goto-char newend)))))
7935 (defun org-kill-is-subtree-p (&optional txt)
7936 "Check if the current kill is an outline subtree, or a set of trees.
7937 Returns nil if kill does not start with a headline, or if the first
7938 headline level is not the largest headline level in the tree.
7939 So this will actually accept several entries of equal levels as well,
7940 which is OK for `org-paste-subtree'.
7941 If optional TXT is given, check this string instead of the current kill."
7942 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7943 (re (org-get-limited-outline-regexp))
7944 (^re (concat "^" re))
7945 (start-level (and kill
7946 (string-match
7947 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7948 kill)
7949 (- (match-end 2) (match-beginning 2) 1)))
7950 (start (1+ (or (match-beginning 2) -1))))
7951 (if (not start-level)
7952 (progn
7953 nil) ;; does not even start with a heading
7954 (catch 'exit
7955 (while (setq start (string-match ^re kill (1+ start)))
7956 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7957 (throw 'exit nil)))
7958 t))))
7960 (defvar org-markers-to-move nil
7961 "Markers that should be moved with a cut-and-paste operation.
7962 Those markers are stored together with their positions relative to
7963 the start of the region.")
7965 (defun org-save-markers-in-region (beg end)
7966 "Check markers in region.
7967 If these markers are between BEG and END, record their position relative
7968 to BEG, so that after moving the block of text, we can put the markers back
7969 into place.
7970 This function gets called just before an entry or tree gets cut from the
7971 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7972 called immediately, to move the markers with the entries."
7973 (setq org-markers-to-move nil)
7974 (when (featurep 'org-clock)
7975 (org-clock-save-markers-for-cut-and-paste beg end))
7976 (when (featurep 'org-agenda)
7977 (org-agenda-save-markers-for-cut-and-paste beg end)))
7979 (defun org-check-and-save-marker (marker beg end)
7980 "Check if MARKER is between BEG and END.
7981 If yes, remember the marker and the distance to BEG."
7982 (when (and (marker-buffer marker)
7983 (equal (marker-buffer marker) (current-buffer)))
7984 (if (and (>= marker beg) (< marker end))
7985 (push (cons marker (- marker beg)) org-markers-to-move))))
7987 (defun org-reinstall-markers-in-region (beg)
7988 "Move all remembered markers to their position relative to BEG."
7989 (mapc (lambda (x)
7990 (move-marker (car x) (+ beg (cdr x))))
7991 org-markers-to-move)
7992 (setq org-markers-to-move nil))
7994 (defun org-narrow-to-subtree ()
7995 "Narrow buffer to the current subtree."
7996 (interactive)
7997 (save-excursion
7998 (save-match-data
7999 (org-with-limited-levels
8000 (narrow-to-region
8001 (progn (org-back-to-heading t) (point))
8002 (progn (org-end-of-subtree t t)
8003 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8004 (point)))))))
8006 (defun org-narrow-to-block ()
8007 "Narrow buffer to the current block."
8008 (interactive)
8009 (let* ((case-fold-search t)
8010 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8011 "^[ \t]*#\\+end_.*")))
8012 (if blockp
8013 (narrow-to-region (car blockp) (cdr blockp))
8014 (error "Not in a block"))))
8016 (eval-when-compile
8017 (defvar org-property-drawer-re))
8019 (defvar org-property-start-re) ;; defined below
8020 (defun org-clone-subtree-with-time-shift (n &optional shift)
8021 "Clone the task (subtree) at point N times.
8022 The clones will be inserted as siblings.
8024 In interactive use, the user will be prompted for the number of
8025 clones to be produced, and for a time SHIFT, which may be a
8026 repeater as used in time stamps, for example `+3d'.
8028 When a valid repeater is given and the entry contains any time
8029 stamps, the clones will become a sequence in time, with time
8030 stamps in the subtree shifted for each clone produced. If SHIFT
8031 is nil or the empty string, time stamps will be left alone. The
8032 ID property of the original subtree is removed.
8034 If the original subtree did contain time stamps with a repeater,
8035 the following will happen:
8036 - the repeater will be removed in each clone
8037 - an additional clone will be produced, with the current, unshifted
8038 date(s) in the entry.
8039 - the original entry will be placed *after* all the clones, with
8040 repeater intact.
8041 - the start days in the repeater in the original entry will be shifted
8042 to past the last clone.
8043 In this way you can spell out a number of instances of a repeating task,
8044 and still retain the repeater to cover future instances of the task."
8045 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8046 (let (beg end template task idprop
8047 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8048 (drawer-re org-drawer-regexp))
8049 (if (not (and (integerp n) (> n 0)))
8050 (error "Invalid number of replications %s" n))
8051 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8052 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8053 shift)))
8054 (error "Invalid shift specification %s" shift))
8055 (when doshift
8056 (setq shift-n (string-to-number (match-string 1 shift))
8057 shift-what (cdr (assoc (match-string 2 shift)
8058 '(("d" . day) ("w" . week)
8059 ("m" . month) ("y" . year))))))
8060 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8061 (setq nmin 1 nmax n)
8062 (org-back-to-heading t)
8063 (setq beg (point))
8064 (setq idprop (org-entry-get nil "ID"))
8065 (org-end-of-subtree t t)
8066 (or (bolp) (insert "\n"))
8067 (setq end (point))
8068 (setq template (buffer-substring beg end))
8069 (when (and doshift
8070 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8071 (delete-region beg end)
8072 (setq end beg)
8073 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8074 (goto-char end)
8075 (loop for n from nmin to nmax do
8076 ;; prepare clone
8077 (with-temp-buffer
8078 (insert template)
8079 (org-mode)
8080 (goto-char (point-min))
8081 (org-show-subtree)
8082 (and idprop (if org-clone-delete-id
8083 (org-entry-delete nil "ID")
8084 (org-id-get-create t)))
8085 (unless (= n 0)
8086 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8087 (kill-whole-line))
8088 (goto-char (point-min))
8089 (while (re-search-forward drawer-re nil t)
8090 (mapc (lambda (d)
8091 (org-remove-empty-drawer-at d (point))) org-drawers)))
8092 (goto-char (point-min))
8093 (when doshift
8094 (while (re-search-forward org-ts-regexp-both nil t)
8095 (org-timestamp-change (* n shift-n) shift-what))
8096 (unless (= n n-no-remove)
8097 (goto-char (point-min))
8098 (while (re-search-forward org-ts-regexp nil t)
8099 (save-excursion
8100 (goto-char (match-beginning 0))
8101 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8102 (delete-region (match-beginning 1) (match-end 1)))))))
8103 (setq task (buffer-string)))
8104 (insert task))
8105 (goto-char beg)))
8107 ;;; Outline Sorting
8109 (defun org-sort (with-case)
8110 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8111 Optional argument WITH-CASE means sort case-sensitively."
8112 (interactive "P")
8113 (cond
8114 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8115 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8117 (org-call-with-arg 'org-sort-entries with-case))))
8119 (defun org-sort-remove-invisible (s)
8120 (remove-text-properties 0 (length s) org-rm-props s)
8121 (while (string-match org-bracket-link-regexp s)
8122 (setq s (replace-match (if (match-end 2)
8123 (match-string 3 s)
8124 (match-string 1 s)) t t s)))
8127 (defvar org-priority-regexp) ; defined later in the file
8129 (defvar org-after-sorting-entries-or-items-hook nil
8130 "Hook that is run after a bunch of entries or items have been sorted.
8131 When children are sorted, the cursor is in the parent line when this
8132 hook gets called. When a region or a plain list is sorted, the cursor
8133 will be in the first entry of the sorted region/list.")
8135 (defun org-sort-entries
8136 (&optional with-case sorting-type getkey-func compare-func property)
8137 "Sort entries on a certain level of an outline tree.
8138 If there is an active region, the entries in the region are sorted.
8139 Else, if the cursor is before the first entry, sort the top-level items.
8140 Else, the children of the entry at point are sorted.
8142 Sorting can be alphabetically, numerically, by date/time as given by
8143 a time stamp, by a property or by priority.
8145 The command prompts for the sorting type unless it has been given to the
8146 function through the SORTING-TYPE argument, which needs to be a character,
8147 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8148 precise meaning of each character:
8150 n Numerically, by converting the beginning of the entry/item to a number.
8151 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8152 t By date/time, either the first active time stamp in the entry, or, if
8153 none exist, by the first inactive one.
8154 s By the scheduled date/time.
8155 d By deadline date/time.
8156 c By creation time, which is assumed to be the first inactive time stamp
8157 at the beginning of a line.
8158 p By priority according to the cookie.
8159 r By the value of a property.
8161 Capital letters will reverse the sort order.
8163 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8164 called with point at the beginning of the record. It must return either
8165 a string or a number that should serve as the sorting key for that record.
8167 Comparing entries ignores case by default. However, with an optional argument
8168 WITH-CASE, the sorting considers case as well."
8169 (interactive "P")
8170 (let ((case-func (if with-case 'identity 'downcase))
8171 start beg end stars re re2
8172 txt what tmp)
8173 ;; Find beginning and end of region to sort
8174 (cond
8175 ((org-region-active-p)
8176 ;; we will sort the region
8177 (setq end (region-end)
8178 what "region")
8179 (goto-char (region-beginning))
8180 (if (not (org-at-heading-p)) (outline-next-heading))
8181 (setq start (point)))
8182 ((or (org-at-heading-p)
8183 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8184 ;; we will sort the children of the current headline
8185 (org-back-to-heading)
8186 (setq start (point)
8187 end (progn (org-end-of-subtree t t)
8188 (or (bolp) (insert "\n"))
8189 (org-back-over-empty-lines)
8190 (point))
8191 what "children")
8192 (goto-char start)
8193 (show-subtree)
8194 (outline-next-heading))
8196 ;; we will sort the top-level entries in this file
8197 (goto-char (point-min))
8198 (or (org-at-heading-p) (outline-next-heading))
8199 (setq start (point))
8200 (goto-char (point-max))
8201 (beginning-of-line 1)
8202 (when (looking-at ".*?\\S-")
8203 ;; File ends in a non-white line
8204 (end-of-line 1)
8205 (insert "\n"))
8206 (setq end (point-max))
8207 (setq what "top-level")
8208 (goto-char start)
8209 (show-all)))
8211 (setq beg (point))
8212 (if (>= beg end) (error "Nothing to sort"))
8214 (looking-at "\\(\\*+\\)")
8215 (setq stars (match-string 1)
8216 re (concat "^" (regexp-quote stars) " +")
8217 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8218 txt (buffer-substring beg end))
8219 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8220 (if (and (not (equal stars "*")) (string-match re2 txt))
8221 (error "Region to sort contains a level above the first entry"))
8223 (unless sorting-type
8224 (message
8225 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8226 [t]ime [s]cheduled [d]eadline [c]reated
8227 A/N/T/S/D/C/P/O/F means reversed:"
8228 what)
8229 (setq sorting-type (read-char-exclusive))
8231 (and (= (downcase sorting-type) ?f)
8232 (setq getkey-func
8233 (org-icompleting-read "Sort using function: "
8234 obarray 'fboundp t nil nil))
8235 (setq getkey-func (intern getkey-func)))
8237 (and (= (downcase sorting-type) ?r)
8238 (setq property
8239 (org-icompleting-read "Property: "
8240 (mapcar 'list (org-buffer-property-keys t))
8241 nil t))))
8243 (message "Sorting entries...")
8245 (save-restriction
8246 (narrow-to-region start end)
8247 (let ((dcst (downcase sorting-type))
8248 (case-fold-search nil)
8249 (now (current-time)))
8250 (sort-subr
8251 (/= dcst sorting-type)
8252 ;; This function moves to the beginning character of the "record" to
8253 ;; be sorted.
8254 (lambda nil
8255 (if (re-search-forward re nil t)
8256 (goto-char (match-beginning 0))
8257 (goto-char (point-max))))
8258 ;; This function moves to the last character of the "record" being
8259 ;; sorted.
8260 (lambda nil
8261 (save-match-data
8262 (condition-case nil
8263 (outline-forward-same-level 1)
8264 (error
8265 (goto-char (point-max))))))
8266 ;; This function returns the value that gets sorted against.
8267 (lambda nil
8268 (cond
8269 ((= dcst ?n)
8270 (if (looking-at org-complex-heading-regexp)
8271 (string-to-number (match-string 4))
8272 nil))
8273 ((= dcst ?a)
8274 (if (looking-at org-complex-heading-regexp)
8275 (funcall case-func (match-string 4))
8276 nil))
8277 ((= dcst ?t)
8278 (let ((end (save-excursion (outline-next-heading) (point))))
8279 (if (or (re-search-forward org-ts-regexp end t)
8280 (re-search-forward org-ts-regexp-both end t))
8281 (org-time-string-to-seconds (match-string 0))
8282 (org-float-time now))))
8283 ((= dcst ?c)
8284 (let ((end (save-excursion (outline-next-heading) (point))))
8285 (if (re-search-forward
8286 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8287 end t)
8288 (org-time-string-to-seconds (match-string 0))
8289 (org-float-time now))))
8290 ((= dcst ?s)
8291 (let ((end (save-excursion (outline-next-heading) (point))))
8292 (if (re-search-forward org-scheduled-time-regexp end t)
8293 (org-time-string-to-seconds (match-string 1))
8294 (org-float-time now))))
8295 ((= dcst ?d)
8296 (let ((end (save-excursion (outline-next-heading) (point))))
8297 (if (re-search-forward org-deadline-time-regexp end t)
8298 (org-time-string-to-seconds (match-string 1))
8299 (org-float-time now))))
8300 ((= dcst ?p)
8301 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8302 (string-to-char (match-string 2))
8303 org-default-priority))
8304 ((= dcst ?r)
8305 (or (org-entry-get nil property) ""))
8306 ((= dcst ?o)
8307 (if (looking-at org-complex-heading-regexp)
8308 (- 9999 (length (member (match-string 2)
8309 org-todo-keywords-1)))))
8310 ((= dcst ?f)
8311 (if getkey-func
8312 (progn
8313 (setq tmp (funcall getkey-func))
8314 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8315 tmp)
8316 (error "Invalid key function `%s'" getkey-func)))
8317 (t (error "Invalid sorting type `%c'" sorting-type))))
8319 (cond
8320 ((= dcst ?a) 'string<)
8321 ((= dcst ?f) compare-func)
8322 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8323 (run-hooks 'org-after-sorting-entries-or-items-hook)
8324 (message "Sorting entries...done")))
8326 (defun org-do-sort (table what &optional with-case sorting-type)
8327 "Sort TABLE of WHAT according to SORTING-TYPE.
8328 The user will be prompted for the SORTING-TYPE if the call to this
8329 function does not specify it. WHAT is only for the prompt, to indicate
8330 what is being sorted. The sorting key will be extracted from
8331 the car of the elements of the table.
8332 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8333 (unless sorting-type
8334 (message
8335 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8336 what)
8337 (setq sorting-type (read-char-exclusive)))
8338 (let ((dcst (downcase sorting-type))
8339 extractfun comparefun)
8340 ;; Define the appropriate functions
8341 (cond
8342 ((= dcst ?n)
8343 (setq extractfun 'string-to-number
8344 comparefun (if (= dcst sorting-type) '< '>)))
8345 ((= dcst ?a)
8346 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8347 (lambda(x) (downcase (org-sort-remove-invisible x))))
8348 comparefun (if (= dcst sorting-type)
8349 'string<
8350 (lambda (a b) (and (not (string< a b))
8351 (not (string= a b)))))))
8352 ((= dcst ?t)
8353 (setq extractfun
8354 (lambda (x)
8355 (if (or (string-match org-ts-regexp x)
8356 (string-match org-ts-regexp-both x))
8357 (org-float-time
8358 (org-time-string-to-time (match-string 0 x)))
8360 comparefun (if (= dcst sorting-type) '< '>)))
8361 (t (error "Invalid sorting type `%c'" sorting-type)))
8363 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8364 table)
8365 (lambda (a b) (funcall comparefun (car a) (car b))))))
8368 ;;; The orgstruct minor mode
8370 ;; Define a minor mode which can be used in other modes in order to
8371 ;; integrate the org-mode structure editing commands.
8373 ;; This is really a hack, because the org-mode structure commands use
8374 ;; keys which normally belong to the major mode. Here is how it
8375 ;; works: The minor mode defines all the keys necessary to operate the
8376 ;; structure commands, but wraps the commands into a function which
8377 ;; tests if the cursor is currently at a headline or a plain list
8378 ;; item. If that is the case, the structure command is used,
8379 ;; temporarily setting many Org-mode variables like regular
8380 ;; expressions for filling etc. However, when any of those keys is
8381 ;; used at a different location, function uses `key-binding' to look
8382 ;; up if the key has an associated command in another currently active
8383 ;; keymap (minor modes, major mode, global), and executes that
8384 ;; command. There might be problems if any of the keys is otherwise
8385 ;; used as a prefix key.
8387 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8388 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8389 ;; addresses this by checking explicitly for both bindings.
8391 (defvar orgstruct-mode-map (make-sparse-keymap)
8392 "Keymap for the minor `orgstruct-mode'.")
8394 (defvar org-local-vars nil
8395 "List of local variables, for use by `orgstruct-mode'.")
8397 ;;;###autoload
8398 (define-minor-mode orgstruct-mode
8399 "Toggle the minor mode `orgstruct-mode'.
8400 This mode is for using Org-mode structure commands in other
8401 modes. The following keys behave as if Org-mode were active, if
8402 the cursor is on a headline, or on a plain list item (both as
8403 defined by Org-mode).
8405 M-up Move entry/item up
8406 M-down Move entry/item down
8407 M-left Promote
8408 M-right Demote
8409 M-S-up Move entry/item up
8410 M-S-down Move entry/item down
8411 M-S-left Promote subtree
8412 M-S-right Demote subtree
8413 M-q Fill paragraph and items like in Org-mode
8414 C-c ^ Sort entries
8415 C-c - Cycle list bullet
8416 TAB Cycle item visibility
8417 M-RET Insert new heading/item
8418 S-M-RET Insert new TODO heading / Checkbox item
8419 C-c C-c Set tags / toggle checkbox"
8420 nil " OrgStruct" nil
8421 (org-load-modules-maybe)
8422 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8424 ;;;###autoload
8425 (defun turn-on-orgstruct ()
8426 "Unconditionally turn on `orgstruct-mode'."
8427 (orgstruct-mode 1))
8429 (defvar org-fb-vars nil)
8430 (make-variable-buffer-local 'org-fb-vars)
8431 (defun orgstruct++-mode (&optional arg)
8432 "Toggle `orgstruct-mode', the enhanced version of it.
8433 In addition to setting orgstruct-mode, this also exports all
8434 indentation and autofilling variables from org-mode into the
8435 buffer. It will also recognize item context in multiline items."
8436 (interactive "P")
8437 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8438 (if (< arg 1)
8439 (progn (orgstruct-mode -1)
8440 (mapc (lambda(v)
8441 (org-set-local (car v)
8442 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8443 org-fb-vars))
8444 (orgstruct-mode 1)
8445 (setq org-fb-vars nil)
8446 (let (var val)
8447 (mapc
8448 (lambda (x)
8449 (when (string-match
8450 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8451 (symbol-name (car x)))
8452 (setq var (car x) val (nth 1 x))
8453 (push (list var `(quote ,(eval var))) org-fb-vars)
8454 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8455 org-local-vars)
8456 (org-set-local 'orgstruct-is-++ t))))
8458 (defvar orgstruct-is-++ nil
8459 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8460 (make-variable-buffer-local 'orgstruct-is-++)
8462 ;;;###autoload
8463 (defun turn-on-orgstruct++ ()
8464 "Unconditionally turn on `orgstruct++-mode'."
8465 (orgstruct++-mode 1))
8467 (defun orgstruct-error ()
8468 "Error when there is no default binding for a structure key."
8469 (interactive)
8470 (error "This key has no function outside structure elements"))
8472 (defun orgstruct-setup ()
8473 "Setup orgstruct keymaps."
8474 (let ((nfunc 0)
8475 (bindings
8476 (list
8477 '([(meta up)] org-metaup)
8478 '([(meta down)] org-metadown)
8479 '([(meta left)] org-metaleft)
8480 '([(meta right)] org-metaright)
8481 '([(meta shift up)] org-shiftmetaup)
8482 '([(meta shift down)] org-shiftmetadown)
8483 '([(meta shift left)] org-shiftmetaleft)
8484 '([(meta shift right)] org-shiftmetaright)
8485 '([?\e (up)] org-metaup)
8486 '([?\e (down)] org-metadown)
8487 '([?\e (left)] org-metaleft)
8488 '([?\e (right)] org-metaright)
8489 '([?\e (shift up)] org-shiftmetaup)
8490 '([?\e (shift down)] org-shiftmetadown)
8491 '([?\e (shift left)] org-shiftmetaleft)
8492 '([?\e (shift right)] org-shiftmetaright)
8493 '([(shift up)] org-shiftup)
8494 '([(shift down)] org-shiftdown)
8495 '([(shift left)] org-shiftleft)
8496 '([(shift right)] org-shiftright)
8497 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8498 '("\M-q" fill-paragraph)
8499 '("\C-c^" org-sort)
8500 '("\C-c-" org-cycle-list-bullet)))
8501 elt key fun cmd)
8502 (while (setq elt (pop bindings))
8503 (setq nfunc (1+ nfunc))
8504 (setq key (org-key (car elt))
8505 fun (nth 1 elt)
8506 cmd (orgstruct-make-binding fun nfunc key))
8507 (org-defkey orgstruct-mode-map key cmd))
8509 ;; Prevent an error for users who forgot to make autoloads
8510 (require 'org-element)
8512 ;; Special treatment needed for TAB and RET
8513 (org-defkey orgstruct-mode-map [(tab)]
8514 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8515 (org-defkey orgstruct-mode-map "\C-i"
8516 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8518 (org-defkey orgstruct-mode-map "\M-\C-m"
8519 (orgstruct-make-binding 'org-insert-heading 105
8520 "\M-\C-m" [(meta return)]))
8521 (org-defkey orgstruct-mode-map [(meta return)]
8522 (orgstruct-make-binding 'org-insert-heading 106
8523 [(meta return)] "\M-\C-m"))
8525 (org-defkey orgstruct-mode-map [(shift meta return)]
8526 (orgstruct-make-binding 'org-insert-todo-heading 107
8527 [(meta return)] "\M-\C-m"))
8529 (org-defkey orgstruct-mode-map "\e\C-m"
8530 (orgstruct-make-binding 'org-insert-heading 108
8531 "\e\C-m" [?\e (return)]))
8532 (org-defkey orgstruct-mode-map [?\e (return)]
8533 (orgstruct-make-binding 'org-insert-heading 109
8534 [?\e (return)] "\e\C-m"))
8535 (org-defkey orgstruct-mode-map [?\e (shift return)]
8536 (orgstruct-make-binding 'org-insert-todo-heading 110
8537 [?\e (return)] "\e\C-m"))
8539 (unless org-local-vars
8540 (setq org-local-vars (org-get-local-variables)))
8544 (defun orgstruct-make-binding (fun n &rest keys)
8545 "Create a function for binding in the structure minor mode.
8546 FUN is the command to call inside a table. N is used to create a unique
8547 command name. KEYS are keys that should be checked in for a command
8548 to execute outside of tables."
8549 (eval
8550 (list 'defun
8551 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8552 '(arg)
8553 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8554 "Outside of structure, run the binding of `"
8555 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8556 "'.")
8557 '(interactive "p")
8558 (list 'if
8559 `(org-context-p 'headline 'item
8560 (and orgstruct-is-++
8561 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8562 'item-body))
8563 (list 'org-run-like-in-org-mode (list 'quote fun))
8564 (list 'let '(orgstruct-mode)
8565 (list 'call-interactively
8566 (append '(or)
8567 (mapcar (lambda (k)
8568 (list 'key-binding k))
8569 keys)
8570 '('orgstruct-error))))))))
8572 (defun org-contextualize-keys (alist contexts)
8573 "Return valid elements in ALIST depending on CONTEXTS.
8575 `org-agenda-custom-commands' or `org-capture-templates' are the
8576 values used for ALIST, and `org-agenda-custom-commands-contexts'
8577 or `org-capture-templates-contexts' are the associated contexts
8578 definitions."
8579 (let ((contexts
8580 ;; normalize contexts
8581 (mapcar
8582 (lambda(c) (cond ((listp (cadr c))
8583 (list (car c) (car c) (cadr c)))
8584 ((string= "" (cadr c))
8585 (list (car c) (car c) (caddr c)))
8586 (t c))) contexts))
8587 (a alist) c r s)
8588 ;; loop over all commands or templates
8589 (while (setq c (pop a))
8590 (let (vrules repl)
8591 (cond
8592 ((not (assoc (car c) contexts))
8593 (push c r))
8594 ((and (assoc (car c) contexts)
8595 (setq vrules (org-contextualize-validate-key
8596 (car c) contexts)))
8597 (mapc (lambda (vr)
8598 (when (not (equal (car vr) (cadr vr)))
8599 (setq repl vr))) vrules)
8600 (if (not repl) (push c r)
8601 (push (cadr repl) s)
8602 (push
8603 (cons (car c)
8604 (cdr (or (assoc (cadr repl) alist)
8605 (error "Undefined key `%s' as contextual replacement for `%s'"
8606 (cadr repl) (car c)))))
8607 r))))))
8608 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8609 (delq
8611 (delete-dups
8612 (mapcar (lambda (x)
8613 (let ((tpl (car x)))
8614 (when (not (delq
8616 (mapcar (lambda(y)
8617 (equal y tpl)) s))) x)))
8618 (reverse r))))))
8620 (defun org-contextualize-validate-key (key contexts)
8621 "Check CONTEXTS for agenda or capture KEY."
8622 (let (r rr res)
8623 (while (setq r (pop contexts))
8624 (mapc
8625 (lambda (rr)
8626 (when
8627 (and (equal key (car r))
8628 (if (functionp rr) (funcall rr)
8629 (or (and (eq (car rr) 'in-file)
8630 (buffer-file-name)
8631 (string-match (cdr rr) (buffer-file-name)))
8632 (and (eq (car rr) 'in-mode)
8633 (string-match (cdr rr) (symbol-name major-mode)))
8634 (when (and (eq (car rr) 'not-in-file)
8635 (buffer-file-name))
8636 (not (string-match (cdr rr) (buffer-file-name))))
8637 (when (eq (car rr) 'not-in-mode)
8638 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8639 (push r res)))
8640 (car (last r))))
8641 (delete-dups (delq nil res))))
8643 (defun org-context-p (&rest contexts)
8644 "Check if local context is any of CONTEXTS.
8645 Possible values in the list of contexts are `table', `headline', and `item'."
8646 (let ((pos (point)))
8647 (goto-char (point-at-bol))
8648 (prog1 (or (and (memq 'table contexts)
8649 (looking-at "[ \t]*|"))
8650 (and (memq 'headline contexts)
8651 (looking-at org-outline-regexp))
8652 (and (memq 'item contexts)
8653 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8654 (and (memq 'item-body contexts)
8655 (org-in-item-p)))
8656 (goto-char pos))))
8658 (defun org-get-local-variables ()
8659 "Return a list of all local variables in an Org mode buffer."
8660 (let (varlist)
8661 (with-current-buffer (get-buffer-create "*Org tmp*")
8662 (erase-buffer)
8663 (org-mode)
8664 (setq varlist (buffer-local-variables)))
8665 (kill-buffer "*Org tmp*")
8666 (delq nil
8667 (mapcar
8668 (lambda (x)
8669 (setq x
8670 (if (symbolp x)
8671 (list x)
8672 (list (car x) (list 'quote (cdr x)))))
8673 (if (string-match
8674 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8675 (symbol-name (car x)))
8676 x nil))
8677 varlist))))
8679 (defun org-clone-local-variables (from-buffer &optional regexp)
8680 "Clone local variables from FROM-BUFFER.
8681 Optional argument REGEXP selects variables to clone."
8682 (mapc
8683 (lambda (pair)
8684 (and (symbolp (car pair))
8685 (or (null regexp)
8686 (string-match regexp (symbol-name (car pair))))
8687 (set (make-local-variable (car pair))
8688 (cdr pair))))
8689 (buffer-local-variables from-buffer)))
8691 ;;;###autoload
8692 (defun org-run-like-in-org-mode (cmd)
8693 "Run a command, pretending that the current buffer is in Org-mode.
8694 This will temporarily bind local variables that are typically bound in
8695 Org-mode to the values they have in Org-mode, and then interactively
8696 call CMD."
8697 (org-load-modules-maybe)
8698 (unless org-local-vars
8699 (setq org-local-vars (org-get-local-variables)))
8700 (eval (list 'let org-local-vars
8701 (list 'call-interactively (list 'quote cmd)))))
8703 ;;;; Archiving
8705 (defun org-get-category (&optional pos force-refresh)
8706 "Get the category applying to position POS."
8707 (save-match-data
8708 (if force-refresh (org-refresh-category-properties))
8709 (let ((pos (or pos (point))))
8710 (or (get-text-property pos 'org-category)
8711 (progn (org-refresh-category-properties)
8712 (get-text-property pos 'org-category))))))
8714 (defun org-refresh-category-properties ()
8715 "Refresh category text properties in the buffer."
8716 (let ((case-fold-search t)
8717 (inhibit-read-only t)
8718 (def-cat (cond
8719 ((null org-category)
8720 (if buffer-file-name
8721 (file-name-sans-extension
8722 (file-name-nondirectory buffer-file-name))
8723 "???"))
8724 ((symbolp org-category) (symbol-name org-category))
8725 (t org-category)))
8726 beg end cat pos optionp)
8727 (org-unmodified
8728 (save-excursion
8729 (save-restriction
8730 (widen)
8731 (goto-char (point-min))
8732 (put-text-property (point) (point-max) 'org-category def-cat)
8733 (while (re-search-forward
8734 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8735 (setq pos (match-end 0)
8736 optionp (equal (char-after (match-beginning 0)) ?#)
8737 cat (org-trim (match-string 2)))
8738 (if optionp
8739 (setq beg (point-at-bol) end (point-max))
8740 (org-back-to-heading t)
8741 (setq beg (point) end (org-end-of-subtree t t)))
8742 (put-text-property beg end 'org-category cat)
8743 (put-text-property beg end 'org-category-position beg)
8744 (goto-char pos)))))))
8747 ;;;; Link Stuff
8749 ;;; Link abbreviations
8751 (defun org-link-expand-abbrev (link)
8752 "Apply replacements as defined in `org-link-abbrev-alist'."
8753 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8754 (let* ((key (match-string 1 link))
8755 (as (or (assoc key org-link-abbrev-alist-local)
8756 (assoc key org-link-abbrev-alist)))
8757 (tag (and (match-end 2) (match-string 3 link)))
8758 rpl)
8759 (if (not as)
8760 link
8761 (setq rpl (cdr as))
8762 (cond
8763 ((symbolp rpl) (funcall rpl tag))
8764 ((string-match "%(\\([^)]+\\))" rpl)
8765 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8766 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8767 ((string-match "%h" rpl)
8768 (replace-match (url-hexify-string (or tag "")) t t rpl))
8769 (t (concat rpl tag)))))
8770 link))
8772 ;;; Storing and inserting links
8774 (defvar org-insert-link-history nil
8775 "Minibuffer history for links inserted with `org-insert-link'.")
8777 (defvar org-stored-links nil
8778 "Contains the links stored with `org-store-link'.")
8780 (defvar org-store-link-plist nil
8781 "Plist with info about the most recently link created with `org-store-link'.")
8783 (defvar org-link-protocols nil
8784 "Link protocols added to Org-mode using `org-add-link-type'.")
8786 (defvar org-store-link-functions nil
8787 "List of functions that are called to create and store a link.
8788 Each function will be called in turn until one returns a non-nil
8789 value. Each function should check if it is responsible for creating
8790 this link (for example by looking at the major mode).
8791 If not, it must exit and return nil.
8792 If yes, it should return a non-nil value after a calling
8793 `org-store-link-props' with a list of properties and values.
8794 Special properties are:
8796 :type The link prefix, like \"http\". This must be given.
8797 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8798 This is obligatory as well.
8799 :description Optional default description for the second pair
8800 of brackets in an Org-mode link. The user can still change
8801 this when inserting this link into an Org-mode buffer.
8803 In addition to these, any additional properties can be specified
8804 and then used in capture templates.")
8806 (defun org-add-link-type (type &optional follow export)
8807 "Add TYPE to the list of `org-link-types'.
8808 Re-compute all regular expressions depending on `org-link-types'
8810 FOLLOW and EXPORT are two functions.
8812 FOLLOW should take the link path as the single argument and do whatever
8813 is necessary to follow the link, for example find a file or display
8814 a mail message.
8816 EXPORT should format the link path for export to one of the export formats.
8817 It should be a function accepting three arguments:
8819 path the path of the link, the text after the prefix (like \"http:\")
8820 desc the description of the link, if any, or a description added by
8821 org-export-normalize-links if there is none
8822 format the export format, a symbol like `html' or `latex' or `ascii'..
8824 The function may use the FORMAT information to return different values
8825 depending on the format. The return value will be put literally into
8826 the exported file. If the return value is nil, this means Org should
8827 do what it normally does with links which do not have EXPORT defined.
8829 Org-mode has a built-in default for exporting links. If you are happy with
8830 this default, there is no need to define an export function for the link
8831 type. For a simple example of an export function, see `org-bbdb.el'."
8832 (add-to-list 'org-link-types type t)
8833 (org-make-link-regexps)
8834 (if (assoc type org-link-protocols)
8835 (setcdr (assoc type org-link-protocols) (list follow export))
8836 (push (list type follow export) org-link-protocols)))
8838 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8839 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8841 ;;;###autoload
8842 (defun org-store-link (arg)
8843 "\\<org-mode-map>Store an org-link to the current location.
8844 This link is added to `org-stored-links' and can later be inserted
8845 into an org-buffer with \\[org-insert-link].
8847 For some link types, a prefix arg is interpreted:
8848 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8849 For file links, arg negates `org-context-in-file-links'."
8850 (interactive "P")
8851 (org-load-modules-maybe)
8852 (setq org-store-link-plist nil) ; reset
8853 (org-with-limited-levels
8854 (let (link cpltxt desc description search txt custom-id agenda-link)
8855 (cond
8857 ((run-hook-with-args-until-success 'org-store-link-functions)
8858 (setq link (plist-get org-store-link-plist :link)
8859 desc (or (plist-get org-store-link-plist :description) link)))
8861 ((org-src-edit-buffer-p)
8862 (let (label gc)
8863 (while (or (not label)
8864 (save-excursion
8865 (save-restriction
8866 (widen)
8867 (goto-char (point-min))
8868 (re-search-forward
8869 (regexp-quote (format org-coderef-label-format label))
8870 nil t))))
8871 (when label (message "Label exists already") (sit-for 2))
8872 (setq label (read-string "Code line label: " label)))
8873 (end-of-line 1)
8874 (setq link (format org-coderef-label-format label))
8875 (setq gc (- 79 (length link)))
8876 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8877 (insert link)
8878 (setq link (concat "(" label ")") desc nil)))
8880 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8881 ;; We are in the agenda, link to referenced location
8882 (let ((m (or (get-text-property (point) 'org-hd-marker)
8883 (get-text-property (point) 'org-marker))))
8884 (when m
8885 (org-with-point-at m
8886 (setq agenda-link
8887 (if (org-called-interactively-p 'any)
8888 (call-interactively 'org-store-link)
8889 (org-store-link nil)))))))
8891 ((eq major-mode 'calendar-mode)
8892 (let ((cd (calendar-cursor-to-date)))
8893 (setq link
8894 (format-time-string
8895 (car org-time-stamp-formats)
8896 (apply 'encode-time
8897 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8898 nil nil nil))))
8899 (org-store-link-props :type "calendar" :date cd)))
8901 ((eq major-mode 'help-mode)
8902 (setq link (concat "help:" (save-excursion
8903 (goto-char (point-min))
8904 (looking-at "^[^ ]+")
8905 (match-string 0))))
8906 (org-store-link-props :type "help"))
8908 ((eq major-mode 'w3-mode)
8909 (setq cpltxt (if (and (buffer-name)
8910 (not (string-match "Untitled" (buffer-name))))
8911 (buffer-name)
8912 (url-view-url t))
8913 link (url-view-url t))
8914 (org-store-link-props :type "w3" :url (url-view-url t)))
8916 ((eq major-mode 'w3m-mode)
8917 (setq cpltxt (or w3m-current-title w3m-current-url)
8918 link w3m-current-url)
8919 (org-store-link-props :type "w3m" :url (url-view-url t)))
8921 ((setq search (run-hook-with-args-until-success
8922 'org-create-file-search-functions))
8923 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8924 "::" search))
8925 (setq cpltxt (or description link)))
8927 ((eq major-mode 'image-mode)
8928 (setq cpltxt (concat "file:"
8929 (abbreviate-file-name buffer-file-name))
8930 link cpltxt)
8931 (org-store-link-props :type "image" :file buffer-file-name))
8933 ((eq major-mode 'dired-mode)
8934 ;; link to the file in the current line
8935 (let ((file (dired-get-filename nil t)))
8936 (setq file (if file
8937 (abbreviate-file-name
8938 (expand-file-name (dired-get-filename nil t)))
8939 ;; otherwise, no file so use current directory.
8940 default-directory))
8941 (setq cpltxt (concat "file:" file)
8942 link cpltxt)))
8944 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8945 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8946 (cond
8947 ((org-in-regexp "<<\\(.*?\\)>>")
8948 (setq cpltxt
8949 (concat "file:"
8950 (abbreviate-file-name
8951 (buffer-file-name (buffer-base-buffer)))
8952 "::" (match-string 1))
8953 link cpltxt))
8954 ((and (featurep 'org-id)
8955 (or (eq org-link-to-org-use-id t)
8956 (and (org-called-interactively-p 'any)
8957 (or (eq org-link-to-org-use-id 'create-if-interactive)
8958 (and (eq org-link-to-org-use-id
8959 'create-if-interactive-and-no-custom-id)
8960 (not custom-id))))
8961 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8962 ;; We can make a link using the ID.
8963 (setq link (condition-case nil
8964 (prog1 (org-id-store-link)
8965 (setq desc (plist-get org-store-link-plist :description)))
8966 (error
8967 ;; probably before first headline, link to file only
8968 (concat "file:"
8969 (abbreviate-file-name
8970 (buffer-file-name (buffer-base-buffer))))))))
8972 ;; Just link to current headline
8973 (setq cpltxt (concat "file:"
8974 (abbreviate-file-name
8975 (buffer-file-name (buffer-base-buffer)))))
8976 ;; Add a context search string
8977 (when (org-xor org-context-in-file-links arg)
8978 (setq txt (cond
8979 ((org-at-heading-p) nil)
8980 ((org-region-active-p)
8981 (buffer-substring (region-beginning) (region-end)))))
8982 (when (or (null txt) (string-match "\\S-" txt))
8983 (setq cpltxt
8984 (concat cpltxt "::"
8985 (condition-case nil
8986 (org-make-org-heading-search-string txt)
8987 (error "")))
8988 desc (or (nth 4 (ignore-errors
8989 (org-heading-components))) "NONE"))))
8990 (if (string-match "::\\'" cpltxt)
8991 (setq cpltxt (substring cpltxt 0 -2)))
8992 (setq link cpltxt))))
8994 ((buffer-file-name (buffer-base-buffer))
8995 ;; Just link to this file here.
8996 (setq cpltxt (concat "file:"
8997 (abbreviate-file-name
8998 (buffer-file-name (buffer-base-buffer)))))
8999 ;; Add a context string
9000 (when (org-xor org-context-in-file-links arg)
9001 (setq txt (if (org-region-active-p)
9002 (buffer-substring (region-beginning) (region-end))
9003 (buffer-substring (point-at-bol) (point-at-eol))))
9004 ;; Only use search option if there is some text.
9005 (when (string-match "\\S-" txt)
9006 (setq cpltxt
9007 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9008 desc "NONE")))
9009 (setq link cpltxt))
9011 ((org-called-interactively-p 'interactive)
9012 (error "Cannot link to a buffer which is not visiting a file"))
9014 (t (setq link nil)))
9016 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9017 (setq link (or link cpltxt)
9018 desc (or desc cpltxt))
9019 (if (equal desc "NONE") (setq desc nil))
9021 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9022 (progn
9023 (setq org-stored-links
9024 (cons (list link desc) org-stored-links))
9025 (message "Stored: %s" (or desc link))
9026 (when custom-id
9027 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9028 "::#" custom-id))
9029 (setq org-stored-links
9030 (cons (list link desc) org-stored-links))))
9031 (or agenda-link (and link (org-make-link-string link desc)))))))
9033 (defun org-store-link-props (&rest plist)
9034 "Store link properties, extract names and addresses."
9035 (let (x adr)
9036 (when (setq x (plist-get plist :from))
9037 (setq adr (mail-extract-address-components x))
9038 (setq plist (plist-put plist :fromname (car adr)))
9039 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9040 (when (setq x (plist-get plist :to))
9041 (setq adr (mail-extract-address-components x))
9042 (setq plist (plist-put plist :toname (car adr)))
9043 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9044 (let ((from (plist-get plist :from))
9045 (to (plist-get plist :to)))
9046 (when (and from to org-from-is-user-regexp)
9047 (setq plist
9048 (plist-put plist :fromto
9049 (if (string-match org-from-is-user-regexp from)
9050 (concat "to %t")
9051 (concat "from %f"))))))
9052 (setq org-store-link-plist plist))
9054 (defun org-add-link-props (&rest plist)
9055 "Add these properties to the link property list."
9056 (let (key value)
9057 (while plist
9058 (setq key (pop plist) value (pop plist))
9059 (setq org-store-link-plist
9060 (plist-put org-store-link-plist key value)))))
9062 (defun org-email-link-description (&optional fmt)
9063 "Return the description part of an email link.
9064 This takes information from `org-store-link-plist' and formats it
9065 according to FMT (default from `org-email-link-description-format')."
9066 (setq fmt (or fmt org-email-link-description-format))
9067 (let* ((p org-store-link-plist)
9068 (to (plist-get p :toaddress))
9069 (from (plist-get p :fromaddress))
9070 (table
9071 (list
9072 (cons "%c" (plist-get p :fromto))
9073 (cons "%F" (plist-get p :from))
9074 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9075 (cons "%T" (plist-get p :to))
9076 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9077 (cons "%s" (plist-get p :subject))
9078 (cons "%d" (plist-get p :date))
9079 (cons "%m" (plist-get p :message-id)))))
9080 (when (string-match "%c" fmt)
9081 ;; Check if the user wrote this message
9082 (if (and org-from-is-user-regexp from to
9083 (save-match-data (string-match org-from-is-user-regexp from)))
9084 (setq fmt (replace-match "to %t" t t fmt))
9085 (setq fmt (replace-match "from %f" t t fmt))))
9086 (org-replace-escapes fmt table)))
9088 (defun org-make-org-heading-search-string (&optional string heading)
9089 "Make search string for STRING or current headline."
9090 (interactive)
9091 (let ((s (or string (org-get-heading)))
9092 (lines org-context-in-file-links))
9093 (unless (and string (not heading))
9094 ;; We are using a headline, clean up garbage in there.
9095 (if (string-match org-todo-regexp s)
9096 (setq s (replace-match "" t t s)))
9097 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9098 (setq s (replace-match "" t t s)))
9099 (setq s (org-trim s))
9100 (if (string-match (concat "^\\(" org-quote-string "\\|"
9101 org-comment-string "\\)") s)
9102 (setq s (replace-match "" t t s)))
9103 (while (string-match org-ts-regexp s)
9104 (setq s (replace-match "" t t s))))
9105 (or string (setq s (concat "*" s))) ; Add * for headlines
9106 (when (and string (integerp lines) (> lines 0))
9107 (let ((slines (org-split-string s "\n")))
9108 (when (< lines (length slines))
9109 (setq s (mapconcat
9110 'identity
9111 (reverse (nthcdr (- (length slines) lines)
9112 (reverse slines))) "\n")))))
9113 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9115 (defun org-make-link-string (link &optional description)
9116 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9117 (unless (string-match "\\S-" link)
9118 (error "Empty link"))
9119 (when (and description
9120 (stringp description)
9121 (not (string-match "\\S-" description)))
9122 (setq description nil))
9123 (when (stringp description)
9124 ;; Remove brackets from the description, they are fatal.
9125 (while (string-match "\\[" description)
9126 (setq description (replace-match "{" t t description)))
9127 (while (string-match "\\]" description)
9128 (setq description (replace-match "}" t t description))))
9129 (when (equal link description)
9130 ;; No description needed, it is identical
9131 (setq description nil))
9132 (when (and (not description)
9133 (not (string-match (org-image-file-name-regexp) link))
9134 (not (equal link (org-link-escape link))))
9135 (setq description (org-extract-attributes link)))
9136 (setq link
9137 (cond ((string-match (org-image-file-name-regexp) link) link)
9138 ((string-match org-link-types-re link)
9139 (concat (match-string 1 link)
9140 (org-link-escape (substring link (match-end 1)))))
9141 (t (org-link-escape link))))
9142 (concat "[[" link "]"
9143 (if description (concat "[" description "]") "")
9144 "]"))
9146 (defconst org-link-escape-chars
9147 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9148 "List of characters that should be escaped in link.
9149 This is the list that is used for internal purposes.")
9151 (defconst org-link-escape-chars-browser
9152 '(?\ )
9153 "List of escapes for characters that are problematic in links.
9154 This is the list that is used before handing over to the browser.")
9156 (defun org-link-escape (text &optional table merge)
9157 "Return percent escaped representation of TEXT.
9158 TEXT is a string with the text to escape.
9159 Optional argument TABLE is a list with characters that should be
9160 escaped. When nil, `org-link-escape-chars' is used.
9161 If optional argument MERGE is set, merge TABLE into
9162 `org-link-escape-chars'."
9163 (cond
9164 ((and table merge)
9165 (mapc (lambda (defchr)
9166 (unless (member defchr table)
9167 (setq table (cons defchr table)))) org-link-escape-chars))
9168 ((null table)
9169 (setq table org-link-escape-chars)))
9170 (mapconcat
9171 (lambda (char)
9172 (if (or (member char table)
9173 (and (or (< char 32) (= char 37) (> char 126))
9174 org-url-hexify-p))
9175 (mapconcat (lambda (sequence-element)
9176 (format "%%%.2X" sequence-element))
9177 (or (encode-coding-char char 'utf-8)
9178 (error "Unable to percent escape character: %s"
9179 (char-to-string char))) "")
9180 (char-to-string char))) text ""))
9182 (defun org-link-unescape (str)
9183 "Unhex hexified Unicode strings as returned from the JavaScript function
9184 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9185 (unless (and (null str) (string= "" str))
9186 (let ((pos 0) (case-fold-search t) unhexed)
9187 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9188 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9189 (setq str (replace-match unhexed t t str))
9190 (setq pos (+ pos (length unhexed))))))
9191 str)
9193 (defun org-link-unescape-compound (hex)
9194 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9195 Note: this function also decodes single byte encodings like
9196 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9197 (save-match-data
9198 (let* ((bytes (cdr (split-string hex "%")))
9199 (ret "")
9200 (eat 0)
9201 (sum 0))
9202 (while bytes
9203 (let* ((val (string-to-number (pop bytes) 16))
9204 (shift-xor
9205 (if (= 0 eat)
9206 (cond
9207 ((>= val 252) (cons 6 252))
9208 ((>= val 248) (cons 5 248))
9209 ((>= val 240) (cons 4 240))
9210 ((>= val 224) (cons 3 224))
9211 ((>= val 192) (cons 2 192))
9212 (t (cons 0 0)))
9213 (cons 6 128))))
9214 (if (>= val 192) (setq eat (car shift-xor)))
9215 (setq val (logxor val (cdr shift-xor)))
9216 (setq sum (+ (lsh sum (car shift-xor)) val))
9217 (if (> eat 0) (setq eat (- eat 1)))
9218 (cond
9219 ((= 0 eat) ;multi byte
9220 (setq ret (concat ret (org-char-to-string sum)))
9221 (setq sum 0))
9222 ((not bytes) ; single byte(s)
9223 (setq ret (org-link-unescape-single-byte-sequence hex))))
9224 )) ;; end (while bytes
9225 ret )))
9227 (defun org-link-unescape-single-byte-sequence (hex)
9228 "Unhexify hex-encoded single byte character sequences."
9229 (mapconcat (lambda (byte)
9230 (char-to-string (string-to-number byte 16)))
9231 (cdr (split-string hex "%")) ""))
9233 (defun org-xor (a b)
9234 "Exclusive or."
9235 (if a (not b) b))
9237 (defun org-fixup-message-id-for-http (s)
9238 "Replace special characters in a message id, so it can be used in an http query."
9239 (when (string-match "%" s)
9240 (setq s (mapconcat (lambda (c)
9241 (if (eq c ?%)
9242 "%25"
9243 (char-to-string c)))
9244 s "")))
9245 (while (string-match "<" s)
9246 (setq s (replace-match "%3C" t t s)))
9247 (while (string-match ">" s)
9248 (setq s (replace-match "%3E" t t s)))
9249 (while (string-match "@" s)
9250 (setq s (replace-match "%40" t t s)))
9253 (defun org-link-prettify (link)
9254 "Return a human-readable representation of LINK.
9255 The car of LINK must be a raw link the cdr of LINK must be either
9256 a link description or nil."
9257 (let ((desc (or (cadr link) "<no description>")))
9258 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9259 "<" (car link) ">")))
9261 ;;;###autoload
9262 (defun org-insert-link-global ()
9263 "Insert a link like Org-mode does.
9264 This command can be called in any mode to insert a link in Org-mode syntax."
9265 (interactive)
9266 (org-load-modules-maybe)
9267 (org-run-like-in-org-mode 'org-insert-link))
9269 (defun org-insert-all-links (&optional keep)
9270 "Insert all links in `org-stored-links'."
9271 (interactive "P")
9272 (let ((links (copy-sequence org-stored-links)) l)
9273 (while (setq l (if keep (pop links) (pop org-stored-links)))
9274 (insert "- ")
9275 (org-insert-link nil (car l) (cadr l))
9276 (insert "\n"))))
9278 (defun org-link-fontify-links-to-this-file ()
9279 "Fontify links to the current file in `org-stored-links'."
9280 (let ((f (buffer-file-name)) a b)
9281 (setq a (mapcar (lambda(l)
9282 (let ((ll (car l)))
9283 (when (and (string-match "^file:\\(.+\\)::" ll)
9284 (equal f (expand-file-name (match-string 1 ll))))
9285 ll)))
9286 org-stored-links))
9287 (when (featurep 'org-id)
9288 (setq b (mapcar (lambda(l)
9289 (let ((ll (car l)))
9290 (when (and (string-match "^id:\\(.+\\)$" ll)
9291 (equal f (expand-file-name
9292 (or (org-id-find-id-file
9293 (match-string 1 ll)) ""))))
9294 ll)))
9295 org-stored-links)))
9296 (mapcar (lambda(l)
9297 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9298 (delq nil (append a b)))))
9300 (defvar org-link-links-in-this-file nil)
9301 (defun org-insert-link (&optional complete-file link-location default-description)
9302 "Insert a link. At the prompt, enter the link.
9304 Completion can be used to insert any of the link protocol prefixes like
9305 http or ftp in use.
9307 The history can be used to select a link previously stored with
9308 `org-store-link'. When the empty string is entered (i.e. if you just
9309 press RET at the prompt), the link defaults to the most recently
9310 stored link. As SPC triggers completion in the minibuffer, you need to
9311 use M-SPC or C-q SPC to force the insertion of a space character.
9313 You will also be prompted for a description, and if one is given, it will
9314 be displayed in the buffer instead of the link.
9316 If there is already a link at point, this command will allow you to edit link
9317 and description parts.
9319 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9320 be selected using completion. The path to the file will be relative to the
9321 current directory if the file is in the current directory or a subdirectory.
9322 Otherwise, the link will be the absolute path as completed in the minibuffer
9323 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9324 option `org-link-file-path-type'.
9326 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9327 the current directory or below.
9329 With three \\[universal-argument] prefixes, negate the meaning of
9330 `org-keep-stored-link-after-insertion'.
9332 If `org-make-link-description-function' is non-nil, this function will be
9333 called with the link target, and the result will be the default
9334 link description.
9336 If the LINK-LOCATION parameter is non-nil, this value will be
9337 used as the link location instead of reading one interactively.
9339 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9340 be used as the default description."
9341 (interactive "P")
9342 (let* ((wcf (current-window-configuration))
9343 (region (if (org-region-active-p)
9344 (buffer-substring (region-beginning) (region-end))))
9345 (remove (and region (list (region-beginning) (region-end))))
9346 (desc region)
9347 tmphist ; byte-compile incorrectly complains about this
9348 (link link-location)
9349 (abbrevs org-link-abbrev-alist-local)
9350 entry file all-prefixes auto-desc)
9351 (cond
9352 (link-location) ; specified by arg, just use it.
9353 ((org-in-regexp org-bracket-link-regexp 1)
9354 ;; We do have a link at point, and we are going to edit it.
9355 (setq remove (list (match-beginning 0) (match-end 0)))
9356 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9357 (setq link (read-string "Link: "
9358 (org-link-unescape
9359 (org-match-string-no-properties 1)))))
9360 ((or (org-in-regexp org-angle-link-re)
9361 (org-in-regexp org-plain-link-re))
9362 ;; Convert to bracket link
9363 (setq remove (list (match-beginning 0) (match-end 0))
9364 link (read-string "Link: "
9365 (org-remove-angle-brackets (match-string 0)))))
9366 ((member complete-file '((4) (16)))
9367 ;; Completing read for file names.
9368 (setq link (org-file-complete-link complete-file)))
9370 ;; Read link, with completion for stored links.
9371 (org-link-fontify-links-to-this-file)
9372 (org-switch-to-buffer-other-window "*Org Links*")
9373 (with-current-buffer "*Org Links*"
9374 (erase-buffer)
9375 (insert "Insert a link.
9376 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9377 (when org-stored-links
9378 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9379 (insert (mapconcat 'org-link-prettify
9380 (reverse org-stored-links) "\n")))
9381 (goto-char (point-min)))
9382 (let ((cw (selected-window)))
9383 (select-window (get-buffer-window "*Org Links*" 'visible))
9384 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9385 (unless (pos-visible-in-window-p (point-max))
9386 (org-fit-window-to-buffer))
9387 (and (window-live-p cw) (select-window cw)))
9388 ;; Fake a link history, containing the stored links.
9389 (setq tmphist (append (mapcar 'car org-stored-links)
9390 org-insert-link-history))
9391 (setq all-prefixes (append (mapcar 'car abbrevs)
9392 (mapcar 'car org-link-abbrev-alist)
9393 org-link-types))
9394 (unwind-protect
9395 (progn
9396 (setq link
9397 (let ((org-completion-use-ido nil)
9398 (org-completion-use-iswitchb nil))
9399 (org-completing-read
9400 "Link: "
9401 (append
9402 (mapcar (lambda (x) (list (concat x ":")))
9403 all-prefixes)
9404 (mapcar 'car org-stored-links)
9405 (mapcar 'cadr org-stored-links))
9406 nil nil nil
9407 'tmphist
9408 (caar org-stored-links))))
9409 (if (not (string-match "\\S-" link))
9410 (error "No link selected"))
9411 (mapc (lambda(l)
9412 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9413 org-stored-links)
9414 (if (or (member link all-prefixes)
9415 (and (equal ":" (substring link -1))
9416 (member (substring link 0 -1) all-prefixes)
9417 (setq link (substring link 0 -1))))
9418 (setq link (org-link-try-special-completion link))))
9419 (set-window-configuration wcf)
9420 (kill-buffer "*Org Links*"))
9421 (setq entry (assoc link org-stored-links))
9422 (or entry (push link org-insert-link-history))
9423 (setq desc (or desc (nth 1 entry)))))
9425 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9426 (not org-keep-stored-link-after-insertion))
9427 (setq org-stored-links (delq (assoc link org-stored-links)
9428 org-stored-links)))
9430 (if (string-match org-plain-link-re link)
9431 ;; URL-like link, normalize the use of angular brackets.
9432 (setq link (org-remove-angle-brackets link)))
9434 ;; Check if we are linking to the current file with a search option
9435 ;; If yes, simplify the link by using only the search option.
9436 (when (and buffer-file-name
9437 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9438 (let* ((path (match-string 1 link))
9439 (case-fold-search nil)
9440 (search (match-string 2 link)))
9441 (save-match-data
9442 (if (equal (file-truename buffer-file-name) (file-truename path))
9443 ;; We are linking to this same file, with a search option
9444 (setq link search)))))
9446 ;; Check if we can/should use a relative path. If yes, simplify the link
9447 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9448 (let* ((type (match-string 1 link))
9449 (path (match-string 2 link))
9450 (origpath path)
9451 (case-fold-search nil))
9452 (cond
9453 ((or (eq org-link-file-path-type 'absolute)
9454 (equal complete-file '(16)))
9455 (setq path (abbreviate-file-name (expand-file-name path))))
9456 ((eq org-link-file-path-type 'noabbrev)
9457 (setq path (expand-file-name path)))
9458 ((eq org-link-file-path-type 'relative)
9459 (setq path (file-relative-name path)))
9461 (save-match-data
9462 (if (string-match (concat "^" (regexp-quote
9463 (expand-file-name
9464 (file-name-as-directory
9465 default-directory))))
9466 (expand-file-name path))
9467 ;; We are linking a file with relative path name.
9468 (setq path (substring (expand-file-name path)
9469 (match-end 0)))
9470 (setq path (abbreviate-file-name (expand-file-name path)))))))
9471 (setq link (concat type path))
9472 (if (equal desc origpath)
9473 (setq desc path))))
9475 (if org-make-link-description-function
9476 (setq desc
9477 (or (condition-case nil
9478 (funcall org-make-link-description-function link desc)
9479 (error (progn (message "Can't get link description from `%s'"
9480 (symbol-name org-make-link-description-function))
9481 (sit-for 2) nil)))
9482 (read-string "Description: " default-description)))
9483 (if default-description (setq desc default-description)
9484 (setq desc (or (and auto-desc desc)
9485 (read-string "Description: " desc)))))
9487 (unless (string-match "\\S-" desc) (setq desc nil))
9488 (if remove (apply 'delete-region remove))
9489 (insert (org-make-link-string link desc))))
9491 (defun org-link-try-special-completion (type)
9492 "If there is completion support for link type TYPE, offer it."
9493 (let ((fun (intern (concat "org-" type "-complete-link"))))
9494 (if (functionp fun)
9495 (funcall fun)
9496 (read-string "Link (no completion support): " (concat type ":")))))
9498 (defun org-file-complete-link (&optional arg)
9499 "Create a file link using completion."
9500 (let (file link)
9501 (setq file (read-file-name "File: "))
9502 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9503 (pwd1 (file-name-as-directory (abbreviate-file-name
9504 (expand-file-name ".")))))
9505 (cond
9506 ((equal arg '(16))
9507 (setq link (concat
9508 "file:"
9509 (abbreviate-file-name (expand-file-name file)))))
9510 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9511 (setq link (concat "file:" (match-string 1 file))))
9512 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9513 (expand-file-name file))
9514 (setq link (concat
9515 "file:" (match-string 1 (expand-file-name file)))))
9516 (t (setq link (concat "file:" file)))))
9517 link))
9519 (defun org-completing-read (&rest args)
9520 "Completing-read with SPACE being a normal character."
9521 (let ((enable-recursive-minibuffers t)
9522 (minibuffer-local-completion-map
9523 (copy-keymap minibuffer-local-completion-map)))
9524 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9525 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9526 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9527 (apply 'org-icompleting-read args)))
9529 (defun org-completing-read-no-i (&rest args)
9530 (let (org-completion-use-ido org-completion-use-iswitchb)
9531 (apply 'org-completing-read args)))
9533 (defun org-iswitchb-completing-read (prompt choices &rest args)
9534 "Use iswitch as a completing-read replacement to choose from choices.
9535 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9536 from."
9537 (let* ((iswitchb-use-virtual-buffers nil)
9538 (iswitchb-make-buflist-hook
9539 (lambda ()
9540 (setq iswitchb-temp-buflist choices))))
9541 (iswitchb-read-buffer prompt)))
9543 (defun org-icompleting-read (&rest args)
9544 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9545 (org-without-partial-completion
9546 (if (and org-completion-use-ido
9547 (fboundp 'ido-completing-read)
9548 (boundp 'ido-mode) ido-mode
9549 (listp (second args)))
9550 (let ((ido-enter-matching-directory nil))
9551 (apply 'ido-completing-read (concat (car args))
9552 (if (consp (car (nth 1 args)))
9553 (mapcar 'car (nth 1 args))
9554 (nth 1 args))
9555 (cddr args)))
9556 (if (and org-completion-use-iswitchb
9557 (boundp 'iswitchb-mode) iswitchb-mode
9558 (listp (second args)))
9559 (apply 'org-iswitchb-completing-read (concat (car args))
9560 (if (consp (car (nth 1 args)))
9561 (mapcar 'car (nth 1 args))
9562 (nth 1 args))
9563 (cddr args))
9564 (apply 'completing-read args)))))
9566 (defun org-extract-attributes (s)
9567 "Extract the attributes cookie from a string and set as text property."
9568 (let (a attr (start 0) key value)
9569 (save-match-data
9570 (when (string-match "{{\\([^}]+\\)}}$" s)
9571 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9572 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9573 (setq key (match-string 1 a) value (match-string 2 a)
9574 start (match-end 0)
9575 attr (plist-put attr (intern key) value))))
9576 (org-add-props s nil 'org-attr attr))
9579 (defun org-extract-attributes-from-string (tag)
9580 (let (key value attr)
9581 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9582 (setq key (match-string 1 tag) value (match-string 2 tag)
9583 tag (replace-match "" t t tag)
9584 attr (plist-put attr (intern key) value)))
9585 (cons tag attr)))
9587 (defun org-attributes-to-string (plist)
9588 "Format a property list into an HTML attribute list."
9589 (let ((s "") key value)
9590 (while plist
9591 (setq key (pop plist) value (pop plist))
9592 (and value
9593 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9596 ;;; Opening/following a link
9598 (defvar org-link-search-failed nil)
9600 (defvar org-open-link-functions nil
9601 "Hook for functions finding a plain text link.
9602 These functions must take a single argument, the link content.
9603 They will be called for links that look like [[link text][description]]
9604 when LINK TEXT does not have a protocol like \"http:\" and does not look
9605 like a filename (e.g. \"./blue.png\").
9607 These functions will be called *before* Org attempts to resolve the
9608 link by doing text searches in the current buffer - so if you want a
9609 link \"[[target]]\" to still find \"<<target>>\", your function should
9610 handle this as a special case.
9612 When the function does handle the link, it must return a non-nil value.
9613 If it decides that it is not responsible for this link, it must return
9614 nil to indicate that that Org-mode can continue with other options
9615 like exact and fuzzy text search.")
9617 (defun org-next-link ()
9618 "Move forward to the next link.
9619 If the link is in hidden text, expose it."
9620 (interactive)
9621 (when (and org-link-search-failed (eq this-command last-command))
9622 (goto-char (point-min))
9623 (message "Link search wrapped back to beginning of buffer"))
9624 (setq org-link-search-failed nil)
9625 (let* ((pos (point))
9626 (ct (org-context))
9627 (a (assoc :link ct)))
9628 (if a (goto-char (nth 2 a)))
9629 (if (re-search-forward org-any-link-re nil t)
9630 (progn
9631 (goto-char (match-beginning 0))
9632 (if (outline-invisible-p) (org-show-context)))
9633 (goto-char pos)
9634 (setq org-link-search-failed t)
9635 (error "No further link found"))))
9637 (defun org-previous-link ()
9638 "Move backward to the previous link.
9639 If the link is in hidden text, expose it."
9640 (interactive)
9641 (when (and org-link-search-failed (eq this-command last-command))
9642 (goto-char (point-max))
9643 (message "Link search wrapped back to end of buffer"))
9644 (setq org-link-search-failed nil)
9645 (let* ((pos (point))
9646 (ct (org-context))
9647 (a (assoc :link ct)))
9648 (if a (goto-char (nth 1 a)))
9649 (if (re-search-backward org-any-link-re nil t)
9650 (progn
9651 (goto-char (match-beginning 0))
9652 (if (outline-invisible-p) (org-show-context)))
9653 (goto-char pos)
9654 (setq org-link-search-failed t)
9655 (error "No further link found"))))
9657 (defun org-translate-link (s)
9658 "Translate a link string if a translation function has been defined."
9659 (if (and org-link-translation-function
9660 (fboundp org-link-translation-function)
9661 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9662 (progn
9663 (setq s (funcall org-link-translation-function
9664 (match-string 1 s) (match-string 2 s)))
9665 (concat (car s) ":" (cdr s)))
9668 (defun org-translate-link-from-planner (type path)
9669 "Translate a link from Emacs Planner syntax so that Org can follow it.
9670 This is still an experimental function, your mileage may vary."
9671 (cond
9672 ((member type '("http" "https" "news" "ftp"))
9673 ;; standard Internet links are the same.
9674 nil)
9675 ((and (equal type "irc") (string-match "^//" path))
9676 ;; Planner has two / at the beginning of an irc link, we have 1.
9677 ;; We should have zero, actually....
9678 (setq path (substring path 1)))
9679 ((and (equal type "lisp") (string-match "^/" path))
9680 ;; Planner has a slash, we do not.
9681 (setq type "elisp" path (substring path 1)))
9682 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9683 ;; A typical message link. Planner has the id after the final slash,
9684 ;; we separate it with a hash mark
9685 (setq path (concat (match-string 1 path) "#"
9686 (org-remove-angle-brackets (match-string 2 path)))))
9688 (cons type path))
9690 (defun org-find-file-at-mouse (ev)
9691 "Open file link or URL at mouse."
9692 (interactive "e")
9693 (mouse-set-point ev)
9694 (org-open-at-point 'in-emacs))
9696 (defun org-open-at-mouse (ev)
9697 "Open file link or URL at mouse.
9698 See the docstring of `org-open-file' for details."
9699 (interactive "e")
9700 (mouse-set-point ev)
9701 (if (eq major-mode 'org-agenda-mode)
9702 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9703 (org-open-at-point))
9705 (defvar org-window-config-before-follow-link nil
9706 "The window configuration before following a link.
9707 This is saved in case the need arises to restore it.")
9709 (defvar org-open-link-marker (make-marker)
9710 "Marker pointing to the location where `org-open-at-point; was called.")
9712 ;;;###autoload
9713 (defun org-open-at-point-global ()
9714 "Follow a link like Org-mode does.
9715 This command can be called in any mode to follow a link that has
9716 Org-mode syntax."
9717 (interactive)
9718 (org-run-like-in-org-mode 'org-open-at-point))
9720 ;;;###autoload
9721 (defun org-open-link-from-string (s &optional arg reference-buffer)
9722 "Open a link in the string S, as if it was in Org-mode."
9723 (interactive "sLink: \nP")
9724 (let ((reference-buffer (or reference-buffer (current-buffer))))
9725 (with-temp-buffer
9726 (let ((org-inhibit-startup (not reference-buffer)))
9727 (org-mode)
9728 (insert s)
9729 (goto-char (point-min))
9730 (when reference-buffer
9731 (setq org-link-abbrev-alist-local
9732 (with-current-buffer reference-buffer
9733 org-link-abbrev-alist-local)))
9734 (org-open-at-point arg reference-buffer)))))
9736 (defvar org-open-at-point-functions nil
9737 "Hook that is run when following a link at point.
9739 Functions in this hook must return t if they identify and follow
9740 a link at point. If they don't find anything interesting at point,
9741 they must return nil.")
9743 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9744 (defun org-open-at-point (&optional arg reference-buffer)
9745 "Open link at or after point.
9746 If there is no link at point, this function will search forward up to
9747 the end of the current line.
9748 Normally, files will be opened by an appropriate application. If the
9749 optional prefix argument ARG is non-nil, Emacs will visit the file.
9750 With a double prefix argument, try to open outside of Emacs, in the
9751 application the system uses for this file type."
9752 (interactive "P")
9753 ;; if in a code block, then open the block's results
9754 (unless (call-interactively #'org-babel-open-src-block-result)
9755 (org-load-modules-maybe)
9756 (move-marker org-open-link-marker (point))
9757 (setq org-window-config-before-follow-link (current-window-configuration))
9758 (org-remove-occur-highlights nil nil t)
9759 (cond
9760 ((and (org-at-heading-p)
9761 (not (org-at-timestamp-p t))
9762 (not (org-in-regexp
9763 (concat org-plain-link-re "\\|"
9764 org-bracket-link-regexp "\\|"
9765 org-angle-link-re "\\|"
9766 "[ \t]:[^ \t\n]+:[ \t]*$")))
9767 (not (get-text-property (point) 'org-linked-text)))
9768 (or (org-offer-links-in-entry arg)
9769 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9770 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9771 ((and (org-at-timestamp-p t)
9772 (not (org-in-regexp org-bracket-link-regexp)))
9773 (org-follow-timestamp-link))
9774 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9775 (not (org-in-regexp org-bracket-link-regexp)))
9776 (org-footnote-action))
9778 (let (type path link line search (pos (point)))
9779 (catch 'match
9780 (save-excursion
9781 (skip-chars-forward "^]\n\r")
9782 (when (org-in-regexp org-bracket-link-regexp 1)
9783 (setq link (org-extract-attributes
9784 (org-link-unescape (org-match-string-no-properties 1))))
9785 (while (string-match " *\n *" link)
9786 (setq link (replace-match " " t t link)))
9787 (setq link (org-link-expand-abbrev link))
9788 (cond
9789 ((or (file-name-absolute-p link)
9790 (string-match "^\\.\\.?/" link))
9791 (setq type "file" path link))
9792 ((string-match org-link-re-with-space3 link)
9793 (setq type (match-string 1 link) path (match-string 2 link)))
9794 ((string-match "^help:+\\(.+\\)" link)
9795 (setq type "help" path (match-string 1 link)))
9796 (t (setq type "thisfile" path link)))
9797 (throw 'match t)))
9799 (when (get-text-property (point) 'org-linked-text)
9800 (setq type "thisfile"
9801 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9802 (1+ (point)) (point))
9803 path (buffer-substring
9804 (or (previous-single-property-change pos 'org-linked-text)
9805 (point-min))
9806 (or (next-single-property-change pos 'org-linked-text)
9807 (point-max))))
9808 (throw 'match t))
9810 (save-excursion
9811 (when (or (org-in-regexp org-angle-link-re)
9812 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9813 (save-match-data (not (looking-back "\\[\\[")))))
9814 (setq type (match-string 1)
9815 path (org-link-unescape (match-string 2)))
9816 (throw 'match t)))
9817 (save-excursion
9818 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9819 (setq type "tags"
9820 path (match-string 1))
9821 (while (string-match ":" path)
9822 (setq path (replace-match "+" t t path)))
9823 (throw 'match t)))
9824 (when (org-in-regexp "<\\([^><\n]+\\)>")
9825 (setq type "tree-match"
9826 path (match-string 1))
9827 (throw 'match t)))
9828 (unless path
9829 (error "No link found"))
9831 ;; switch back to reference buffer
9832 ;; needed when if called in a temporary buffer through
9833 ;; org-open-link-from-string
9834 (with-current-buffer (or reference-buffer (current-buffer))
9836 ;; Remove any trailing spaces in path
9837 (if (string-match " +\\'" path)
9838 (setq path (replace-match "" t t path)))
9839 (if (and org-link-translation-function
9840 (fboundp org-link-translation-function))
9841 ;; Check if we need to translate the link
9842 (let ((tmp (funcall org-link-translation-function type path)))
9843 (setq type (car tmp) path (cdr tmp))))
9845 (cond
9847 ((assoc type org-link-protocols)
9848 (funcall (nth 1 (assoc type org-link-protocols)) path))
9850 ((equal type "help")
9851 (let ((f-or-v (intern path)))
9852 (cond ((fboundp f-or-v)
9853 (describe-function f-or-v))
9854 ((boundp f-or-v)
9855 (describe-variable f-or-v))
9856 (t (error "Not a known function or variable")))))
9858 ((equal type "mailto")
9859 (let ((cmd (car org-link-mailto-program))
9860 (args (cdr org-link-mailto-program)) args1
9861 (address path) (subject "") a)
9862 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9863 (setq address (match-string 1 path)
9864 subject (org-link-escape (match-string 2 path))))
9865 (while args
9866 (cond
9867 ((not (stringp (car args))) (push (pop args) args1))
9868 (t (setq a (pop args))
9869 (if (string-match "%a" a)
9870 (setq a (replace-match address t t a)))
9871 (if (string-match "%s" a)
9872 (setq a (replace-match subject t t a)))
9873 (push a args1))))
9874 (apply cmd (nreverse args1))))
9876 ((member type '("http" "https" "ftp" "news"))
9877 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9878 (org-link-escape
9879 path org-link-escape-chars-browser)
9880 path))))
9882 ((string= type "doi")
9883 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9884 (org-link-escape
9885 path org-link-escape-chars-browser)
9886 path))))
9888 ((member type '("message"))
9889 (browse-url (concat type ":" path)))
9891 ((string= type "tags")
9892 (org-tags-view arg path))
9894 ((string= type "tree-match")
9895 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9897 ((string= type "file")
9898 (if (string-match "::\\([0-9]+\\)\\'" path)
9899 (setq line (string-to-number (match-string 1 path))
9900 path (substring path 0 (match-beginning 0)))
9901 (if (string-match "::\\(.+\\)\\'" path)
9902 (setq search (match-string 1 path)
9903 path (substring path 0 (match-beginning 0)))))
9904 (if (string-match "[*?{]" (file-name-nondirectory path))
9905 (dired path)
9906 (org-open-file path arg line search)))
9908 ((string= type "shell")
9909 (let ((buf (generate-new-buffer "*Org Shell Output"))
9910 (cmd path))
9911 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9912 (string-match org-confirm-shell-link-not-regexp cmd))
9913 (not org-confirm-shell-link-function)
9914 (funcall org-confirm-shell-link-function
9915 (format "Execute \"%s\" in shell? "
9916 (org-add-props cmd nil
9917 'face 'org-warning))))
9918 (progn
9919 (message "Executing %s" cmd)
9920 (shell-command cmd buf)
9921 (if (featurep 'midnight)
9922 (setq clean-buffer-list-kill-buffer-names
9923 (cons buf clean-buffer-list-kill-buffer-names))))
9924 (error "Abort"))))
9926 ((string= type "elisp")
9927 (let ((cmd path))
9928 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9929 (string-match org-confirm-elisp-link-not-regexp cmd))
9930 (not org-confirm-elisp-link-function)
9931 (funcall org-confirm-elisp-link-function
9932 (format "Execute \"%s\" as elisp? "
9933 (org-add-props cmd nil
9934 'face 'org-warning))))
9935 (message "%s => %s" cmd
9936 (if (equal (string-to-char cmd) ?\()
9937 (eval (read cmd))
9938 (call-interactively (read cmd))))
9939 (error "Abort"))))
9941 ((and (string= type "thisfile")
9942 (run-hook-with-args-until-success
9943 'org-open-link-functions path)))
9945 ((string= type "thisfile")
9946 (if arg
9947 (switch-to-buffer-other-window
9948 (org-get-buffer-for-internal-link (current-buffer)))
9949 (org-mark-ring-push))
9950 (let ((cmd `(org-link-search
9951 ,path
9952 ,(cond ((equal arg '(4)) ''occur)
9953 ((equal arg '(16)) ''org-occur))
9954 ,pos)))
9955 (condition-case nil (let ((org-link-search-inhibit-query t))
9956 (eval cmd))
9957 (error (progn (widen) (eval cmd))))))
9959 (t (browse-url-at-point)))))))
9960 (move-marker org-open-link-marker nil)
9961 (run-hook-with-args 'org-follow-link-hook)))
9963 (defun org-offer-links-in-entry (&optional nth zero)
9964 "Offer links in the current entry and follow the selected link.
9965 If there is only one link, follow it immediately as well.
9966 If NTH is an integer, immediately pick the NTH link found.
9967 If ZERO is a string, check also this string for a link, and if
9968 there is one, offer it as link number zero."
9969 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9970 "\\(" org-angle-link-re "\\)\\|"
9971 "\\(" org-plain-link-re "\\)"))
9972 (cnt ?0)
9973 (in-emacs (if (integerp nth) nil nth))
9974 have-zero end links link c)
9975 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9976 (push (match-string 0 zero) links)
9977 (setq cnt (1- cnt) have-zero t))
9978 (save-excursion
9979 (org-back-to-heading t)
9980 (setq end (save-excursion (outline-next-heading) (point)))
9981 (while (re-search-forward re end t)
9982 (push (match-string 0) links))
9983 (setq links (org-uniquify (reverse links))))
9985 (cond
9986 ((null links)
9987 (message "No links"))
9988 ((equal (length links) 1)
9989 (setq link (list (car links))))
9990 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9991 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9992 (t ; we have to select a link
9993 (save-excursion
9994 (save-window-excursion
9995 (delete-other-windows)
9996 (with-output-to-temp-buffer "*Select Link*"
9997 (mapc (lambda (l)
9998 (if (not (string-match org-bracket-link-regexp l))
9999 (princ (format "[%c] %s\n" (incf cnt)
10000 (org-remove-angle-brackets l)))
10001 (if (match-end 3)
10002 (princ (format "[%c] %s (%s)\n" (incf cnt)
10003 (match-string 3 l) (match-string 1 l)))
10004 (princ (format "[%c] %s\n" (incf cnt)
10005 (match-string 1 l))))))
10006 links))
10007 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10008 (message "Select link to open, RET to open all:")
10009 (setq c (read-char-exclusive))
10010 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10011 (when (equal c ?q) (error "Abort"))
10012 (if (equal c ?\C-m)
10013 (setq link links)
10014 (setq nth (- c ?0))
10015 (if have-zero (setq nth (1+ nth)))
10016 (unless (and (integerp nth) (>= (length links) nth))
10017 (error "Invalid link selection"))
10018 (setq link (list (nth (1- nth) links))))))
10019 (if link
10020 (let ((buf (current-buffer)))
10021 (dolist (l link)
10022 (org-open-link-from-string l in-emacs buf))
10024 nil)))
10026 ;; Add special file links that specify the way of opening
10028 (org-add-link-type "file+sys" 'org-open-file-with-system)
10029 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10030 (defun org-open-file-with-system (path)
10031 "Open file at PATH using the system way of opening it."
10032 (org-open-file path 'system))
10033 (defun org-open-file-with-emacs (path)
10034 "Open file at PATH in Emacs."
10035 (org-open-file path 'emacs))
10036 (defun org-remove-file-link-modifiers ()
10037 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10038 (goto-char (point-min))
10039 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10040 (org-if-unprotected
10041 (replace-match "file:" t t))))
10042 (eval-after-load "org-exp"
10043 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10044 'org-remove-file-link-modifiers))
10046 ;;;; Time estimates
10048 (defun org-get-effort (&optional pom)
10049 "Get the effort estimate for the current entry."
10050 (org-entry-get pom org-effort-property))
10052 ;;; File search
10054 (defvar org-create-file-search-functions nil
10055 "List of functions to construct the right search string for a file link.
10056 These functions are called in turn with point at the location to
10057 which the link should point.
10059 A function in the hook should first test if it would like to
10060 handle this file type, for example by checking the `major-mode'
10061 or the file extension. If it decides not to handle this file, it
10062 should just return nil to give other functions a chance. If it
10063 does handle the file, it must return the search string to be used
10064 when following the link. The search string will be part of the
10065 file link, given after a double colon, and `org-open-at-point'
10066 will automatically search for it. If special measures must be
10067 taken to make the search successful, another function should be
10068 added to the companion hook `org-execute-file-search-functions',
10069 which see.
10071 A function in this hook may also use `setq' to set the variable
10072 `description' to provide a suggestion for the descriptive text to
10073 be used for this link when it gets inserted into an Org-mode
10074 buffer with \\[org-insert-link].")
10076 (defvar org-execute-file-search-functions nil
10077 "List of functions to execute a file search triggered by a link.
10079 Functions added to this hook must accept a single argument, the
10080 search string that was part of the file link, the part after the
10081 double colon. The function must first check if it would like to
10082 handle this search, for example by checking the `major-mode' or
10083 the file extension. If it decides not to handle this search, it
10084 should just return nil to give other functions a chance. If it
10085 does handle the search, it must return a non-nil value to keep
10086 other functions from trying.
10088 Each function can access the current prefix argument through the
10089 variable `current-prefix-argument'. Note that a single prefix is
10090 used to force opening a link in Emacs, so it may be good to only
10091 use a numeric or double prefix to guide the search function.
10093 In case this is needed, a function in this hook can also restore
10094 the window configuration before `org-open-at-point' was called using:
10096 (set-window-configuration org-window-config-before-follow-link)")
10098 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10099 (defun org-link-search (s &optional type avoid-pos stealth)
10100 "Search for a link search option.
10101 If S is surrounded by forward slashes, it is interpreted as a
10102 regular expression. In org-mode files, this will create an `org-occur'
10103 sparse tree. In ordinary files, `occur' will be used to list matches.
10104 If the current buffer is in `dired-mode', grep will be used to search
10105 in all files. If AVOID-POS is given, ignore matches near that position.
10107 When optional argument STEALTH is non-nil, do not modify
10108 visibility around point, thus ignoring
10109 `org-show-hierarchy-above', `org-show-following-heading' and
10110 `org-show-siblings' variables."
10111 (let ((case-fold-search t)
10112 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10113 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10114 (append '(("") (" ") ("\t") ("\n"))
10115 org-emphasis-alist)
10116 "\\|") "\\)"))
10117 (pos (point))
10118 (pre nil) (post nil)
10119 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10120 (cond
10121 ;; First check if there are any special search functions
10122 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10123 ;; Now try the builtin stuff
10124 ((and (equal (string-to-char s0) ?#)
10125 (> (length s0) 1)
10126 (save-excursion
10127 (goto-char (point-min))
10128 (and
10129 (re-search-forward
10130 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10131 (setq type 'dedicated
10132 pos (match-beginning 0))))
10133 ;; There is an exact target for this
10134 (goto-char pos)
10135 (org-back-to-heading t)))
10136 ((save-excursion
10137 (goto-char (point-min))
10138 (and
10139 (re-search-forward
10140 (concat "<<" (regexp-quote s0) ">>") nil t)
10141 (setq type 'dedicated
10142 pos (match-beginning 0))))
10143 ;; There is an exact target for this
10144 (goto-char pos))
10145 ((save-excursion
10146 (goto-char (point-min))
10147 (and
10148 (re-search-forward
10149 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10150 (setq type 'dedicated pos (match-beginning 0))))
10151 ;; Found an invisible target.
10152 (goto-char pos))
10153 ((save-excursion
10154 (goto-char (point-min))
10155 (and
10156 (re-search-forward
10157 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10158 (setq type 'dedicated pos (match-beginning 0))))
10159 ;; Found an element with a matching #+name affiliated keyword.
10160 (goto-char pos))
10161 ((and (string-match "^(\\(.*\\))$" s0)
10162 (save-excursion
10163 (goto-char (point-min))
10164 (and
10165 (re-search-forward
10166 (concat "[^[]" (regexp-quote
10167 (format org-coderef-label-format
10168 (match-string 1 s0))))
10169 nil t)
10170 (setq type 'dedicated
10171 pos (1+ (match-beginning 0))))))
10172 ;; There is a coderef target for this
10173 (goto-char pos))
10174 ((string-match "^/\\(.*\\)/$" s)
10175 ;; A regular expression
10176 (cond
10177 ((derived-mode-p 'org-mode)
10178 (org-occur (match-string 1 s)))
10179 ;;((eq major-mode 'dired-mode)
10180 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10181 (t (org-do-occur (match-string 1 s)))))
10182 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10183 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10184 (goto-char (point-min))
10185 (cond
10186 ((let (case-fold-search)
10187 (re-search-forward (format org-complex-heading-regexp-format
10188 (regexp-quote s))
10189 nil t))
10190 ;; OK, found a match
10191 (setq type 'dedicated)
10192 (goto-char (match-beginning 0)))
10193 ((and (not org-link-search-inhibit-query)
10194 (eq org-link-search-must-match-exact-headline 'query-to-create)
10195 (y-or-n-p "No match - create this as a new heading? "))
10196 (goto-char (point-max))
10197 (or (bolp) (newline))
10198 (insert "* " s "\n")
10199 (beginning-of-line 0))
10201 (goto-char pos)
10202 (error "No match"))))
10204 ;; A normal search string
10205 (when (equal (string-to-char s) ?*)
10206 ;; Anchor on headlines, post may include tags.
10207 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10208 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10209 s (substring s 1)))
10210 (remove-text-properties
10211 0 (length s)
10212 '(face nil mouse-face nil keymap nil fontified nil) s)
10213 ;; Make a series of regular expressions to find a match
10214 (setq words (org-split-string s "[ \n\r\t]+")
10216 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10217 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10218 "\\)" markers)
10219 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10220 re2a (concat "[ \t\r\n]" re2a_)
10221 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10222 re4 (concat "[^a-zA-Z_]" re4_)
10224 re1 (concat pre re2 post)
10225 re3 (concat pre (if pre re4_ re4) post)
10226 re5 (concat pre ".*" re4)
10227 re2 (concat pre re2)
10228 re2a (concat pre (if pre re2a_ re2a))
10229 re4 (concat pre (if pre re4_ re4))
10230 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10231 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10232 re5 "\\)"
10234 (cond
10235 ((eq type 'org-occur) (org-occur reall))
10236 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10237 (t (goto-char (point-min))
10238 (setq type 'fuzzy)
10239 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10240 (org-search-not-self 1 re1 nil t)
10241 (org-search-not-self 1 re2 nil t)
10242 (org-search-not-self 1 re2a nil t)
10243 (org-search-not-self 1 re3 nil t)
10244 (org-search-not-self 1 re4 nil t)
10245 (org-search-not-self 1 re5 nil t)
10247 (goto-char (match-beginning 1))
10248 (goto-char pos)
10249 (error "No match"))))))
10250 (and (derived-mode-p 'org-mode)
10251 (not stealth)
10252 (org-show-context 'link-search))
10253 type))
10255 (defun org-search-not-self (group &rest args)
10256 "Execute `re-search-forward', but only accept matches that do not
10257 enclose the position of `org-open-link-marker'."
10258 (let ((m org-open-link-marker))
10259 (catch 'exit
10260 (while (apply 're-search-forward args)
10261 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10262 (goto-char (match-end group))
10263 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10264 (> (match-beginning 0) (marker-position m))
10265 (< (match-end 0) (marker-position m)))
10266 (save-match-data
10267 (or (not (org-in-regexp
10268 org-bracket-link-analytic-regexp 1))
10269 (not (match-end 4)) ; no description
10270 (and (<= (match-beginning 4) (point))
10271 (>= (match-end 4) (point))))))
10272 (throw 'exit (point))))))))
10274 (defun org-get-buffer-for-internal-link (buffer)
10275 "Return a buffer to be used for displaying the link target of internal links."
10276 (cond
10277 ((not org-display-internal-link-with-indirect-buffer)
10278 buffer)
10279 ((string-match "(Clone)$" (buffer-name buffer))
10280 (message "Buffer is already a clone, not making another one")
10281 ;; we also do not modify visibility in this case
10282 buffer)
10283 (t ; make a new indirect buffer for displaying the link
10284 (let* ((bn (buffer-name buffer))
10285 (ibn (concat bn "(Clone)"))
10286 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10287 (with-current-buffer ib (org-overview))
10288 ib))))
10290 (defun org-do-occur (regexp &optional cleanup)
10291 "Call the Emacs command `occur'.
10292 If CLEANUP is non-nil, remove the printout of the regular expression
10293 in the *Occur* buffer. This is useful if the regex is long and not useful
10294 to read."
10295 (occur regexp)
10296 (when cleanup
10297 (let ((cwin (selected-window)) win beg end)
10298 (when (setq win (get-buffer-window "*Occur*"))
10299 (select-window win))
10300 (goto-char (point-min))
10301 (when (re-search-forward "match[a-z]+" nil t)
10302 (setq beg (match-end 0))
10303 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10304 (setq end (1- (match-beginning 0)))))
10305 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10306 (goto-char (point-min))
10307 (select-window cwin))))
10309 ;;; The mark ring for links jumps
10311 (defvar org-mark-ring nil
10312 "Mark ring for positions before jumps in Org-mode.")
10313 (defvar org-mark-ring-last-goto nil
10314 "Last position in the mark ring used to go back.")
10315 ;; Fill and close the ring
10316 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10317 (loop for i from 1 to org-mark-ring-length do
10318 (push (make-marker) org-mark-ring))
10319 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10320 org-mark-ring)
10322 (defun org-mark-ring-push (&optional pos buffer)
10323 "Put the current position or POS into the mark ring and rotate it."
10324 (interactive)
10325 (setq pos (or pos (point)))
10326 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10327 (move-marker (car org-mark-ring)
10328 (or pos (point))
10329 (or buffer (current-buffer)))
10330 (message "%s"
10331 (substitute-command-keys
10332 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10334 (defun org-mark-ring-goto (&optional n)
10335 "Jump to the previous position in the mark ring.
10336 With prefix arg N, jump back that many stored positions. When
10337 called several times in succession, walk through the entire ring.
10338 Org-mode commands jumping to a different position in the current file,
10339 or to another Org-mode file, automatically push the old position
10340 onto the ring."
10341 (interactive "p")
10342 (let (p m)
10343 (if (eq last-command this-command)
10344 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10345 (setq p org-mark-ring))
10346 (setq org-mark-ring-last-goto p)
10347 (setq m (car p))
10348 (org-pop-to-buffer-same-window (marker-buffer m))
10349 (goto-char m)
10350 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10352 (defun org-remove-angle-brackets (s)
10353 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10354 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10356 (defun org-add-angle-brackets (s)
10357 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10358 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10360 (defun org-remove-double-quotes (s)
10361 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10362 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10365 ;;; Following specific links
10367 (defun org-follow-timestamp-link ()
10368 "Open an agenda view for the time-stamp date/range at point."
10369 (cond
10370 ((org-at-date-range-p t)
10371 (let ((org-agenda-start-on-weekday)
10372 (t1 (match-string 1))
10373 (t2 (match-string 2)) tt1 tt2)
10374 (setq tt1 (time-to-days (org-time-string-to-time t1))
10375 tt2 (time-to-days (org-time-string-to-time t2)))
10376 (let ((org-agenda-buffer-tmp-name
10377 (format "*Org Agenda(a:%s)"
10378 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10379 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10380 ((org-at-timestamp-p t)
10381 (let ((org-agenda-buffer-tmp-name
10382 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10383 (org-agenda-list nil (time-to-days (org-time-string-to-time
10384 (substring (match-string 1) 0 10)))
10385 1)))
10386 (t (error "This should not happen"))))
10389 ;;; Following file links
10390 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10391 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10392 (declare-function mailcap-mime-info
10393 "mailcap" (string &optional request no-decode))
10394 (defvar org-wait nil)
10395 (defun org-open-file (path &optional in-emacs line search)
10396 "Open the file at PATH.
10397 First, this expands any special file name abbreviations. Then the
10398 configuration variable `org-file-apps' is checked if it contains an
10399 entry for this file type, and if yes, the corresponding command is launched.
10401 If no application is found, Emacs simply visits the file.
10403 With optional prefix argument IN-EMACS, Emacs will visit the file.
10404 With a double \\[universal-argument] \\[universal-argument] \
10405 prefix arg, Org tries to avoid opening in Emacs
10406 and to use an external application to visit the file.
10408 Optional LINE specifies a line to go to, optional SEARCH a string
10409 to search for. If LINE or SEARCH is given, the file will be
10410 opened in Emacs, unless an entry from org-file-apps that makes
10411 use of groups in a regexp matches.
10413 If you want to change the way frames are used when following a
10414 link, please customize `org-link-frame-setup'.
10416 If the file does not exist, an error is thrown."
10417 (let* ((file (if (equal path "")
10418 buffer-file-name
10419 (substitute-in-file-name (expand-file-name path))))
10420 (file-apps (append org-file-apps (org-default-apps)))
10421 (apps (org-remove-if
10422 'org-file-apps-entry-match-against-dlink-p file-apps))
10423 (apps-dlink (org-remove-if-not
10424 'org-file-apps-entry-match-against-dlink-p file-apps))
10425 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10426 (dirp (if remp nil (file-directory-p file)))
10427 (file (if (and dirp org-open-directory-means-index-dot-org)
10428 (concat (file-name-as-directory file) "index.org")
10429 file))
10430 (a-m-a-p (assq 'auto-mode apps))
10431 (dfile (downcase file))
10432 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10433 (link (cond ((and (eq line nil)
10434 (eq search nil))
10435 file)
10436 (line
10437 (concat file "::" (number-to-string line)))
10438 (search
10439 (concat file "::" search))))
10440 (dlink (downcase link))
10441 (old-buffer (current-buffer))
10442 (old-pos (point))
10443 (old-mode major-mode)
10444 ext cmd link-match-data)
10445 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10446 (setq ext (match-string 1 dfile))
10447 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10448 (setq ext (match-string 1 dfile))))
10449 (cond
10450 ((member in-emacs '((16) system))
10451 (setq cmd (cdr (assoc 'system apps))))
10452 (in-emacs (setq cmd 'emacs))
10454 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10455 (and dirp (cdr (assoc 'directory apps)))
10456 ; first, try matching against apps-dlink
10457 ; if we get a match here, store the match data for later
10458 (let ((match (assoc-default dlink apps-dlink
10459 'string-match)))
10460 (if match
10461 (progn (setq link-match-data (match-data))
10462 match)
10463 (progn (setq in-emacs (or in-emacs line search))
10464 nil))) ; if we have no match in apps-dlink,
10465 ; always open the file in emacs if line or search
10466 ; is given (for backwards compatibility)
10467 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10468 'string-match)
10469 (cdr (assoc ext apps))
10470 (cdr (assoc t apps))))))
10471 (when (eq cmd 'system)
10472 (setq cmd (cdr (assoc 'system apps))))
10473 (when (eq cmd 'default)
10474 (setq cmd (cdr (assoc t apps))))
10475 (when (eq cmd 'mailcap)
10476 (require 'mailcap)
10477 (mailcap-parse-mailcaps)
10478 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10479 (command (mailcap-mime-info mime-type)))
10480 (if (stringp command)
10481 (setq cmd command)
10482 (setq cmd 'emacs))))
10483 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10484 (not (file-exists-p file))
10485 (not org-open-non-existing-files))
10486 (error "No such file: %s" file))
10487 (cond
10488 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10489 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10490 (while (string-match "['\"]%s['\"]" cmd)
10491 (setq cmd (replace-match "%s" t t cmd)))
10492 (while (string-match "%s" cmd)
10493 (setq cmd (replace-match
10494 (save-match-data
10495 (shell-quote-argument
10496 (convert-standard-filename file)))
10497 t t cmd)))
10499 ;; Replace "%1", "%2" etc. in command with group matches from regex
10500 (save-match-data
10501 (let ((match-index 1)
10502 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10503 (set-match-data link-match-data)
10504 (while (<= match-index number-of-groups)
10505 (let ((regex (concat "%" (number-to-string match-index)))
10506 (replace-with (match-string match-index dlink)))
10507 (while (string-match regex cmd)
10508 (setq cmd (replace-match replace-with t t cmd))))
10509 (setq match-index (+ match-index 1)))))
10511 (save-window-excursion
10512 (start-process-shell-command cmd nil cmd)
10513 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10515 ((or (stringp cmd)
10516 (eq cmd 'emacs))
10517 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10518 (widen)
10519 (if line (org-goto-line line)
10520 (if search (org-link-search search))))
10521 ((consp cmd)
10522 (let ((file (convert-standard-filename file)))
10523 (save-match-data
10524 (set-match-data link-match-data)
10525 (eval cmd))))
10526 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10527 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10528 (or (not (equal old-buffer (current-buffer)))
10529 (not (equal old-pos (point))))
10530 (org-mark-ring-push old-pos old-buffer))))
10532 (defun org-file-apps-entry-match-against-dlink-p (entry)
10533 "This function returns non-nil if `entry' uses a regular
10534 expression which should be matched against the whole link by
10535 org-open-file.
10537 It assumes that is the case when the entry uses a regular
10538 expression which has at least one grouping construct and the
10539 action is either a lisp form or a command string containing
10540 '%1', i.e. using at least one subexpression match as a
10541 parameter."
10542 (let ((selector (car entry))
10543 (action (cdr entry)))
10544 (if (stringp selector)
10545 (and (> (regexp-opt-depth selector) 0)
10546 (or (and (stringp action)
10547 (string-match "%[0-9]" action))
10548 (consp action)))
10549 nil)))
10551 (defun org-default-apps ()
10552 "Return the default applications for this operating system."
10553 (cond
10554 ((eq system-type 'darwin)
10555 org-file-apps-defaults-macosx)
10556 ((eq system-type 'windows-nt)
10557 org-file-apps-defaults-windowsnt)
10558 (t org-file-apps-defaults-gnu)))
10560 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10561 "Convert extensions to regular expressions in the cars of LIST.
10562 Also, weed out any non-string entries, because the return value is used
10563 only for regexp matching.
10564 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10565 point to the symbol `emacs', indicating that the file should
10566 be opened in Emacs."
10567 (append
10568 (delq nil
10569 (mapcar (lambda (x)
10570 (if (not (stringp (car x)))
10572 (if (string-match "\\W" (car x))
10574 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10575 list))
10576 (if add-auto-mode
10577 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10579 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10580 (defun org-file-remote-p (file)
10581 "Test whether FILE specifies a location on a remote system.
10582 Return non-nil if the location is indeed remote.
10584 For example, the filename \"/user@host:/foo\" specifies a location
10585 on the system \"/user@host:\"."
10586 (cond ((fboundp 'file-remote-p)
10587 (file-remote-p file))
10588 ((fboundp 'tramp-handle-file-remote-p)
10589 (tramp-handle-file-remote-p file))
10590 ((and (boundp 'ange-ftp-name-format)
10591 (string-match (car ange-ftp-name-format) file))
10592 t)))
10595 ;;;; Refiling
10597 (defun org-get-org-file ()
10598 "Read a filename, with default directory `org-directory'."
10599 (let ((default (or org-default-notes-file remember-data-file)))
10600 (read-file-name (format "File name [%s]: " default)
10601 (file-name-as-directory org-directory)
10602 default)))
10604 (defun org-notes-order-reversed-p ()
10605 "Check if the current file should receive notes in reversed order."
10606 (cond
10607 ((not org-reverse-note-order) nil)
10608 ((eq t org-reverse-note-order) t)
10609 ((not (listp org-reverse-note-order)) nil)
10610 (t (catch 'exit
10611 (let ((all org-reverse-note-order)
10612 entry)
10613 (while (setq entry (pop all))
10614 (if (string-match (car entry) buffer-file-name)
10615 (throw 'exit (cdr entry))))
10616 nil)))))
10618 (defvar org-refile-target-table nil
10619 "The list of refile targets, created by `org-refile'.")
10621 (defvar org-agenda-new-buffers nil
10622 "Buffers created to visit agenda files.")
10624 (defvar org-refile-cache nil
10625 "Cache for refile targets.")
10627 (defvar org-refile-markers nil
10628 "All the markers used for caching refile locations.")
10630 (defun org-refile-marker (pos)
10631 "Get a new refile marker, but only if caching is in use."
10632 (if (not org-refile-use-cache)
10634 (let ((m (make-marker)))
10635 (move-marker m pos)
10636 (push m org-refile-markers)
10637 m)))
10639 (defun org-refile-cache-clear ()
10640 "Clear the refile cache and disable all the markers."
10641 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10642 (setq org-refile-markers nil)
10643 (setq org-refile-cache nil)
10644 (message "Refile cache has been cleared"))
10646 (defun org-refile-cache-check-set (set)
10647 "Check if all the markers in the cache still have live buffers."
10648 (let (marker)
10649 (catch 'exit
10650 (while (and set (setq marker (nth 3 (pop set))))
10651 ;; if org-refile-use-outline-path is 'file, marker may be nil
10652 (when (and marker (null (marker-buffer marker)))
10653 (message "not found") (sit-for 3)
10654 (throw 'exit nil)))
10655 t)))
10657 (defun org-refile-cache-put (set &rest identifiers)
10658 "Push the refile targets SET into the cache, under IDENTIFIERS."
10659 (let* ((key (sha1 (prin1-to-string identifiers)))
10660 (entry (assoc key org-refile-cache)))
10661 (if entry
10662 (setcdr entry set)
10663 (push (cons key set) org-refile-cache))))
10665 (defun org-refile-cache-get (&rest identifiers)
10666 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10667 (cond
10668 ((not org-refile-cache) nil)
10669 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10671 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10672 org-refile-cache))))
10673 (and set (org-refile-cache-check-set set) set)))))
10675 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10676 "Produce a table with refile targets."
10677 (let ((case-fold-search nil)
10678 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10679 (entries (or org-refile-targets '((nil . (:level . 1)))))
10680 targets tgs txt re files f desc descre fast-path-p level pos0)
10681 (message "Getting targets...")
10682 (with-current-buffer (or default-buffer (current-buffer))
10683 (while (setq entry (pop entries))
10684 (setq files (car entry) desc (cdr entry))
10685 (setq fast-path-p nil)
10686 (cond
10687 ((null files) (setq files (list (current-buffer))))
10688 ((eq files 'org-agenda-files)
10689 (setq files (org-agenda-files 'unrestricted)))
10690 ((and (symbolp files) (fboundp files))
10691 (setq files (funcall files)))
10692 ((and (symbolp files) (boundp files))
10693 (setq files (symbol-value files))))
10694 (if (stringp files) (setq files (list files)))
10695 (cond
10696 ((eq (car desc) :tag)
10697 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10698 ((eq (car desc) :todo)
10699 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10700 ((eq (car desc) :regexp)
10701 (setq descre (cdr desc)))
10702 ((eq (car desc) :level)
10703 (setq descre (concat "^\\*\\{" (number-to-string
10704 (if org-odd-levels-only
10705 (1- (* 2 (cdr desc)))
10706 (cdr desc)))
10707 "\\}[ \t]")))
10708 ((eq (car desc) :maxlevel)
10709 (setq fast-path-p t)
10710 (setq descre (concat "^\\*\\{1," (number-to-string
10711 (if org-odd-levels-only
10712 (1- (* 2 (cdr desc)))
10713 (cdr desc)))
10714 "\\}[ \t]")))
10715 (t (error "Bad refiling target description %s" desc)))
10716 (while (setq f (pop files))
10717 (with-current-buffer
10718 (if (bufferp f) f (org-get-agenda-file-buffer f))
10720 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10721 (progn
10722 (if (bufferp f) (setq f (buffer-file-name
10723 (buffer-base-buffer f))))
10724 (setq f (and f (expand-file-name f)))
10725 (if (eq org-refile-use-outline-path 'file)
10726 (push (list (file-name-nondirectory f) f nil nil) tgs))
10727 (save-excursion
10728 (save-restriction
10729 (widen)
10730 (goto-char (point-min))
10731 (while (re-search-forward descre nil t)
10732 (goto-char (setq pos0 (point-at-bol)))
10733 (catch 'next
10734 (when org-refile-target-verify-function
10735 (save-match-data
10736 (or (funcall org-refile-target-verify-function)
10737 (throw 'next t))))
10738 (when (and (looking-at org-complex-heading-regexp)
10739 (not (member (match-string 4) excluded-entries))
10740 (match-string 4))
10741 (setq level (org-reduced-level
10742 (- (match-end 1) (match-beginning 1)))
10743 txt (org-link-display-format (match-string 4))
10744 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10745 re (format org-complex-heading-regexp-format
10746 (regexp-quote (match-string 4))))
10747 (when org-refile-use-outline-path
10748 (setq txt (mapconcat
10749 'org-protect-slash
10750 (append
10751 (if (eq org-refile-use-outline-path
10752 'file)
10753 (list (file-name-nondirectory
10754 (buffer-file-name
10755 (buffer-base-buffer))))
10756 (if (eq org-refile-use-outline-path
10757 'full-file-path)
10758 (list (buffer-file-name
10759 (buffer-base-buffer)))))
10760 (org-get-outline-path fast-path-p
10761 level txt)
10762 (list txt))
10763 "/")))
10764 (push (list txt f re (org-refile-marker (point)))
10765 tgs)))
10766 (when (= (point) pos0)
10767 ;; verification function has not moved point
10768 (goto-char (point-at-eol))))))))
10769 (when org-refile-use-cache
10770 (org-refile-cache-put tgs (buffer-file-name) descre))
10771 (setq targets (append tgs targets))
10772 ))))
10773 (message "Getting targets...done")
10774 (nreverse targets)))
10776 (defun org-protect-slash (s)
10777 (while (string-match "/" s)
10778 (setq s (replace-match "\\" t t s)))
10781 (defvar org-olpa (make-vector 20 nil))
10783 (defun org-get-outline-path (&optional fastp level heading)
10784 "Return the outline path to the current entry, as a list.
10786 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10787 routine which makes outline path derivations for an entire file,
10788 avoiding backtracing. Refile target collection makes use of that."
10789 (if fastp
10790 (progn
10791 (if (> level 19)
10792 (error "Outline path failure, more than 19 levels"))
10793 (loop for i from level upto 19 do
10794 (aset org-olpa i nil))
10795 (prog1
10796 (delq nil (append org-olpa nil))
10797 (aset org-olpa level heading)))
10798 (let (rtn case-fold-search)
10799 (save-excursion
10800 (save-restriction
10801 (widen)
10802 (while (org-up-heading-safe)
10803 (when (looking-at org-complex-heading-regexp)
10804 (push (org-match-string-no-properties 4) rtn)))
10805 rtn)))))
10807 (defun org-format-outline-path (path &optional width prefix)
10808 "Format the outline path PATH for display.
10809 Width is the maximum number of characters that is available.
10810 Prefix is a prefix to be included in the returned string,
10811 such as the file name."
10812 (setq width (or width 79))
10813 (if prefix (setq width (- width (length prefix))))
10814 (if (not path)
10815 (or prefix "")
10816 (let* ((nsteps (length path))
10817 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10818 (maxwidth (if (<= total-width width)
10819 10000 ;; everything fits
10820 ;; we need to shorten the level headings
10821 (/ (- width nsteps) nsteps)))
10822 (org-odd-levels-only nil)
10823 (n 0)
10824 (total (1+ (length prefix))))
10825 (setq maxwidth (max maxwidth 10))
10826 (concat prefix
10827 (mapconcat
10828 (lambda (h)
10829 (setq n (1+ n))
10830 (if (and (= n nsteps) (< maxwidth 10000))
10831 (setq maxwidth (- total-width total)))
10832 (if (< (length h) maxwidth)
10833 (progn (setq total (+ total (length h) 1)) h)
10834 (setq h (substring h 0 (- maxwidth 2))
10835 total (+ total maxwidth 1))
10836 (if (string-match "[ \t]+\\'" h)
10837 (setq h (substring h 0 (match-beginning 0))))
10838 (setq h (concat h "..")))
10839 (org-add-props h nil 'face
10840 (nth (% (1- n) org-n-level-faces)
10841 org-level-faces))
10843 path "/")))))
10845 (defun org-display-outline-path (&optional file current)
10846 "Display the current outline path in the echo area."
10847 (interactive "P")
10848 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10849 (case-fold-search nil)
10850 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10851 (if current (setq path (append path
10852 (save-excursion
10853 (org-back-to-heading t)
10854 (if (looking-at org-complex-heading-regexp)
10855 (list (match-string 4)))))))
10856 (message "%s"
10857 (org-format-outline-path
10858 path
10859 (1- (frame-width))
10860 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10862 (defvar org-refile-history nil
10863 "History for refiling operations.")
10865 (defvar org-after-refile-insert-hook nil
10866 "Hook run after `org-refile' has inserted its stuff at the new location.
10867 Note that this is still *before* the stuff will be removed from
10868 the *old* location.")
10870 (defvar org-capture-last-stored-marker)
10871 (defun org-refile (&optional goto default-buffer rfloc)
10872 "Move the entry or entries at point to another heading.
10873 The list of target headings is compiled using the information in
10874 `org-refile-targets', which see.
10876 At the target location, the entry is filed as a subitem of the target
10877 heading. Depending on `org-reverse-note-order', the new subitem will
10878 either be the first or the last subitem.
10880 If there is an active region, all entries in that region will be moved.
10881 However, the region must fulfill the requirement that the first heading
10882 is the first one sets the top-level of the moved text - at most siblings
10883 below it are allowed.
10885 With prefix arg GOTO, the command will only visit the target location
10886 and not actually move anything.
10888 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10889 go to the location where the last refiling operation has put the subtree.
10890 With a prefix argument of `2', refile to the running clock.
10892 RFLOC can be a refile location obtained in a different way.
10894 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10896 If you are using target caching (see `org-refile-use-cache'),
10897 you have to clear the target cache in order to find new targets.
10898 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10899 prefix argument (`C-u C-u C-u C-c C-w')."
10901 (interactive "P")
10902 (if (member goto '(0 (64)))
10903 (org-refile-cache-clear)
10904 (let* ((cbuf (current-buffer))
10905 (regionp (org-region-active-p))
10906 (region-start (and regionp (region-beginning)))
10907 (region-end (and regionp (region-end)))
10908 (region-length (and regionp (- region-end region-start)))
10909 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10910 pos it nbuf file re level reversed)
10911 (setq last-command nil)
10912 (when regionp
10913 (goto-char region-start)
10914 (or (bolp) (goto-char (point-at-bol)))
10915 (setq region-start (point))
10916 (unless (or (org-kill-is-subtree-p
10917 (buffer-substring region-start region-end))
10918 (prog1 org-refile-active-region-within-subtree
10919 (org-toggle-heading)))
10920 (error "The region is not a (sequence of) subtree(s)")))
10921 (if (equal goto '(16))
10922 (org-refile-goto-last-stored)
10923 (when (or
10924 (and (equal goto 2)
10925 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10926 (prog1
10927 (setq it (list (or org-clock-heading "running clock")
10928 (buffer-file-name
10929 (marker-buffer org-clock-hd-marker))
10931 (marker-position org-clock-hd-marker)))
10932 (setq goto nil)))
10933 (setq it (or rfloc
10934 (let (heading-text)
10935 (save-excursion
10936 (unless goto
10937 (org-back-to-heading t)
10938 (setq heading-text
10939 (nth 4 (org-heading-components))))
10940 (org-refile-get-location
10941 (cond (goto "Goto")
10942 (regionp "Refile region to")
10943 (t (concat "Refile subtree \""
10944 heading-text "\" to")))
10945 default-buffer
10946 (and (not (equal '(4) goto))
10947 org-refile-allow-creating-parent-nodes)
10948 goto))))))
10949 (setq file (nth 1 it)
10950 re (nth 2 it)
10951 pos (nth 3 it))
10952 (if (and (not goto)
10954 (equal (buffer-file-name) file)
10955 (if regionp
10956 (and (>= pos region-start)
10957 (<= pos region-end))
10958 (and (>= pos (point))
10959 (< pos (save-excursion
10960 (org-end-of-subtree t t))))))
10961 (error "Cannot refile to position inside the tree or region"))
10963 (setq nbuf (or (find-buffer-visiting file)
10964 (find-file-noselect file)))
10965 (if goto
10966 (progn
10967 (org-pop-to-buffer-same-window nbuf)
10968 (goto-char pos)
10969 (org-show-context 'org-goto))
10970 (if regionp
10971 (progn
10972 (org-kill-new (buffer-substring region-start region-end))
10973 (org-save-markers-in-region region-start region-end))
10974 (org-copy-subtree 1 nil t))
10975 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10976 (find-file-noselect file)))
10977 (setq reversed (org-notes-order-reversed-p))
10978 (save-excursion
10979 (save-restriction
10980 (widen)
10981 (if pos
10982 (progn
10983 (goto-char pos)
10984 (looking-at org-outline-regexp)
10985 (setq level (org-get-valid-level (funcall outline-level) 1))
10986 (goto-char
10987 (if reversed
10988 (or (outline-next-heading) (point-max))
10989 (or (save-excursion (org-get-next-sibling))
10990 (org-end-of-subtree t t)
10991 (point-max)))))
10992 (setq level 1)
10993 (if (not reversed)
10994 (goto-char (point-max))
10995 (goto-char (point-min))
10996 (or (outline-next-heading) (goto-char (point-max)))))
10997 (if (not (bolp)) (newline))
10998 (org-paste-subtree level)
10999 (when org-log-refile
11000 (org-add-log-setup 'refile nil nil 'findpos
11001 org-log-refile)
11002 (unless (eq org-log-refile 'note)
11003 (save-excursion (org-add-log-note))))
11004 (and org-auto-align-tags
11005 (let ((org-loop-over-headlines-in-active-region nil))
11006 (org-set-tags nil t)))
11007 (bookmark-set "org-refile-last-stored")
11008 ;; If we are refiling for capture, make sure that the
11009 ;; last-capture pointers point here
11010 (when (org-bound-and-true-p org-refile-for-capture)
11011 (bookmark-set "org-capture-last-stored-marker")
11012 (move-marker org-capture-last-stored-marker (point)))
11013 (if (fboundp 'deactivate-mark) (deactivate-mark))
11014 (run-hooks 'org-after-refile-insert-hook))))
11015 (if regionp
11016 (delete-region (point) (+ (point) region-length))
11017 (org-cut-subtree))
11018 (when (featurep 'org-inlinetask)
11019 (org-inlinetask-remove-END-maybe))
11020 (setq org-markers-to-move nil)
11021 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11023 (defun org-refile-goto-last-stored ()
11024 "Go to the location where the last refile was stored."
11025 (interactive)
11026 (bookmark-jump "org-refile-last-stored")
11027 (message "This is the location of the last refile"))
11029 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11030 no-exclude)
11031 "Prompt the user for a refile location, using PROMPT.
11032 PROMPT should not be suffixed with a colon and a space, because
11033 this function appends the default value from
11034 `org-refile-history' automatically, if that is not empty.
11035 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11036 this is used for the GOTO interface."
11037 (let ((org-refile-targets org-refile-targets)
11038 (org-refile-use-outline-path org-refile-use-outline-path)
11039 excluded-entries)
11040 (when (and (derived-mode-p 'org-mode)
11041 (not org-refile-use-cache)
11042 (not no-exclude))
11043 (org-map-tree
11044 (lambda()
11045 (setq excluded-entries
11046 (append excluded-entries (list (org-get-heading t t)))))))
11047 (setq org-refile-target-table
11048 (org-refile-get-targets default-buffer excluded-entries)))
11049 (unless org-refile-target-table
11050 (error "No refile targets"))
11051 (let* ((prompt (concat prompt
11052 (and (car org-refile-history)
11053 (concat " (default " (car org-refile-history) ")"))
11054 ": "))
11055 (cbuf (current-buffer))
11056 (partial-completion-mode nil)
11057 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11058 (cfunc (if (and org-refile-use-outline-path
11059 org-outline-path-complete-in-steps)
11060 'org-olpath-completing-read
11061 'org-icompleting-read))
11062 (extra (if org-refile-use-outline-path "/" ""))
11063 (filename (and cfn (expand-file-name cfn)))
11064 (tbl (mapcar
11065 (lambda (x)
11066 (if (and (not (member org-refile-use-outline-path
11067 '(file full-file-path)))
11068 (not (equal filename (nth 1 x))))
11069 (cons (concat (car x) extra " ("
11070 (file-name-nondirectory (nth 1 x)) ")")
11071 (cdr x))
11072 (cons (concat (car x) extra) (cdr x))))
11073 org-refile-target-table))
11074 (completion-ignore-case t)
11075 pa answ parent-target child parent old-hist)
11076 (setq old-hist org-refile-history)
11077 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11078 nil 'org-refile-history (car org-refile-history)))
11079 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11080 (org-refile-check-position pa)
11081 (if pa
11082 (progn
11083 (when (or (not org-refile-history)
11084 (not (eq old-hist org-refile-history))
11085 (not (equal (car pa) (car org-refile-history))))
11086 (setq org-refile-history
11087 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11088 org-refile-history
11089 (cdr org-refile-history))))
11090 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11091 (pop org-refile-history)))
11093 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11094 (progn
11095 (setq parent (match-string 1 answ)
11096 child (match-string 2 answ))
11097 (setq parent-target (or (assoc parent tbl)
11098 (assoc (concat parent "/") tbl)))
11099 (when (and parent-target
11100 (or (eq new-nodes t)
11101 (and (eq new-nodes 'confirm)
11102 (y-or-n-p (format "Create new node \"%s\"? "
11103 child)))))
11104 (org-refile-new-child parent-target child)))
11105 (error "Invalid target location")))))
11107 (declare-function org-string-nw-p "org-macs.el" (s))
11108 (defun org-refile-check-position (refile-pointer)
11109 "Check if the refile pointer matches the readline to which it points."
11110 (let* ((file (nth 1 refile-pointer))
11111 (re (nth 2 refile-pointer))
11112 (pos (nth 3 refile-pointer))
11113 buffer)
11114 (when (org-string-nw-p re)
11115 (setq buffer (if (markerp pos)
11116 (marker-buffer pos)
11117 (or (find-buffer-visiting file)
11118 (find-file-noselect file))))
11119 (with-current-buffer buffer
11120 (save-excursion
11121 (save-restriction
11122 (widen)
11123 (goto-char pos)
11124 (beginning-of-line 1)
11125 (unless (org-looking-at-p re)
11126 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11128 (defun org-refile-new-child (parent-target child)
11129 "Use refile target PARENT-TARGET to add new CHILD below it."
11130 (unless parent-target
11131 (error "Cannot find parent for new node"))
11132 (let ((file (nth 1 parent-target))
11133 (pos (nth 3 parent-target))
11134 level)
11135 (with-current-buffer (or (find-buffer-visiting file)
11136 (find-file-noselect file))
11137 (save-excursion
11138 (save-restriction
11139 (widen)
11140 (if pos
11141 (goto-char pos)
11142 (goto-char (point-max))
11143 (if (not (bolp)) (newline)))
11144 (when (looking-at org-outline-regexp)
11145 (setq level (funcall outline-level))
11146 (org-end-of-subtree t t))
11147 (org-back-over-empty-lines)
11148 (insert "\n" (make-string
11149 (if pos (org-get-valid-level level 1) 1) ?*)
11150 " " child "\n")
11151 (beginning-of-line 0)
11152 (list (concat (car parent-target) "/" child) file "" (point)))))))
11154 (defun org-olpath-completing-read (prompt collection &rest args)
11155 "Read an outline path like a file name."
11156 (let ((thetable collection)
11157 (org-completion-use-ido nil) ; does not work with ido.
11158 (org-completion-use-iswitchb nil)) ; or iswitchb
11159 (apply
11160 'org-icompleting-read prompt
11161 (lambda (string predicate &optional flag)
11162 (let (rtn r f (l (length string)))
11163 (cond
11164 ((eq flag nil)
11165 ;; try completion
11166 (try-completion string thetable))
11167 ((eq flag t)
11168 ;; all-completions
11169 (setq rtn (all-completions string thetable predicate))
11170 (mapcar
11171 (lambda (x)
11172 (setq r (substring x l))
11173 (if (string-match " ([^)]*)$" x)
11174 (setq f (match-string 0 x))
11175 (setq f ""))
11176 (if (string-match "/" r)
11177 (concat string (substring r 0 (match-end 0)) f)
11179 rtn))
11180 ((eq flag 'lambda)
11181 ;; exact match?
11182 (assoc string thetable)))))
11183 args)))
11185 ;;;; Dynamic blocks
11187 (defun org-find-dblock (name)
11188 "Find the first dynamic block with name NAME in the buffer.
11189 If not found, stay at current position and return nil."
11190 (let ((case-fold-search t) pos)
11191 (save-excursion
11192 (goto-char (point-min))
11193 (setq pos (and (re-search-forward
11194 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11195 (match-beginning 0))))
11196 (if pos (goto-char pos))
11197 pos))
11199 (defconst org-dblock-start-re
11200 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11201 "Matches the start line of a dynamic block, with parameters.")
11203 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11204 "Matches the end of a dynamic block.")
11206 (defun org-create-dblock (plist)
11207 "Create a dynamic block section, with parameters taken from PLIST.
11208 PLIST must contain a :name entry which is used as name of the block."
11209 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11210 (end-of-line 1)
11211 (newline))
11212 (let ((col (current-column))
11213 (name (plist-get plist :name)))
11214 (insert "#+BEGIN: " name)
11215 (while plist
11216 (if (eq (car plist) :name)
11217 (setq plist (cddr plist))
11218 (insert " " (prin1-to-string (pop plist)))))
11219 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11220 (beginning-of-line -2)))
11222 (defun org-prepare-dblock ()
11223 "Prepare dynamic block for refresh.
11224 This empties the block, puts the cursor at the insert position and returns
11225 the property list including an extra property :name with the block name."
11226 (unless (looking-at org-dblock-start-re)
11227 (error "Not at a dynamic block"))
11228 (let* ((begdel (1+ (match-end 0)))
11229 (name (org-no-properties (match-string 1)))
11230 (params (append (list :name name)
11231 (read (concat "(" (match-string 3) ")")))))
11232 (save-excursion
11233 (beginning-of-line 1)
11234 (skip-chars-forward " \t")
11235 (setq params (plist-put params :indentation-column (current-column))))
11236 (unless (re-search-forward org-dblock-end-re nil t)
11237 (error "Dynamic block not terminated"))
11238 (setq params
11239 (append params
11240 (list :content (buffer-substring
11241 begdel (match-beginning 0)))))
11242 (delete-region begdel (match-beginning 0))
11243 (goto-char begdel)
11244 (open-line 1)
11245 params))
11247 (defun org-map-dblocks (&optional command)
11248 "Apply COMMAND to all dynamic blocks in the current buffer.
11249 If COMMAND is not given, use `org-update-dblock'."
11250 (let ((cmd (or command 'org-update-dblock)))
11251 (save-excursion
11252 (goto-char (point-min))
11253 (while (re-search-forward org-dblock-start-re nil t)
11254 (goto-char (match-beginning 0))
11255 (save-excursion
11256 (condition-case nil
11257 (funcall cmd)
11258 (error (message "Error during update of dynamic block"))))
11259 (unless (re-search-forward org-dblock-end-re nil t)
11260 (error "Dynamic block not terminated"))))))
11262 (defun org-dblock-update (&optional arg)
11263 "User command for updating dynamic blocks.
11264 Update the dynamic block at point. With prefix ARG, update all dynamic
11265 blocks in the buffer."
11266 (interactive "P")
11267 (if arg
11268 (org-update-all-dblocks)
11269 (or (looking-at org-dblock-start-re)
11270 (org-beginning-of-dblock))
11271 (org-update-dblock)))
11273 (defun org-update-dblock ()
11274 "Update the dynamic block at point.
11275 This means to empty the block, parse for parameters and then call
11276 the correct writing function."
11277 (interactive)
11278 (save-window-excursion
11279 (let* ((pos (point))
11280 (line (org-current-line))
11281 (params (org-prepare-dblock))
11282 (name (plist-get params :name))
11283 (indent (plist-get params :indentation-column))
11284 (cmd (intern (concat "org-dblock-write:" name))))
11285 (message "Updating dynamic block `%s' at line %d..." name line)
11286 (funcall cmd params)
11287 (message "Updating dynamic block `%s' at line %d...done" name line)
11288 (goto-char pos)
11289 (when (and indent (> indent 0))
11290 (setq indent (make-string indent ?\ ))
11291 (save-excursion
11292 (org-beginning-of-dblock)
11293 (forward-line 1)
11294 (while (not (looking-at org-dblock-end-re))
11295 (insert indent)
11296 (beginning-of-line 2))
11297 (when (looking-at org-dblock-end-re)
11298 (and (looking-at "[ \t]+")
11299 (replace-match ""))
11300 (insert indent)))))))
11302 (defun org-beginning-of-dblock ()
11303 "Find the beginning of the dynamic block at point.
11304 Error if there is no such block at point."
11305 (let ((pos (point))
11306 beg)
11307 (end-of-line 1)
11308 (if (and (re-search-backward org-dblock-start-re nil t)
11309 (setq beg (match-beginning 0))
11310 (re-search-forward org-dblock-end-re nil t)
11311 (> (match-end 0) pos))
11312 (goto-char beg)
11313 (goto-char pos)
11314 (error "Not in a dynamic block"))))
11316 ;;;###autoload
11317 (defun org-update-all-dblocks ()
11318 "Update all dynamic blocks in the buffer.
11319 This function can be used in a hook."
11320 (interactive)
11321 (when (derived-mode-p 'org-mode)
11322 (org-map-dblocks 'org-update-dblock)))
11325 ;;;; Completion
11327 (defconst org-additional-option-like-keywords
11328 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11329 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11330 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11331 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11332 "BEGIN:" "END:"
11333 "ORGTBL" "TBLFM:" "TBLNAME:"
11334 "BEGIN_EXAMPLE" "END_EXAMPLE"
11335 "BEGIN_VERBATIM" "END_VERBATIM"
11336 "BEGIN_QUOTE" "END_QUOTE"
11337 "BEGIN_VERSE" "END_VERSE"
11338 "BEGIN_CENTER" "END_CENTER"
11339 "BEGIN_SRC" "END_SRC"
11340 "BEGIN_RESULT" "END_RESULT"
11341 "BEGIN_lstlisting" "END_lstlisting"
11342 "NAME:" "RESULTS:"
11343 "HEADER:" "HEADERS:"
11344 "COLUMNS:" "PROPERTY:"
11345 "CAPTION:" "LABEL:"
11346 "SETUPFILE:"
11347 "INCLUDE:"
11348 "BIND:"
11349 "MACRO:"))
11351 (defconst org-options-keywords
11352 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11353 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11354 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11355 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11356 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11357 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11358 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11360 (defconst org-additional-option-like-keywords-for-flyspell
11361 (delete-dups
11362 (split-string
11363 (mapconcat (lambda(k)
11364 (replace-regexp-in-string
11365 "_\\|:" " "
11366 (concat k " " (downcase k) " " (upcase k))))
11367 (append org-options-keywords org-additional-option-like-keywords)
11368 " ")
11369 " +" t)))
11371 (defcustom org-structure-template-alist
11373 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11374 "<src lang=\"?\">\n\n</src>")
11375 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11376 "<example>\n?\n</example>")
11377 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11378 "<quote>\n?\n</quote>")
11379 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11380 "<verse>\n?\n</verse>")
11381 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11382 "<center>\n?\n</center>")
11383 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11384 "<literal style=\"latex\">\n?\n</literal>")
11385 ("L" "#+LaTeX: "
11386 "<literal style=\"latex\">?</literal>")
11387 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11388 "<literal style=\"html\">\n?\n</literal>")
11389 ("H" "#+HTML: "
11390 "<literal style=\"html\">?</literal>")
11391 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11392 ("A" "#+ASCII: ")
11393 ("i" "#+INDEX: ?"
11394 "#+INDEX: ?")
11395 ("I" "#+INCLUDE: %file ?"
11396 "<include file=%file markup=\"?\">")
11398 "Structure completion elements.
11399 This is a list of abbreviation keys and values. The value gets inserted
11400 if you type `<' followed by the key and then press the completion key,
11401 usually `M-TAB'. %file will be replaced by a file name after prompting
11402 for the file using completion. The cursor will be placed at the position
11403 of the `?` in the template.
11404 There are two templates for each key, the first uses the original Org syntax,
11405 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11406 the default when the /org-mtags.el/ module has been loaded. See also the
11407 variable `org-mtags-prefer-muse-templates'."
11408 :group 'org-completion
11409 :type '(repeat
11410 (string :tag "Key")
11411 (string :tag "Template")
11412 (string :tag "Muse Template")))
11414 (defun org-try-structure-completion ()
11415 "Try to complete a structure template before point.
11416 This looks for strings like \"<e\" on an otherwise empty line and
11417 expands them."
11418 (let ((l (buffer-substring (point-at-bol) (point)))
11420 (when (and (looking-at "[ \t]*$")
11421 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11422 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11423 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11424 (match-beginning 1)) a)
11425 t)))
11427 (defun org-complete-expand-structure-template (start cell)
11428 "Expand a structure template."
11429 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11430 (rpl (nth (if musep 2 1) cell))
11431 (ind ""))
11432 (delete-region start (point))
11433 (when (string-match "\\`#\\+" rpl)
11434 (cond
11435 ((bolp))
11436 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11437 (setq ind (buffer-substring (point-at-bol) (point))))
11438 (t (newline))))
11439 (setq start (point))
11440 (if (string-match "%file" rpl)
11441 (setq rpl (replace-match
11442 (concat
11443 "\""
11444 (save-match-data
11445 (abbreviate-file-name (read-file-name "Include file: ")))
11446 "\"")
11447 t t rpl)))
11448 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11449 (concat "\n" ind)))
11450 (insert rpl)
11451 (if (re-search-backward "\\?" start t) (delete-char 1))))
11453 ;;;; TODO, DEADLINE, Comments
11455 (defun org-toggle-comment ()
11456 "Change the COMMENT state of an entry."
11457 (interactive)
11458 (save-excursion
11459 (org-back-to-heading)
11460 (let (case-fold-search)
11461 (cond
11462 ((looking-at (format org-heading-keyword-regexp-format
11463 org-comment-string))
11464 (goto-char (match-end 1))
11465 (looking-at (concat " +" org-comment-string))
11466 (replace-match "" t t)
11467 (when (eolp) (insert " ")))
11468 ((looking-at org-outline-regexp)
11469 (goto-char (match-end 0))
11470 (insert org-comment-string " "))))))
11472 (defvar org-last-todo-state-is-todo nil
11473 "This is non-nil when the last TODO state change led to a TODO state.
11474 If the last change removed the TODO tag or switched to DONE, then
11475 this is nil.")
11477 (defvar org-setting-tags nil) ; dynamically skipped
11479 (defvar org-todo-setup-filter-hook nil
11480 "Hook for functions that pre-filter todo specs.
11481 Each function takes a todo spec and returns either nil or the spec
11482 transformed into canonical form." )
11484 (defvar org-todo-get-default-hook nil
11485 "Hook for functions that get a default item for todo.
11486 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11487 nil or a string to be used for the todo mark." )
11489 (defvar org-agenda-headline-snapshot-before-repeat)
11491 (defun org-current-effective-time ()
11492 "Return current time adjusted for `org-extend-today-until' variable."
11493 (let* ((ct (org-current-time))
11494 (dct (decode-time ct))
11495 (ct1
11496 (if (and org-use-effective-time
11497 (< (nth 2 dct) org-extend-today-until))
11498 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11499 ct)))
11500 ct1))
11502 (defun org-todo-yesterday (&optional arg)
11503 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11504 (interactive "P")
11505 (if (eq major-mode 'org-agenda-mode)
11506 (apply 'org-agenda-todo-yesterday arg)
11507 (let* ((hour (third (decode-time
11508 (org-current-time))))
11509 (org-extend-today-until (1+ hour)))
11510 (org-todo arg))))
11512 (defun org-todo (&optional arg)
11513 "Change the TODO state of an item.
11514 The state of an item is given by a keyword at the start of the heading,
11515 like
11516 *** TODO Write paper
11517 *** DONE Call mom
11519 The different keywords are specified in the variable `org-todo-keywords'.
11520 By default the available states are \"TODO\" and \"DONE\".
11521 So for this example: when the item starts with TODO, it is changed to DONE.
11522 When it starts with DONE, the DONE is removed. And when neither TODO nor
11523 DONE are present, add TODO at the beginning of the heading.
11525 With \\[universal-argument] prefix arg, use completion to determine the new \
11526 state.
11527 With numeric prefix arg, switch to that state.
11528 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11529 keywords (nextset).
11530 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11531 With a numeric prefix arg of 0, inhibit note taking for the change.
11533 For calling through lisp, arg is also interpreted in the following way:
11534 'none -> empty state
11535 \"\"(empty string) -> switch to empty state
11536 'done -> switch to DONE
11537 'nextset -> switch to the next set of keywords
11538 'previousset -> switch to the previous set of keywords
11539 \"WAITING\" -> switch to the specified keyword, but only if it
11540 really is a member of `org-todo-keywords'."
11541 (interactive "P")
11542 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11543 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11544 'region-start-level 'region))
11545 org-loop-over-headlines-in-active-region)
11546 (org-map-entries
11547 `(org-todo ,arg)
11548 org-loop-over-headlines-in-active-region
11549 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11550 (if (equal arg '(16)) (setq arg 'nextset))
11551 (let ((org-blocker-hook org-blocker-hook)
11552 (case-fold-search nil))
11553 (when (equal arg '(64))
11554 (setq arg nil org-blocker-hook nil))
11555 (when (and org-blocker-hook
11556 (or org-inhibit-blocking
11557 (org-entry-get nil "NOBLOCKING")))
11558 (setq org-blocker-hook nil))
11559 (save-excursion
11560 (catch 'exit
11561 (org-back-to-heading t)
11562 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11563 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11564 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11565 (let* ((match-data (match-data))
11566 (startpos (point-at-bol))
11567 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11568 (org-log-done org-log-done)
11569 (org-log-repeat org-log-repeat)
11570 (org-todo-log-states org-todo-log-states)
11571 (org-inhibit-logging
11572 (if (equal arg 0)
11573 (progn (setq arg nil) 'note) org-inhibit-logging))
11574 (this (match-string 1))
11575 (hl-pos (match-beginning 0))
11576 (head (org-get-todo-sequence-head this))
11577 (ass (assoc head org-todo-kwd-alist))
11578 (interpret (nth 1 ass))
11579 (done-word (nth 3 ass))
11580 (final-done-word (nth 4 ass))
11581 (org-last-state (or this ""))
11582 (completion-ignore-case t)
11583 (member (member this org-todo-keywords-1))
11584 (tail (cdr member))
11585 (org-state (cond
11586 ((and org-todo-key-trigger
11587 (or (and (equal arg '(4))
11588 (eq org-use-fast-todo-selection 'prefix))
11589 (and (not arg) org-use-fast-todo-selection
11590 (not (eq org-use-fast-todo-selection
11591 'prefix)))))
11592 ;; Use fast selection
11593 (org-fast-todo-selection))
11594 ((and (equal arg '(4))
11595 (or (not org-use-fast-todo-selection)
11596 (not org-todo-key-trigger)))
11597 ;; Read a state with completion
11598 (org-icompleting-read
11599 "State: " (mapcar (lambda(x) (list x))
11600 org-todo-keywords-1)
11601 nil t))
11602 ((eq arg 'right)
11603 (if this
11604 (if tail (car tail) nil)
11605 (car org-todo-keywords-1)))
11606 ((eq arg 'left)
11607 (if (equal member org-todo-keywords-1)
11609 (if this
11610 (nth (- (length org-todo-keywords-1)
11611 (length tail) 2)
11612 org-todo-keywords-1)
11613 (org-last org-todo-keywords-1))))
11614 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11615 (setq arg nil))) ; hack to fall back to cycling
11616 (arg
11617 ;; user or caller requests a specific state
11618 (cond
11619 ((equal arg "") nil)
11620 ((eq arg 'none) nil)
11621 ((eq arg 'done) (or done-word (car org-done-keywords)))
11622 ((eq arg 'nextset)
11623 (or (car (cdr (member head org-todo-heads)))
11624 (car org-todo-heads)))
11625 ((eq arg 'previousset)
11626 (let ((org-todo-heads (reverse org-todo-heads)))
11627 (or (car (cdr (member head org-todo-heads)))
11628 (car org-todo-heads))))
11629 ((car (member arg org-todo-keywords-1)))
11630 ((stringp arg)
11631 (error "State `%s' not valid in this file" arg))
11632 ((nth (1- (prefix-numeric-value arg))
11633 org-todo-keywords-1))))
11634 ((null member) (or head (car org-todo-keywords-1)))
11635 ((equal this final-done-word) nil) ;; -> make empty
11636 ((null tail) nil) ;; -> first entry
11637 ((memq interpret '(type priority))
11638 (if (eq this-command last-command)
11639 (car tail)
11640 (if (> (length tail) 0)
11641 (or done-word (car org-done-keywords))
11642 nil)))
11644 (car tail))))
11645 (org-state (or
11646 (run-hook-with-args-until-success
11647 'org-todo-get-default-hook org-state org-last-state)
11648 org-state))
11649 (next (if org-state (concat " " org-state " ") " "))
11650 (change-plist (list :type 'todo-state-change :from this :to org-state
11651 :position startpos))
11652 dolog now-done-p)
11653 (when org-blocker-hook
11654 (setq org-last-todo-state-is-todo
11655 (not (member this org-done-keywords)))
11656 (unless (save-excursion
11657 (save-match-data
11658 (org-with-wide-buffer
11659 (run-hook-with-args-until-failure
11660 'org-blocker-hook change-plist))))
11661 (if (org-called-interactively-p 'interactive)
11662 (error "TODO state change from %s to %s blocked" this org-state)
11663 ;; fail silently
11664 (message "TODO state change from %s to %s blocked" this org-state)
11665 (throw 'exit nil))))
11666 (store-match-data match-data)
11667 (replace-match next t t)
11668 (unless (pos-visible-in-window-p hl-pos)
11669 (message "TODO state changed to %s" (org-trim next)))
11670 (unless head
11671 (setq head (org-get-todo-sequence-head org-state)
11672 ass (assoc head org-todo-kwd-alist)
11673 interpret (nth 1 ass)
11674 done-word (nth 3 ass)
11675 final-done-word (nth 4 ass)))
11676 (when (memq arg '(nextset previousset))
11677 (message "Keyword-Set %d/%d: %s"
11678 (- (length org-todo-sets) -1
11679 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11680 (length org-todo-sets)
11681 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11682 (setq org-last-todo-state-is-todo
11683 (not (member org-state org-done-keywords)))
11684 (setq now-done-p (and (member org-state org-done-keywords)
11685 (not (member this org-done-keywords))))
11686 (and logging (org-local-logging logging))
11687 (when (and (or org-todo-log-states org-log-done)
11688 (not (eq org-inhibit-logging t))
11689 (not (memq arg '(nextset previousset))))
11690 ;; we need to look at recording a time and note
11691 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11692 (nth 2 (assoc this org-todo-log-states))))
11693 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11694 (setq dolog 'time))
11695 (when (and org-state
11696 (member org-state org-not-done-keywords)
11697 (not (member this org-not-done-keywords)))
11698 ;; This is now a todo state and was not one before
11699 ;; If there was a CLOSED time stamp, get rid of it.
11700 (org-add-planning-info nil nil 'closed))
11701 (when (and now-done-p org-log-done)
11702 ;; It is now done, and it was not done before
11703 (org-add-planning-info 'closed (org-current-effective-time))
11704 (if (and (not dolog) (eq 'note org-log-done))
11705 (org-add-log-setup 'done org-state this 'findpos 'note)))
11706 (when (and org-state dolog)
11707 ;; This is a non-nil state, and we need to log it
11708 (org-add-log-setup 'state org-state this 'findpos dolog)))
11709 ;; Fixup tag positioning
11710 (org-todo-trigger-tag-changes org-state)
11711 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11712 (when org-provide-todo-statistics
11713 (org-update-parent-todo-statistics))
11714 (run-hooks 'org-after-todo-state-change-hook)
11715 (if (and arg (not (member org-state org-done-keywords)))
11716 (setq head (org-get-todo-sequence-head org-state)))
11717 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11718 ;; Do we need to trigger a repeat?
11719 (when now-done-p
11720 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11721 ;; This is for the agenda, take a snapshot of the headline.
11722 (save-match-data
11723 (setq org-agenda-headline-snapshot-before-repeat
11724 (org-get-heading))))
11725 (org-auto-repeat-maybe org-state))
11726 ;; Fixup cursor location if close to the keyword
11727 (if (and (outline-on-heading-p)
11728 (not (bolp))
11729 (save-excursion (beginning-of-line 1)
11730 (looking-at org-todo-line-regexp))
11731 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11732 (progn
11733 (goto-char (or (match-end 2) (match-end 1)))
11734 (and (looking-at " ") (just-one-space))))
11735 (when org-trigger-hook
11736 (save-excursion
11737 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11739 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11740 "Block turning an entry into a TODO, using the hierarchy.
11741 This checks whether the current task should be blocked from state
11742 changes. Such blocking occurs when:
11744 1. The task has children which are not all in a completed state.
11746 2. A task has a parent with the property :ORDERED:, and there
11747 are siblings prior to the current task with incomplete
11748 status.
11750 3. The parent of the task is blocked because it has siblings that should
11751 be done first, or is child of a block grandparent TODO entry."
11753 (if (not org-enforce-todo-dependencies)
11754 t ; if locally turned off don't block
11755 (catch 'dont-block
11756 ;; If this is not a todo state change, or if this entry is already DONE,
11757 ;; do not block
11758 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11759 (member (plist-get change-plist :from)
11760 (cons 'done org-done-keywords))
11761 (member (plist-get change-plist :to)
11762 (cons 'todo org-not-done-keywords))
11763 (not (plist-get change-plist :to)))
11764 (throw 'dont-block t))
11765 ;; If this task has children, and any are undone, it's blocked
11766 (save-excursion
11767 (org-back-to-heading t)
11768 (let ((this-level (funcall outline-level)))
11769 (outline-next-heading)
11770 (let ((child-level (funcall outline-level)))
11771 (while (and (not (eobp))
11772 (> child-level this-level))
11773 ;; this todo has children, check whether they are all
11774 ;; completed
11775 (if (and (not (org-entry-is-done-p))
11776 (org-entry-is-todo-p))
11777 (throw 'dont-block nil))
11778 (outline-next-heading)
11779 (setq child-level (funcall outline-level))))))
11780 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11781 ;; any previous siblings are undone, it's blocked
11782 (save-excursion
11783 (org-back-to-heading t)
11784 (let* ((pos (point))
11785 (parent-pos (and (org-up-heading-safe) (point))))
11786 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11787 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11788 (forward-line 1)
11789 (re-search-forward org-not-done-heading-regexp pos t))
11790 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11791 ;; Search further up the hierarchy, to see if an ancestor is blocked
11792 (while t
11793 (goto-char parent-pos)
11794 (if (not (looking-at org-not-done-heading-regexp))
11795 (throw 'dont-block t)) ; do not block, parent is not a TODO
11796 (setq pos (point))
11797 (setq parent-pos (and (org-up-heading-safe) (point)))
11798 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11799 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11800 (forward-line 1)
11801 (re-search-forward org-not-done-heading-regexp pos t))
11802 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11804 (defcustom org-track-ordered-property-with-tag nil
11805 "Should the ORDERED property also be shown as a tag?
11806 The ORDERED property decides if an entry should require subtasks to be
11807 completed in sequence. Since a property is not very visible, setting
11808 this option means that toggling the ORDERED property with the command
11809 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11810 not relevant for the behavior, but it makes things more visible.
11812 Note that toggling the tag with tags commands will not change the property
11813 and therefore not influence behavior!
11815 This can be t, meaning the tag ORDERED should be used, It can also be a
11816 string to select a different tag for this task."
11817 :group 'org-todo
11818 :type '(choice
11819 (const :tag "No tracking" nil)
11820 (const :tag "Track with ORDERED tag" t)
11821 (string :tag "Use other tag")))
11823 (defun org-toggle-ordered-property ()
11824 "Toggle the ORDERED property of the current entry.
11825 For better visibility, you can track the value of this property with a tag.
11826 See variable `org-track-ordered-property-with-tag'."
11827 (interactive)
11828 (let* ((t1 org-track-ordered-property-with-tag)
11829 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11830 (save-excursion
11831 (org-back-to-heading)
11832 (if (org-entry-get nil "ORDERED")
11833 (progn
11834 (org-delete-property "ORDERED")
11835 (and tag (org-toggle-tag tag 'off))
11836 (message "Subtasks can be completed in arbitrary order"))
11837 (org-entry-put nil "ORDERED" "t")
11838 (and tag (org-toggle-tag tag 'on))
11839 (message "Subtasks must be completed in sequence")))))
11841 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11842 (defun org-block-todo-from-checkboxes (change-plist)
11843 "Block turning an entry into a TODO, using checkboxes.
11844 This checks whether the current task should be blocked from state
11845 changes because there are unchecked boxes in this entry."
11846 (if (not org-enforce-todo-checkbox-dependencies)
11847 t ; if locally turned off don't block
11848 (catch 'dont-block
11849 ;; If this is not a todo state change, or if this entry is already DONE,
11850 ;; do not block
11851 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11852 (member (plist-get change-plist :from)
11853 (cons 'done org-done-keywords))
11854 (member (plist-get change-plist :to)
11855 (cons 'todo org-not-done-keywords))
11856 (not (plist-get change-plist :to)))
11857 (throw 'dont-block t))
11858 ;; If this task has checkboxes that are not checked, it's blocked
11859 (save-excursion
11860 (org-back-to-heading t)
11861 (let ((beg (point)) end)
11862 (outline-next-heading)
11863 (setq end (point))
11864 (goto-char beg)
11865 (if (org-list-search-forward
11866 (concat (org-item-beginning-re)
11867 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11868 "\\[[- ]\\]")
11869 end t)
11870 (progn
11871 (if (boundp 'org-blocked-by-checkboxes)
11872 (setq org-blocked-by-checkboxes t))
11873 (throw 'dont-block nil)))))
11874 t))) ; do not block
11876 (defun org-entry-blocked-p ()
11877 "Is the current entry blocked?"
11878 (if (org-entry-get nil "NOBLOCKING")
11879 nil ;; Never block this entry
11880 (not
11881 (run-hook-with-args-until-failure
11882 'org-blocker-hook
11883 (list :type 'todo-state-change
11884 :position (point)
11885 :from 'todo
11886 :to 'done)))))
11888 (defun org-update-statistics-cookies (all)
11889 "Update the statistics cookie, either from TODO or from checkboxes.
11890 This should be called with the cursor in a line with a statistics cookie."
11891 (interactive "P")
11892 (if all
11893 (progn
11894 (org-update-checkbox-count 'all)
11895 (org-map-entries 'org-update-parent-todo-statistics))
11896 (if (not (org-at-heading-p))
11897 (org-update-checkbox-count)
11898 (let ((pos (move-marker (make-marker) (point)))
11899 end l1 l2)
11900 (ignore-errors (org-back-to-heading t))
11901 (if (not (org-at-heading-p))
11902 (org-update-checkbox-count)
11903 (setq l1 (org-outline-level))
11904 (setq end (save-excursion
11905 (outline-next-heading)
11906 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11907 (point)))
11908 (if (and (save-excursion
11909 (re-search-forward
11910 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11911 (not (save-excursion (re-search-forward
11912 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11913 (org-update-checkbox-count)
11914 (if (and l2 (> l2 l1))
11915 (progn
11916 (goto-char end)
11917 (org-update-parent-todo-statistics))
11918 (goto-char pos)
11919 (beginning-of-line 1)
11920 (while (re-search-forward
11921 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11922 (point-at-eol) t)
11923 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11924 (goto-char pos)
11925 (move-marker pos nil)))))
11927 (defvar org-entry-property-inherited-from) ;; defined below
11928 (defun org-update-parent-todo-statistics ()
11929 "Update any statistics cookie in the parent of the current headline.
11930 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11931 the entire subtree and this will travel up the hierarchy and update
11932 statistics everywhere."
11933 (let* ((prop (save-excursion (org-up-heading-safe)
11934 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11935 (recursive (or (not org-hierarchical-todo-statistics)
11936 (and prop (string-match "\\<recursive\\>" prop))))
11937 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11939 (first t)
11940 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11941 level ltoggle l1 new ndel
11942 (cnt-all 0) (cnt-done 0) is-percent kwd
11943 checkbox-beg ov ovs ove cookie-present)
11944 (catch 'exit
11945 (save-excursion
11946 (beginning-of-line 1)
11947 (setq ltoggle (funcall outline-level))
11948 ;; Three situations are to consider:
11950 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11951 ;; to the top-level ancestor on the headline;
11953 ;; 2. If parent has "recursive" property, repeat up to the
11954 ;; headline setting that property, taking inheritance into
11955 ;; account;
11957 ;; 3. Else, move up to direct parent and proceed only once.
11958 (while (and (setq level (org-up-heading-safe))
11959 (or recursive first)
11960 (>= (point) lim))
11961 (setq first nil cookie-present nil)
11962 (unless (and level
11963 (not (string-match
11964 "\\<checkbox\\>"
11965 (downcase (or (org-entry-get nil "COOKIE_DATA")
11966 "")))))
11967 (throw 'exit nil))
11968 (while (re-search-forward box-re (point-at-eol) t)
11969 (setq cnt-all 0 cnt-done 0 cookie-present t)
11970 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11971 (save-match-data
11972 (unless (outline-next-heading) (throw 'exit nil))
11973 (while (and (looking-at org-complex-heading-regexp)
11974 (> (setq l1 (length (match-string 1))) level))
11975 (setq kwd (and (or recursive (= l1 ltoggle))
11976 (match-string 2)))
11977 (if (or (eq org-provide-todo-statistics 'all-headlines)
11978 (and (listp org-provide-todo-statistics)
11979 (or (member kwd org-provide-todo-statistics)
11980 (member kwd org-done-keywords))))
11981 (setq cnt-all (1+ cnt-all))
11982 (if (eq org-provide-todo-statistics t)
11983 (and kwd (setq cnt-all (1+ cnt-all)))))
11984 (and (member kwd org-done-keywords)
11985 (setq cnt-done (1+ cnt-done)))
11986 (outline-next-heading)))
11987 (setq new
11988 (if is-percent
11989 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11990 (format "[%d/%d]" cnt-done cnt-all))
11991 ndel (- (match-end 0) checkbox-beg))
11992 ;; handle overlays when updating cookie from column view
11993 (when (setq ov (car (overlays-at checkbox-beg)))
11994 (setq ovs (overlay-start ov) ove (overlay-end ov))
11995 (delete-overlay ov))
11996 (goto-char checkbox-beg)
11997 (insert new)
11998 (delete-region (point) (+ (point) ndel))
11999 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12000 (when ov (move-overlay ov ovs ove)))
12001 (when cookie-present
12002 (run-hook-with-args 'org-after-todo-statistics-hook
12003 cnt-done (- cnt-all cnt-done))))))
12004 (run-hooks 'org-todo-statistics-hook)))
12006 (defvar org-after-todo-statistics-hook nil
12007 "Hook that is called after a TODO statistics cookie has been updated.
12008 Each function is called with two arguments: the number of not-done entries
12009 and the number of done entries.
12011 For example, the following function, when added to this hook, will switch
12012 an entry to DONE when all children are done, and back to TODO when new
12013 entries are set to a TODO status. Note that this hook is only called
12014 when there is a statistics cookie in the headline!
12016 (defun org-summary-todo (n-done n-not-done)
12017 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12018 (let (org-log-done org-log-states) ; turn off logging
12019 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12022 (defvar org-todo-statistics-hook nil
12023 "Hook that is run whenever Org thinks TODO statistics should be updated.
12024 This hook runs even if there is no statistics cookie present, in which case
12025 `org-after-todo-statistics-hook' would not run.")
12027 (defun org-todo-trigger-tag-changes (state)
12028 "Apply the changes defined in `org-todo-state-tags-triggers'."
12029 (let ((l org-todo-state-tags-triggers)
12030 changes)
12031 (when (or (not state) (equal state ""))
12032 (setq changes (append changes (cdr (assoc "" l)))))
12033 (when (and (stringp state) (> (length state) 0))
12034 (setq changes (append changes (cdr (assoc state l)))))
12035 (when (member state org-not-done-keywords)
12036 (setq changes (append changes (cdr (assoc 'todo l)))))
12037 (when (member state org-done-keywords)
12038 (setq changes (append changes (cdr (assoc 'done l)))))
12039 (dolist (c changes)
12040 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12042 (defun org-local-logging (value)
12043 "Get logging settings from a property VALUE."
12044 (let* (words w a)
12045 ;; directly set the variables, they are already local.
12046 (setq org-log-done nil
12047 org-log-repeat nil
12048 org-todo-log-states nil)
12049 (setq words (org-split-string value))
12050 (while (setq w (pop words))
12051 (cond
12052 ((setq a (assoc w org-startup-options))
12053 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12054 (set (nth 1 a) (nth 2 a))))
12055 ((setq a (org-extract-log-state-settings w))
12056 (and (member (car a) org-todo-keywords-1)
12057 (push a org-todo-log-states)))))))
12059 (defun org-get-todo-sequence-head (kwd)
12060 "Return the head of the TODO sequence to which KWD belongs.
12061 If KWD is not set, check if there is a text property remembering the
12062 right sequence."
12063 (let (p)
12064 (cond
12065 ((not kwd)
12066 (or (get-text-property (point-at-bol) 'org-todo-head)
12067 (progn
12068 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12069 nil (point-at-eol)))
12070 (get-text-property p 'org-todo-head))))
12071 ((not (member kwd org-todo-keywords-1))
12072 (car org-todo-keywords-1))
12073 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12075 (defun org-fast-todo-selection ()
12076 "Fast TODO keyword selection with single keys.
12077 Returns the new TODO keyword, or nil if no state change should occur."
12078 (let* ((fulltable org-todo-key-alist)
12079 (done-keywords org-done-keywords) ;; needed for the faces.
12080 (maxlen (apply 'max (mapcar
12081 (lambda (x)
12082 (if (stringp (car x)) (string-width (car x)) 0))
12083 fulltable)))
12084 (expert nil)
12085 (fwidth (+ maxlen 3 1 3))
12086 (ncol (/ (- (window-width) 4) fwidth))
12087 tg cnt e c tbl
12088 groups ingroup)
12089 (save-excursion
12090 (save-window-excursion
12091 (if expert
12092 (set-buffer (get-buffer-create " *Org todo*"))
12093 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12094 (erase-buffer)
12095 (org-set-local 'org-done-keywords done-keywords)
12096 (setq tbl fulltable cnt 0)
12097 (while (setq e (pop tbl))
12098 (cond
12099 ((equal e '(:startgroup))
12100 (push '() groups) (setq ingroup t)
12101 (when (not (= cnt 0))
12102 (setq cnt 0)
12103 (insert "\n"))
12104 (insert "{ "))
12105 ((equal e '(:endgroup))
12106 (setq ingroup nil cnt 0)
12107 (insert "}\n"))
12108 ((equal e '(:newline))
12109 (when (not (= cnt 0))
12110 (setq cnt 0)
12111 (insert "\n")
12112 (setq e (car tbl))
12113 (while (equal (car tbl) '(:newline))
12114 (insert "\n")
12115 (setq tbl (cdr tbl)))))
12117 (setq tg (car e) c (cdr e))
12118 (if ingroup (push tg (car groups)))
12119 (setq tg (org-add-props tg nil 'face
12120 (org-get-todo-face tg)))
12121 (if (and (= cnt 0) (not ingroup)) (insert " "))
12122 (insert "[" c "] " tg (make-string
12123 (- fwidth 4 (length tg)) ?\ ))
12124 (when (= (setq cnt (1+ cnt)) ncol)
12125 (insert "\n")
12126 (if ingroup (insert " "))
12127 (setq cnt 0)))))
12128 (insert "\n")
12129 (goto-char (point-min))
12130 (if (not expert) (org-fit-window-to-buffer))
12131 (message "[a-z..]:Set [SPC]:clear")
12132 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12133 (cond
12134 ((or (= c ?\C-g)
12135 (and (= c ?q) (not (rassoc c fulltable))))
12136 (setq quit-flag t))
12137 ((= c ?\ ) nil)
12138 ((setq e (rassoc c fulltable) tg (car e))
12140 (t (setq quit-flag t)))))))
12142 (defun org-entry-is-todo-p ()
12143 (member (org-get-todo-state) org-not-done-keywords))
12145 (defun org-entry-is-done-p ()
12146 (member (org-get-todo-state) org-done-keywords))
12148 (defun org-get-todo-state ()
12149 (save-excursion
12150 (org-back-to-heading t)
12151 (and (looking-at org-todo-line-regexp)
12152 (match-end 2)
12153 (match-string 2))))
12155 (defun org-at-date-range-p (&optional inactive-ok)
12156 "Is the cursor inside a date range?"
12157 (interactive)
12158 (save-excursion
12159 (catch 'exit
12160 (let ((pos (point)))
12161 (skip-chars-backward "^[<\r\n")
12162 (skip-chars-backward "<[")
12163 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12164 (>= (match-end 0) pos)
12165 (throw 'exit t))
12166 (skip-chars-backward "^<[\r\n")
12167 (skip-chars-backward "<[")
12168 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12169 (>= (match-end 0) pos)
12170 (throw 'exit t)))
12171 nil)))
12173 (defun org-get-repeat (&optional tagline)
12174 "Check if there is a deadline/schedule with repeater in this entry."
12175 (save-match-data
12176 (save-excursion
12177 (org-back-to-heading t)
12178 (and (re-search-forward (if tagline
12179 (concat tagline "\\s-*" org-repeat-re)
12180 org-repeat-re)
12181 (org-entry-end-position) t)
12182 (match-string-no-properties 1)))))
12184 (defvar org-last-changed-timestamp)
12185 (defvar org-last-inserted-timestamp)
12186 (defvar org-log-post-message)
12187 (defvar org-log-note-purpose)
12188 (defvar org-log-note-how)
12189 (defvar org-log-note-extra)
12190 (defun org-auto-repeat-maybe (done-word)
12191 "Check if the current headline contains a repeated deadline/schedule.
12192 If yes, set TODO state back to what it was and change the base date
12193 of repeating deadline/scheduled time stamps to new date.
12194 This function is run automatically after each state change to a DONE state."
12195 ;; last-state is dynamically scoped into this function
12196 (let* ((repeat (org-get-repeat))
12197 (aa (assoc org-last-state org-todo-kwd-alist))
12198 (interpret (nth 1 aa))
12199 (head (nth 2 aa))
12200 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12201 (msg "Entry repeats: ")
12202 (org-log-done nil)
12203 (org-todo-log-states nil)
12204 re type n what ts time to-state)
12205 (when repeat
12206 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12207 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12208 org-todo-repeat-to-state))
12209 (unless (and to-state (member to-state org-todo-keywords-1))
12210 (setq to-state (if (eq interpret 'type) org-last-state head)))
12211 (org-todo to-state)
12212 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12213 (org-entry-put nil "LAST_REPEAT" (format-time-string
12214 (org-time-stamp-format t t))))
12215 (when org-log-repeat
12216 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12217 (memq 'org-add-log-note post-command-hook))
12218 ;; OK, we are already setup for some record
12219 (if (eq org-log-repeat 'note)
12220 ;; make sure we take a note, not only a time stamp
12221 (setq org-log-note-how 'note))
12222 ;; Set up for taking a record
12223 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12224 org-last-state
12225 'findpos org-log-repeat)))
12226 (org-back-to-heading t)
12227 (org-add-planning-info nil nil 'closed)
12228 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12229 org-deadline-time-regexp "\\)\\|\\("
12230 org-ts-regexp "\\)"))
12231 (while (re-search-forward
12232 re (save-excursion (outline-next-heading) (point)) t)
12233 (setq type (if (match-end 1) org-scheduled-string
12234 (if (match-end 3) org-deadline-string "Plain:"))
12235 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12236 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12237 (setq n (string-to-number (match-string 2 ts))
12238 what (match-string 3 ts))
12239 (if (equal what "w") (setq n (* n 7) what "d"))
12240 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12241 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12242 ;; Preparation, see if we need to modify the start date for the change
12243 (when (match-end 1)
12244 (setq time (save-match-data (org-time-string-to-time ts)))
12245 (cond
12246 ((equal (match-string 1 ts) ".")
12247 ;; Shift starting date to today
12248 (org-timestamp-change
12249 (- (org-today) (time-to-days time))
12250 'day))
12251 ((equal (match-string 1 ts) "+")
12252 (let ((nshiftmax 10) (nshift 0))
12253 (while (or (= nshift 0)
12254 (<= (time-to-days time)
12255 (time-to-days (current-time))))
12256 (when (= (incf nshift) nshiftmax)
12257 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12258 (error "Abort")))
12259 (org-timestamp-change n (cdr (assoc what whata)))
12260 (org-at-timestamp-p t)
12261 (setq ts (match-string 1))
12262 (setq time (save-match-data (org-time-string-to-time ts)))))
12263 (org-timestamp-change (- n) (cdr (assoc what whata)))
12264 ;; rematch, so that we have everything in place for the real shift
12265 (org-at-timestamp-p t)
12266 (setq ts (match-string 1))
12267 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12268 (org-timestamp-change n (cdr (assoc what whata)))
12269 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12270 (setq org-log-post-message msg)
12271 (message "%s" msg))))
12273 (defun org-show-todo-tree (arg)
12274 "Make a compact tree which shows all headlines marked with TODO.
12275 The tree will show the lines where the regexp matches, and all higher
12276 headlines above the match.
12277 With a \\[universal-argument] prefix, prompt for a regexp to match.
12278 With a numeric prefix N, construct a sparse tree for the Nth element
12279 of `org-todo-keywords-1'."
12280 (interactive "P")
12281 (let ((case-fold-search nil)
12282 (kwd-re
12283 (cond ((null arg) org-not-done-regexp)
12284 ((equal arg '(4))
12285 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12286 (mapcar 'list org-todo-keywords-1))))
12287 (concat "\\("
12288 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12289 "\\)\\>")))
12290 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12291 (regexp-quote (nth (1- (prefix-numeric-value arg))
12292 org-todo-keywords-1)))
12293 (t (error "Invalid prefix argument: %s" arg)))))
12294 (message "%d TODO entries found"
12295 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12297 (defun org-deadline (&optional remove time)
12298 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12299 With argument REMOVE, remove any deadline from the item.
12300 With argument TIME, set the deadline at the corresponding date. TIME
12301 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12302 (interactive "P")
12303 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12304 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12305 'region-start-level 'region))
12306 org-loop-over-headlines-in-active-region)
12307 (org-map-entries
12308 `(org-deadline ',remove ,time)
12309 org-loop-over-headlines-in-active-region
12310 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12311 (let* ((old-date (org-entry-get nil "DEADLINE"))
12312 (repeater (and old-date
12313 (string-match
12314 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12315 old-date)
12316 (match-string 1 old-date))))
12317 (if remove
12318 (progn
12319 (when (and old-date org-log-redeadline)
12320 (org-add-log-setup 'deldeadline nil old-date 'findpos
12321 org-log-redeadline))
12322 (org-remove-timestamp-with-keyword org-deadline-string)
12323 (message "Item no longer has a deadline."))
12324 (org-add-planning-info 'deadline time 'closed)
12325 (when (and old-date org-log-redeadline
12326 (not (equal old-date
12327 (substring org-last-inserted-timestamp 1 -1))))
12328 (org-add-log-setup 'redeadline nil old-date 'findpos
12329 org-log-redeadline))
12330 (when repeater
12331 (save-excursion
12332 (org-back-to-heading t)
12333 (when (re-search-forward (concat org-deadline-string " "
12334 org-last-inserted-timestamp)
12335 (save-excursion
12336 (outline-next-heading) (point)) t)
12337 (goto-char (1- (match-end 0)))
12338 (insert " " repeater)
12339 (setq org-last-inserted-timestamp
12340 (concat (substring org-last-inserted-timestamp 0 -1)
12341 " " repeater
12342 (substring org-last-inserted-timestamp -1))))))
12343 (message "Deadline on %s" org-last-inserted-timestamp)))))
12345 (defun org-schedule (&optional remove time)
12346 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12347 With argument REMOVE, remove any scheduling date from the item.
12348 With argument TIME, scheduled at the corresponding date. TIME can
12349 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12350 (interactive "P")
12351 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12352 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12353 'region-start-level 'region))
12354 org-loop-over-headlines-in-active-region)
12355 (org-map-entries
12356 `(org-schedule ',remove ,time)
12357 org-loop-over-headlines-in-active-region
12358 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12359 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12360 (repeater (and old-date
12361 (string-match
12362 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12363 old-date)
12364 (match-string 1 old-date))))
12365 (if remove
12366 (progn
12367 (when (and old-date org-log-reschedule)
12368 (org-add-log-setup 'delschedule nil old-date 'findpos
12369 org-log-reschedule))
12370 (org-remove-timestamp-with-keyword org-scheduled-string)
12371 (message "Item is no longer scheduled."))
12372 (org-add-planning-info 'scheduled time 'closed)
12373 (when (and old-date org-log-reschedule
12374 (not (equal old-date
12375 (substring org-last-inserted-timestamp 1 -1))))
12376 (org-add-log-setup 'reschedule nil old-date 'findpos
12377 org-log-reschedule))
12378 (when repeater
12379 (save-excursion
12380 (org-back-to-heading t)
12381 (when (re-search-forward (concat org-scheduled-string " "
12382 org-last-inserted-timestamp)
12383 (save-excursion
12384 (outline-next-heading) (point)) t)
12385 (goto-char (1- (match-end 0)))
12386 (insert " " repeater)
12387 (setq org-last-inserted-timestamp
12388 (concat (substring org-last-inserted-timestamp 0 -1)
12389 " " repeater
12390 (substring org-last-inserted-timestamp -1))))))
12391 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12393 (defun org-get-scheduled-time (pom &optional inherit)
12394 "Get the scheduled time as a time tuple, of a format suitable
12395 for calling org-schedule with, or if there is no scheduling,
12396 returns nil."
12397 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12398 (when time
12399 (apply 'encode-time (org-parse-time-string time)))))
12401 (defun org-get-deadline-time (pom &optional inherit)
12402 "Get the deadline as a time tuple, of a format suitable for
12403 calling org-deadline with, or if there is no scheduling, returns
12404 nil."
12405 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12406 (when time
12407 (apply 'encode-time (org-parse-time-string time)))))
12409 (defun org-remove-timestamp-with-keyword (keyword)
12410 "Remove all time stamps with KEYWORD in the current entry."
12411 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12412 beg)
12413 (save-excursion
12414 (org-back-to-heading t)
12415 (setq beg (point))
12416 (outline-next-heading)
12417 (while (re-search-backward re beg t)
12418 (replace-match "")
12419 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12420 (equal (char-before) ?\ ))
12421 (backward-delete-char 1)
12422 (if (string-match "^[ \t]*$" (buffer-substring
12423 (point-at-bol) (point-at-eol)))
12424 (delete-region (point-at-bol)
12425 (min (point-max) (1+ (point-at-eol))))))))))
12427 (defun org-add-planning-info (what &optional time &rest remove)
12428 "Insert new timestamp with keyword in the line directly after the headline.
12429 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12430 If non is given, the user is prompted for a date.
12431 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12432 be removed."
12433 (interactive)
12434 (let (org-time-was-given org-end-time-was-given ts
12435 end default-time default-input)
12437 (catch 'exit
12438 (when (and (memq what '(scheduled deadline))
12439 (or (not time)
12440 (and (stringp time)
12441 (string-match "^[-+]+[0-9]" time))))
12442 ;; Try to get a default date/time from existing timestamp
12443 (save-excursion
12444 (org-back-to-heading t)
12445 (setq end (save-excursion (outline-next-heading) (point)))
12446 (when (re-search-forward (if (eq what 'scheduled)
12447 org-scheduled-time-regexp
12448 org-deadline-time-regexp)
12449 end t)
12450 (setq ts (match-string 1)
12451 default-time
12452 (apply 'encode-time (org-parse-time-string ts))
12453 default-input (and ts (org-get-compact-tod ts))))))
12454 (when what
12455 (setq time
12456 (if (stringp time)
12457 ;; This is a string (relative or absolute), set proper date
12458 (apply 'encode-time
12459 (org-read-date-analyze
12460 time default-time (decode-time default-time)))
12461 ;; If necessary, get the time from the user
12462 (or time (org-read-date nil 'to-time nil nil
12463 default-time default-input)))))
12465 (when (and org-insert-labeled-timestamps-at-point
12466 (member what '(scheduled deadline)))
12467 (insert
12468 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12469 (org-insert-time-stamp time org-time-was-given
12470 nil nil nil (list org-end-time-was-given))
12471 (setq what nil))
12472 (save-excursion
12473 (save-restriction
12474 (let (col list elt ts buffer-invisibility-spec)
12475 (org-back-to-heading t)
12476 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12477 (goto-char (match-end 1))
12478 (setq col (current-column))
12479 (goto-char (match-end 0))
12480 (if (eobp) (insert "\n") (forward-char 1))
12481 (when (and (not what)
12482 (not (looking-at
12483 (concat "[ \t]*"
12484 org-keyword-time-not-clock-regexp))))
12485 ;; Nothing to add, nothing to remove...... :-)
12486 (throw 'exit nil))
12487 (if (and (not (looking-at org-outline-regexp))
12488 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12489 "[^\r\n]*"))
12490 (not (equal (match-string 1) org-clock-string)))
12491 (narrow-to-region (match-beginning 0) (match-end 0))
12492 (insert-before-markers "\n")
12493 (backward-char 1)
12494 (narrow-to-region (point) (point))
12495 (and org-adapt-indentation (org-indent-to-column col)))
12496 ;; Check if we have to remove something.
12497 (setq list (cons what remove))
12498 (while list
12499 (setq elt (pop list))
12500 (when (or (and (eq elt 'scheduled)
12501 (re-search-forward org-scheduled-time-regexp nil t))
12502 (and (eq elt 'deadline)
12503 (re-search-forward org-deadline-time-regexp nil t))
12504 (and (eq elt 'closed)
12505 (re-search-forward org-closed-time-regexp nil t)))
12506 (replace-match "")
12507 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12508 (and (looking-at "[ \t]+") (replace-match ""))
12509 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12510 (when what
12511 (insert
12512 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12513 (cond ((eq what 'scheduled) org-scheduled-string)
12514 ((eq what 'deadline) org-deadline-string)
12515 ((eq what 'closed) org-closed-string))
12516 " ")
12517 (setq ts (org-insert-time-stamp
12518 time
12519 (or org-time-was-given
12520 (and (eq what 'closed) org-log-done-with-time))
12521 (eq what 'closed)
12522 nil nil (list org-end-time-was-given)))
12523 (insert
12524 (if (not (or (bolp) (eq (char-before) ?\ )
12525 (memq (char-after) '(32 10))
12526 (eobp))) " " ""))
12527 (end-of-line 1))
12528 (goto-char (point-min))
12529 (widen)
12530 (if (and (looking-at "[ \t]*\n")
12531 (equal (char-before) ?\n))
12532 (delete-region (1- (point)) (point-at-eol)))
12533 ts))))))
12535 (defvar org-log-note-marker (make-marker))
12536 (defvar org-log-note-purpose nil)
12537 (defvar org-log-note-state nil)
12538 (defvar org-log-note-previous-state nil)
12539 (defvar org-log-note-how nil)
12540 (defvar org-log-note-extra nil)
12541 (defvar org-log-note-window-configuration nil)
12542 (defvar org-log-note-return-to (make-marker))
12543 (defvar org-log-note-effective-time nil
12544 "Remembered current time so that dynamically scoped
12545 `org-extend-today-until' affects tha timestamps in state change
12546 log")
12548 (defvar org-log-post-message nil
12549 "Message to be displayed after a log note has been stored.
12550 The auto-repeater uses this.")
12552 (defun org-add-note ()
12553 "Add a note to the current entry.
12554 This is done in the same way as adding a state change note."
12555 (interactive)
12556 (org-add-log-setup 'note nil nil 'findpos nil))
12558 (defvar org-property-end-re)
12559 (defun org-add-log-setup (&optional purpose state prev-state
12560 findpos how extra)
12561 "Set up the post command hook to take a note.
12562 If this is about to TODO state change, the new state is expected in STATE.
12563 When FINDPOS is non-nil, find the correct position for the note in
12564 the current entry. If not, assume that it can be inserted at point.
12565 HOW is an indicator what kind of note should be created.
12566 EXTRA is additional text that will be inserted into the notes buffer."
12567 (let* ((org-log-into-drawer (org-log-into-drawer))
12568 (drawer (cond ((stringp org-log-into-drawer)
12569 org-log-into-drawer)
12570 (org-log-into-drawer "LOGBOOK"))))
12571 (save-restriction
12572 (save-excursion
12573 (when findpos
12574 (org-back-to-heading t)
12575 (narrow-to-region (point) (save-excursion
12576 (outline-next-heading) (point)))
12577 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12578 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12579 "[^\r\n]*\\)?"))
12580 (goto-char (match-end 0))
12581 (cond
12582 (drawer
12583 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12584 nil t)
12585 (progn
12586 (goto-char (match-end 0))
12587 (or org-log-states-order-reversed
12588 (and (re-search-forward org-property-end-re nil t)
12589 (goto-char (1- (match-beginning 0))))))
12590 (insert "\n:" drawer ":\n:END:")
12591 (beginning-of-line 0)
12592 (org-indent-line)
12593 (beginning-of-line 2)
12594 (org-indent-line)
12595 (end-of-line 0)))
12596 ((and org-log-state-notes-insert-after-drawers
12597 (save-excursion
12598 (forward-line) (looking-at org-drawer-regexp)))
12599 (forward-line)
12600 (while (looking-at org-drawer-regexp)
12601 (goto-char (match-end 0))
12602 (re-search-forward org-property-end-re (point-max) t)
12603 (forward-line))
12604 (forward-line -1)))
12605 (unless org-log-states-order-reversed
12606 (and (= (char-after) ?\n) (forward-char 1))
12607 (org-skip-over-state-notes)
12608 (skip-chars-backward " \t\n\r")))
12609 (move-marker org-log-note-marker (point))
12610 (setq org-log-note-purpose purpose
12611 org-log-note-state state
12612 org-log-note-previous-state prev-state
12613 org-log-note-how how
12614 org-log-note-extra extra
12615 org-log-note-effective-time (org-current-effective-time))
12616 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12618 (defun org-skip-over-state-notes ()
12619 "Skip past the list of State notes in an entry."
12620 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12621 (when (ignore-errors (goto-char (org-in-item-p)))
12622 (let* ((struct (org-list-struct))
12623 (prevs (org-list-prevs-alist struct)))
12624 (while (looking-at "[ \t]*- State")
12625 (goto-char (or (org-list-get-next-item (point) struct prevs)
12626 (org-list-get-item-end (point) struct)))))))
12628 (defun org-add-log-note (&optional purpose)
12629 "Pop up a window for taking a note, and add this note later at point."
12630 (remove-hook 'post-command-hook 'org-add-log-note)
12631 (setq org-log-note-window-configuration (current-window-configuration))
12632 (delete-other-windows)
12633 (move-marker org-log-note-return-to (point))
12634 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12635 (goto-char org-log-note-marker)
12636 (org-switch-to-buffer-other-window "*Org Note*")
12637 (erase-buffer)
12638 (if (memq org-log-note-how '(time state))
12639 (let (current-prefix-arg) (org-store-log-note))
12640 (let ((org-inhibit-startup t)) (org-mode))
12641 (insert (format "# Insert note for %s.
12642 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12643 (cond
12644 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12645 ((eq org-log-note-purpose 'done) "closed todo item")
12646 ((eq org-log-note-purpose 'state)
12647 (format "state change from \"%s\" to \"%s\""
12648 (or org-log-note-previous-state "")
12649 (or org-log-note-state "")))
12650 ((eq org-log-note-purpose 'reschedule)
12651 "rescheduling")
12652 ((eq org-log-note-purpose 'delschedule)
12653 "no longer scheduled")
12654 ((eq org-log-note-purpose 'redeadline)
12655 "changing deadline")
12656 ((eq org-log-note-purpose 'deldeadline)
12657 "removing deadline")
12658 ((eq org-log-note-purpose 'refile)
12659 "refiling")
12660 ((eq org-log-note-purpose 'note)
12661 "this entry")
12662 (t (error "This should not happen")))))
12663 (if org-log-note-extra (insert org-log-note-extra))
12664 (org-set-local 'org-finish-function 'org-store-log-note)
12665 (run-hooks 'org-log-buffer-setup-hook)))
12667 (defvar org-note-abort nil) ; dynamically scoped
12668 (defun org-store-log-note ()
12669 "Finish taking a log note, and insert it to where it belongs."
12670 (let ((txt (buffer-string))
12671 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12672 lines ind bul)
12673 (kill-buffer (current-buffer))
12674 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12675 (setq txt (replace-match "" t t txt)))
12676 (if (string-match "\\s-+\\'" txt)
12677 (setq txt (replace-match "" t t txt)))
12678 (setq lines (org-split-string txt "\n"))
12679 (when (and note (string-match "\\S-" note))
12680 (setq note
12681 (org-replace-escapes
12682 note
12683 (list (cons "%u" (user-login-name))
12684 (cons "%U" user-full-name)
12685 (cons "%t" (format-time-string
12686 (org-time-stamp-format 'long 'inactive)
12687 org-log-note-effective-time))
12688 (cons "%T" (format-time-string
12689 (org-time-stamp-format 'long nil)
12690 org-log-note-effective-time))
12691 (cons "%d" (format-time-string
12692 (org-time-stamp-format nil 'inactive)
12693 org-log-note-effective-time))
12694 (cons "%D" (format-time-string
12695 (org-time-stamp-format nil nil)
12696 org-log-note-effective-time))
12697 (cons "%s" (if org-log-note-state
12698 (concat "\"" org-log-note-state "\"")
12699 ""))
12700 (cons "%S" (if org-log-note-previous-state
12701 (concat "\"" org-log-note-previous-state "\"")
12702 "\"\"")))))
12703 (if lines (setq note (concat note " \\\\")))
12704 (push note lines))
12705 (when (or current-prefix-arg org-note-abort)
12706 (when org-log-into-drawer
12707 (org-remove-empty-drawer-at
12708 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12709 org-log-note-marker))
12710 (setq lines nil))
12711 (when lines
12712 (with-current-buffer (marker-buffer org-log-note-marker)
12713 (save-excursion
12714 (goto-char org-log-note-marker)
12715 (move-marker org-log-note-marker nil)
12716 (end-of-line 1)
12717 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12718 (setq ind (save-excursion
12719 (if (ignore-errors (goto-char (org-in-item-p)))
12720 (let ((struct (org-list-struct)))
12721 (org-list-get-ind
12722 (org-list-get-top-point struct) struct))
12723 (skip-chars-backward " \r\t\n")
12724 (cond
12725 ((and (org-at-heading-p)
12726 org-adapt-indentation)
12727 (1+ (org-current-level)))
12728 ((org-at-heading-p) 0)
12729 (t (org-get-indentation))))))
12730 (setq bul (org-list-bullet-string "-"))
12731 (org-indent-line-to ind)
12732 (insert bul (pop lines))
12733 (let ((ind-body (+ (length bul) ind)))
12734 (while lines
12735 (insert "\n")
12736 (org-indent-line-to ind-body)
12737 (insert (pop lines))))
12738 (message "Note stored")
12739 (org-back-to-heading t)
12740 (org-cycle-hide-drawers 'children)))))
12741 (set-window-configuration org-log-note-window-configuration)
12742 (with-current-buffer (marker-buffer org-log-note-return-to)
12743 (goto-char org-log-note-return-to))
12744 (move-marker org-log-note-return-to nil)
12745 (and org-log-post-message (message "%s" org-log-post-message)))
12747 (defun org-remove-empty-drawer-at (drawer pos)
12748 "Remove an empty drawer DRAWER at position POS.
12749 POS may also be a marker."
12750 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12751 (save-excursion
12752 (save-restriction
12753 (widen)
12754 (goto-char pos)
12755 (if (org-in-regexp
12756 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12757 (replace-match ""))))))
12759 (defvar org-ts-type nil)
12760 (defun org-sparse-tree (&optional arg type)
12761 "Create a sparse tree, prompt for the details.
12762 This command can create sparse trees. You first need to select the type
12763 of match used to create the tree:
12765 t Show all TODO entries.
12766 T Show entries with a specific TODO keyword.
12767 m Show entries selected by a tags/property match.
12768 p Enter a property name and its value (both with completion on existing
12769 names/values) and show entries with that property.
12770 r Show entries matching a regular expression (`/' can be used as well).
12771 b Show deadlines and scheduled items before a date.
12772 a Show deadlines and scheduled items after a date.
12773 d Show deadlines due within `org-deadline-warning-days'.
12774 D Show deadlines and scheduled items between a date range."
12775 (interactive "P")
12776 (let (ans kwd value ts-type)
12777 (setq type (or type org-sparse-tree-default-date-type))
12778 (setq org-ts-type type)
12779 (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"
12780 (cond ((eq type 'all) "all timestamps")
12781 ((eq type 'scheduled) "only scheduled")
12782 ((eq type 'deadline) "only deadline")
12783 ((eq type 'active) "only active timestamps")
12784 ((eq type 'inactive) "only inactive timestamps")
12785 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12786 (t "scheduled/deadline")))
12787 (setq ans (read-char-exclusive))
12788 (cond
12789 ((equal ans ?c)
12790 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12791 ((equal ans ?d)
12792 (call-interactively 'org-check-deadlines))
12793 ((equal ans ?b)
12794 (call-interactively 'org-check-before-date))
12795 ((equal ans ?a)
12796 (call-interactively 'org-check-after-date))
12797 ((equal ans ?D)
12798 (call-interactively 'org-check-dates-range))
12799 ((equal ans ?t)
12800 (org-show-todo-tree nil))
12801 ((equal ans ?T)
12802 (org-show-todo-tree '(4)))
12803 ((member ans '(?T ?m))
12804 (call-interactively 'org-match-sparse-tree))
12805 ((member ans '(?p ?P))
12806 (setq kwd (org-icompleting-read "Property: "
12807 (mapcar 'list (org-buffer-property-keys))))
12808 (setq value (org-icompleting-read "Value: "
12809 (mapcar 'list (org-property-values kwd))))
12810 (unless (string-match "\\`{.*}\\'" value)
12811 (setq value (concat "\"" value "\"")))
12812 (org-match-sparse-tree arg (concat kwd "=" value)))
12813 ((member ans '(?r ?R ?/))
12814 (call-interactively 'org-occur))
12815 (t (error "No such sparse tree command \"%c\"" ans)))))
12817 (defvar org-occur-highlights nil
12818 "List of overlays used for occur matches.")
12819 (make-variable-buffer-local 'org-occur-highlights)
12820 (defvar org-occur-parameters nil
12821 "Parameters of the active org-occur calls.
12822 This is a list, each call to org-occur pushes as cons cell,
12823 containing the regular expression and the callback, onto the list.
12824 The list can contain several entries if `org-occur' has been called
12825 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12826 will only contain one set of parameters. When the highlights are
12827 removed (for example with `C-c C-c', or with the next edit (depending
12828 on `org-remove-highlights-with-change'), this variable is emptied
12829 as well.")
12830 (make-variable-buffer-local 'org-occur-parameters)
12832 (defun org-occur (regexp &optional keep-previous callback)
12833 "Make a compact tree which shows all matches of REGEXP.
12834 The tree will show the lines where the regexp matches, and all higher
12835 headlines above the match. It will also show the heading after the match,
12836 to make sure editing the matching entry is easy.
12837 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12838 call to `org-occur' will be kept, to allow stacking of calls to this
12839 command.
12840 If CALLBACK is non-nil, it is a function which is called to confirm
12841 that the match should indeed be shown."
12842 (interactive "sRegexp: \nP")
12843 (when (equal regexp "")
12844 (error "Regexp cannot be empty"))
12845 (unless keep-previous
12846 (org-remove-occur-highlights nil nil t))
12847 (push (cons regexp callback) org-occur-parameters)
12848 (let ((cnt 0))
12849 (save-excursion
12850 (goto-char (point-min))
12851 (if (or (not keep-previous) ; do not want to keep
12852 (not org-occur-highlights)) ; no previous matches
12853 ;; hide everything
12854 (org-overview))
12855 (while (re-search-forward regexp nil t)
12856 (when (or (not callback)
12857 (save-match-data (funcall callback)))
12858 (setq cnt (1+ cnt))
12859 (when org-highlight-sparse-tree-matches
12860 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12861 (org-show-context 'occur-tree))))
12862 (when org-remove-highlights-with-change
12863 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12864 nil 'local))
12865 (unless org-sparse-tree-open-archived-trees
12866 (org-hide-archived-subtrees (point-min) (point-max)))
12867 (run-hooks 'org-occur-hook)
12868 (if (org-called-interactively-p 'interactive)
12869 (message "%d match(es) for regexp %s" cnt regexp))
12870 cnt))
12872 (defun org-occur-next-match (&optional n reset)
12873 "Function for `next-error-function' to find sparse tree matches.
12874 N is the number of matches to move, when negative move backwards.
12875 RESET is entirely ignored - this function always goes back to the
12876 starting point when no match is found."
12877 (let* ((limit (if (< n 0) (point-min) (point-max)))
12878 (search-func (if (< n 0)
12879 'previous-single-char-property-change
12880 'next-single-char-property-change))
12881 (n (abs n))
12882 (pos (point))
12884 (catch 'exit
12885 (while (setq p1 (funcall search-func (point) 'org-type))
12886 (when (equal p1 limit)
12887 (goto-char pos)
12888 (error "No more matches"))
12889 (when (equal (get-char-property p1 'org-type) 'org-occur)
12890 (setq n (1- n))
12891 (when (= n 0)
12892 (goto-char p1)
12893 (throw 'exit (point))))
12894 (goto-char p1))
12895 (goto-char p1)
12896 (error "No more matches"))))
12898 (defun org-show-context (&optional key)
12899 "Make sure point and context are visible.
12900 How much context is shown depends upon the variables
12901 `org-show-hierarchy-above', `org-show-following-heading',
12902 `org-show-entry-below' and `org-show-siblings'."
12903 (let ((heading-p (org-at-heading-p t))
12904 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12905 (following-p (org-get-alist-option org-show-following-heading key))
12906 (entry-p (org-get-alist-option org-show-entry-below key))
12907 (siblings-p (org-get-alist-option org-show-siblings key)))
12908 (catch 'exit
12909 ;; Show heading or entry text
12910 (if (and heading-p (not entry-p))
12911 (org-flag-heading nil) ; only show the heading
12912 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12913 (org-show-hidden-entry))) ; show entire entry
12914 (when following-p
12915 ;; Show next sibling, or heading below text
12916 (save-excursion
12917 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12918 (org-flag-heading nil))))
12919 (when siblings-p (org-show-siblings))
12920 (when hierarchy-p
12921 ;; show all higher headings, possibly with siblings
12922 (save-excursion
12923 (while (and (condition-case nil
12924 (progn (org-up-heading-all 1) t)
12925 (error nil))
12926 (not (bobp)))
12927 (org-flag-heading nil)
12928 (when siblings-p (org-show-siblings))))))))
12930 (defvar org-reveal-start-hook nil
12931 "Hook run before revealing a location.")
12933 (defun org-reveal (&optional siblings)
12934 "Show current entry, hierarchy above it, and the following headline.
12935 This can be used to show a consistent set of context around locations
12936 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12937 not t for the search context.
12939 With optional argument SIBLINGS, on each level of the hierarchy all
12940 siblings are shown. This repairs the tree structure to what it would
12941 look like when opened with hierarchical calls to `org-cycle'.
12942 With double optional argument \\[universal-argument] \\[universal-argument], \
12943 go to the parent and show the
12944 entire tree."
12945 (interactive "P")
12946 (run-hooks 'org-reveal-start-hook)
12947 (let ((org-show-hierarchy-above t)
12948 (org-show-following-heading t)
12949 (org-show-siblings (if siblings t org-show-siblings)))
12950 (org-show-context nil))
12951 (when (equal siblings '(16))
12952 (save-excursion
12953 (when (org-up-heading-safe)
12954 (org-show-subtree)
12955 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12957 (defun org-highlight-new-match (beg end)
12958 "Highlight from BEG to END and mark the highlight is an occur headline."
12959 (let ((ov (make-overlay beg end)))
12960 (overlay-put ov 'face 'secondary-selection)
12961 (overlay-put ov 'org-type 'org-occur)
12962 (push ov org-occur-highlights)))
12964 (defun org-remove-occur-highlights (&optional beg end noremove)
12965 "Remove the occur highlights from the buffer.
12966 BEG and END are ignored. If NOREMOVE is nil, remove this function
12967 from the `before-change-functions' in the current buffer."
12968 (interactive)
12969 (unless org-inhibit-highlight-removal
12970 (mapc 'delete-overlay org-occur-highlights)
12971 (setq org-occur-highlights nil)
12972 (setq org-occur-parameters nil)
12973 (unless noremove
12974 (remove-hook 'before-change-functions
12975 'org-remove-occur-highlights 'local))))
12977 ;;;; Priorities
12979 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12980 "Regular expression matching the priority indicator.")
12982 (defvar org-remove-priority-next-time nil)
12984 (defun org-priority-up ()
12985 "Increase the priority of the current item."
12986 (interactive)
12987 (org-priority 'up))
12989 (defun org-priority-down ()
12990 "Decrease the priority of the current item."
12991 (interactive)
12992 (org-priority 'down))
12994 (defun org-priority (&optional action show)
12995 "Change the priority of an item.
12996 ACTION can be `set', `up', `down', or a character."
12997 (interactive "P")
12998 (if (equal action '(4))
12999 (org-show-priority)
13000 (unless org-enable-priority-commands
13001 (error "Priority commands are disabled"))
13002 (setq action (or action 'set))
13003 (let (current new news have remove)
13004 (save-excursion
13005 (org-back-to-heading t)
13006 (if (looking-at org-priority-regexp)
13007 (setq current (string-to-char (match-string 2))
13008 have t))
13009 (cond
13010 ((eq action 'remove)
13011 (setq remove t new ?\ ))
13012 ((or (eq action 'set)
13013 (if (featurep 'xemacs) (characterp action) (integerp action)))
13014 (if (not (eq action 'set))
13015 (setq new action)
13016 (message "Priority %c-%c, SPC to remove: "
13017 org-highest-priority org-lowest-priority)
13018 (save-match-data
13019 (setq new (read-char-exclusive))))
13020 (if (and (= (upcase org-highest-priority) org-highest-priority)
13021 (= (upcase org-lowest-priority) org-lowest-priority))
13022 (setq new (upcase new)))
13023 (cond ((equal new ?\ ) (setq remove t))
13024 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13025 (error "Priority must be between `%c' and `%c'"
13026 org-highest-priority org-lowest-priority))))
13027 ((eq action 'up)
13028 (setq new (if have
13029 (1- current) ; normal cycling
13030 ;; last priority was empty
13031 (if (eq last-command this-command)
13032 org-lowest-priority ; wrap around empty to lowest
13033 ;; default
13034 (if org-priority-start-cycle-with-default
13035 org-default-priority
13036 (1- org-default-priority))))))
13037 ((eq action 'down)
13038 (setq new (if have
13039 (1+ current) ; normal cycling
13040 ;; last priority was empty
13041 (if (eq last-command this-command)
13042 org-highest-priority ; wrap around empty to highest
13043 ;; default
13044 (if org-priority-start-cycle-with-default
13045 org-default-priority
13046 (1+ org-default-priority))))))
13047 (t (error "Invalid action")))
13048 (if (or (< (upcase new) org-highest-priority)
13049 (> (upcase new) org-lowest-priority))
13050 (if (and (memq action '(up down))
13051 (not have) (not (eq last-command this-command)))
13052 ;; `new' is from default priority
13053 (error
13054 "The default can not be set, see `org-default-priority' why")
13055 ;; normal cycling: `new' is beyond highest/lowest priority
13056 ;; and is wrapped around to the empty priority
13057 (setq remove t)))
13058 (setq news (format "%c" new))
13059 (if have
13060 (if remove
13061 (replace-match "" t t nil 1)
13062 (replace-match news t t nil 2))
13063 (if remove
13064 (error "No priority cookie found in line")
13065 (let ((case-fold-search nil))
13066 (looking-at org-todo-line-regexp))
13067 (if (match-end 2)
13068 (progn
13069 (goto-char (match-end 2))
13070 (insert " [#" news "]"))
13071 (goto-char (match-beginning 3))
13072 (insert "[#" news "] "))))
13073 (org-preserve-lc (org-set-tags nil 'align)))
13074 (if remove
13075 (message "Priority removed")
13076 (message "Priority of current item set to %s" news)))))
13078 (defun org-show-priority ()
13079 "Show the priority of the current item.
13080 This priority is composed of the main priority given with the [#A] cookies,
13081 and by additional input from the age of a schedules or deadline entry."
13082 (interactive)
13083 (let ((pri (if (eq major-mode 'org-agenda-mode)
13084 (org-get-at-bol 'priority)
13085 (save-excursion
13086 (save-match-data
13087 (beginning-of-line)
13088 (and (looking-at org-heading-regexp)
13089 (org-get-priority (match-string 0))))))))
13090 (message "Priority is %d" (if pri pri -1000))))
13092 (defun org-get-priority (s)
13093 "Find priority cookie and return priority."
13094 (if (functionp org-get-priority-function)
13095 (funcall org-get-priority-function)
13096 (save-match-data
13097 (if (not (string-match org-priority-regexp s))
13098 (* 1000 (- org-lowest-priority org-default-priority))
13099 (* 1000 (- org-lowest-priority
13100 (string-to-char (match-string 2 s))))))))
13102 ;;;; Tags
13104 (defvar org-agenda-archives-mode)
13105 (defvar org-map-continue-from nil
13106 "Position from where mapping should continue.
13107 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13109 (defvar org-scanner-tags nil
13110 "The current tag list while the tags scanner is running.")
13111 (defvar org-trust-scanner-tags nil
13112 "Should `org-get-tags-at' use the tags for the scanner.
13113 This is for internal dynamical scoping only.
13114 When this is non-nil, the function `org-get-tags-at' will return the value
13115 of `org-scanner-tags' instead of building the list by itself. This
13116 can lead to large speed-ups when the tags scanner is used in a file with
13117 many entries, and when the list of tags is retrieved, for example to
13118 obtain a list of properties. Building the tags list for each entry in such
13119 a file becomes an N^2 operation - but with this variable set, it scales
13120 as N.")
13122 (defun org-scan-tags (action matcher todo-only &optional start-level)
13123 "Scan headline tags with inheritance and produce output ACTION.
13125 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13126 or `agenda' to produce an entry list for an agenda view. It can also be
13127 a Lisp form or a function that should be called at each matched headline, in
13128 this case the return value is a list of all return values from these calls.
13130 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13131 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13132 only lines with a not-done TODO keyword are included in the output.
13133 This should be the same variable that was scoped into
13134 and set by `org-make-tags-matcher' when it constructed MATCHER.
13136 START-LEVEL can be a string with asterisks, reducing the scope to
13137 headlines matching this string."
13138 (require 'org-agenda)
13139 (let* ((re (concat "^"
13140 (if start-level
13141 ;; Get the correct level to match
13142 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13143 org-outline-regexp)
13144 " *\\(\\<\\("
13145 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13146 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13147 (props (list 'face 'default
13148 'done-face 'org-agenda-done
13149 'undone-face 'default
13150 'mouse-face 'highlight
13151 'org-not-done-regexp org-not-done-regexp
13152 'org-todo-regexp org-todo-regexp
13153 'org-complex-heading-regexp org-complex-heading-regexp
13154 'help-echo
13155 (format "mouse-2 or RET jump to org file %s"
13156 (abbreviate-file-name
13157 (or (buffer-file-name (buffer-base-buffer))
13158 (buffer-name (buffer-base-buffer)))))))
13159 (case-fold-search nil)
13160 (org-map-continue-from nil)
13161 lspos tags tags-list
13162 (tags-alist (list (cons 0 org-file-tags)))
13163 (llast 0) rtn rtn1 level category i txt
13164 todo marker entry priority)
13165 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13166 (setq action (list 'lambda nil action)))
13167 (save-excursion
13168 (goto-char (point-min))
13169 (when (eq action 'sparse-tree)
13170 (org-overview)
13171 (org-remove-occur-highlights))
13172 (while (re-search-forward re nil t)
13173 (setq org-map-continue-from nil)
13174 (catch :skip
13175 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13176 tags (if (match-end 4) (org-match-string-no-properties 4)))
13177 (goto-char (setq lspos (match-beginning 0)))
13178 (setq level (org-reduced-level (funcall outline-level))
13179 category (org-get-category))
13180 (setq i llast llast level)
13181 ;; remove tag lists from same and sublevels
13182 (while (>= i level)
13183 (when (setq entry (assoc i tags-alist))
13184 (setq tags-alist (delete entry tags-alist)))
13185 (setq i (1- i)))
13186 ;; add the next tags
13187 (when tags
13188 (setq tags (org-split-string tags ":")
13189 tags-alist
13190 (cons (cons level tags) tags-alist)))
13191 ;; compile tags for current headline
13192 (setq tags-list
13193 (if org-use-tag-inheritance
13194 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13195 tags)
13196 org-scanner-tags tags-list)
13197 (when org-use-tag-inheritance
13198 (setcdr (car tags-alist)
13199 (mapcar (lambda (x)
13200 (setq x (copy-sequence x))
13201 (org-add-prop-inherited x))
13202 (cdar tags-alist))))
13203 (when (and tags org-use-tag-inheritance
13204 (or (not (eq t org-use-tag-inheritance))
13205 org-tags-exclude-from-inheritance))
13206 ;; selective inheritance, remove uninherited ones
13207 (setcdr (car tags-alist)
13208 (org-remove-uninherited-tags (cdar tags-alist))))
13209 (when (and
13211 ;; eval matcher only when the todo condition is OK
13212 (and (or (not todo-only) (member todo org-not-done-keywords))
13213 (let ((case-fold-search t) (org-trust-scanner-tags t))
13214 (eval matcher)))
13216 ;; Call the skipper, but return t if it does not skip,
13217 ;; so that the `and' form continues evaluating
13218 (progn
13219 (unless (eq action 'sparse-tree) (org-agenda-skip))
13222 ;; Check if timestamps are deselecting this entry
13223 (or (not todo-only)
13224 (and (member todo org-not-done-keywords)
13225 (or (not org-agenda-tags-todo-honor-ignore-options)
13226 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13228 ;; Extra check for the archive tag
13229 ;; FIXME: Does the skipper already do this????
13231 (not (member org-archive-tag tags-list))
13232 ;; we have an archive tag, should we use this anyway?
13233 (or (not org-agenda-skip-archived-trees)
13234 (and (eq action 'agenda) org-agenda-archives-mode))))
13236 ;; select this headline
13238 (cond
13239 ((eq action 'sparse-tree)
13240 (and org-highlight-sparse-tree-matches
13241 (org-get-heading) (match-end 0)
13242 (org-highlight-new-match
13243 (match-beginning 1) (match-end 1)))
13244 (org-show-context 'tags-tree))
13245 ((eq action 'agenda)
13246 (setq txt (org-agenda-format-item
13248 (concat
13249 (if (eq org-tags-match-list-sublevels 'indented)
13250 (make-string (1- level) ?.) "")
13251 (org-get-heading))
13252 category
13253 tags-list)
13254 priority (org-get-priority txt))
13255 (goto-char lspos)
13256 (setq marker (org-agenda-new-marker))
13257 (org-add-props txt props
13258 'org-marker marker 'org-hd-marker marker 'org-category category
13259 'todo-state todo
13260 'priority priority 'type "tagsmatch")
13261 (push txt rtn))
13262 ((functionp action)
13263 (setq org-map-continue-from nil)
13264 (save-excursion
13265 (setq rtn1 (funcall action))
13266 (push rtn1 rtn)))
13267 (t (error "Invalid action")))
13269 ;; if we are to skip sublevels, jump to end of subtree
13270 (unless org-tags-match-list-sublevels
13271 (org-end-of-subtree t)
13272 (backward-char 1))))
13273 ;; Get the correct position from where to continue
13274 (if org-map-continue-from
13275 (goto-char org-map-continue-from)
13276 (and (= (point) lspos) (end-of-line 1)))))
13277 (when (and (eq action 'sparse-tree)
13278 (not org-sparse-tree-open-archived-trees))
13279 (org-hide-archived-subtrees (point-min) (point-max)))
13280 (nreverse rtn)))
13282 (defun org-remove-uninherited-tags (tags)
13283 "Remove all tags that are not inherited from the list TAGS."
13284 (cond
13285 ((eq org-use-tag-inheritance t)
13286 (if org-tags-exclude-from-inheritance
13287 (org-delete-all org-tags-exclude-from-inheritance tags)
13288 tags))
13289 ((not org-use-tag-inheritance) nil)
13290 ((stringp org-use-tag-inheritance)
13291 (delq nil (mapcar
13292 (lambda (x)
13293 (if (and (string-match org-use-tag-inheritance x)
13294 (not (member x org-tags-exclude-from-inheritance)))
13295 x nil))
13296 tags)))
13297 ((listp org-use-tag-inheritance)
13298 (delq nil (mapcar
13299 (lambda (x)
13300 (if (member x org-use-tag-inheritance) x nil))
13301 tags)))))
13303 (defun org-match-sparse-tree (&optional todo-only match)
13304 "Create a sparse tree according to tags string MATCH.
13305 MATCH can contain positive and negative selection of tags, like
13306 \"+WORK+URGENT-WITHBOSS\".
13307 If optional argument TODO-ONLY is non-nil, only select lines that are
13308 also TODO lines."
13309 (interactive "P")
13310 (org-agenda-prepare-buffers (list (current-buffer)))
13311 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13313 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13315 (defvar org-cached-props nil)
13316 (defun org-cached-entry-get (pom property)
13317 (if (or (eq t org-use-property-inheritance)
13318 (and (stringp org-use-property-inheritance)
13319 (string-match org-use-property-inheritance property))
13320 (and (listp org-use-property-inheritance)
13321 (member property org-use-property-inheritance)))
13322 ;; Caching is not possible, check it directly
13323 (org-entry-get pom property 'inherit)
13324 ;; Get all properties, so that we can do complicated checks easily
13325 (cdr (assoc property (or org-cached-props
13326 (setq org-cached-props
13327 (org-entry-properties pom)))))))
13329 (defun org-global-tags-completion-table (&optional files)
13330 "Return the list of all tags in all agenda buffer/files.
13331 Optional FILES argument is a list of files which can be used
13332 instead of the agenda files."
13333 (save-excursion
13334 (org-uniquify
13335 (delq nil
13336 (apply 'append
13337 (mapcar
13338 (lambda (file)
13339 (set-buffer (find-file-noselect file))
13340 (append (org-get-buffer-tags)
13341 (mapcar (lambda (x) (if (stringp (car-safe x))
13342 (list (car-safe x)) nil))
13343 org-tag-alist)))
13344 (if (and files (car files))
13345 files
13346 (org-agenda-files))))))))
13348 (defun org-make-tags-matcher (match)
13349 "Create the TAGS/TODO matcher form for the selection string MATCH.
13351 The variable `todo-only' is scoped dynamically into this function.
13352 It will be set to t if the matcher restricts matching to TODO entries,
13353 otherwise will not be touched.
13355 Returns a cons of the selection string MATCH and the constructed
13356 lisp form implementing the matcher. The matcher is to be evaluated
13357 at an Org entry, with point on the headline, and returns t if the
13358 entry matches the selection string MATCH. The returned lisp form
13359 references two variables with information about the entry, which
13360 must be bound around the form's evaluation: todo, the TODO keyword
13361 at the entry (or nil of none); and tags-list, the list of all tags
13362 at the entry including inherited ones. Additionally, the category
13363 of the entry (if any) must be specified as the text property
13364 'org-category on the headline.
13366 See also `org-scan-tags'.
13368 (declare (special todo-only))
13369 (unless (boundp 'todo-only)
13370 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13371 (unless match
13372 ;; Get a new match request, with completion
13373 (let ((org-last-tags-completion-table
13374 (org-global-tags-completion-table)))
13375 (setq match (org-completing-read-no-i
13376 "Match: " 'org-tags-completion-function nil nil nil
13377 'org-tags-history))))
13379 ;; Parse the string and create a lisp form
13380 (let ((match0 match)
13381 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13382 minus tag mm
13383 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13384 orterms term orlist re-p str-p level-p level-op time-p
13385 prop-p pn pv po gv rest)
13386 (if (string-match "/+" match)
13387 ;; match contains also a todo-matching request
13388 (progn
13389 (setq tagsmatch (substring match 0 (match-beginning 0))
13390 todomatch (substring match (match-end 0)))
13391 (if (string-match "^!" todomatch)
13392 (setq todo-only t todomatch (substring todomatch 1)))
13393 (if (string-match "^\\s-*$" todomatch)
13394 (setq todomatch nil)))
13395 ;; only matching tags
13396 (setq tagsmatch match todomatch nil))
13398 ;; Make the tags matcher
13399 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13400 (setq tagsmatcher t)
13401 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13402 (while (setq term (pop orterms))
13403 (while (and (equal (substring term -1) "\\") orterms)
13404 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13405 (while (string-match re term)
13406 (setq rest (substring term (match-end 0))
13407 minus (and (match-end 1)
13408 (equal (match-string 1 term) "-"))
13409 tag (save-match-data (replace-regexp-in-string
13410 "\\\\-" "-"
13411 (match-string 2 term)))
13412 re-p (equal (string-to-char tag) ?{)
13413 level-p (match-end 4)
13414 prop-p (match-end 5)
13415 mm (cond
13416 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13417 (level-p
13418 (setq level-op (org-op-to-function (match-string 3 term)))
13419 `(,level-op level ,(string-to-number
13420 (match-string 4 term))))
13421 (prop-p
13422 (setq pn (match-string 5 term)
13423 po (match-string 6 term)
13424 pv (match-string 7 term)
13425 re-p (equal (string-to-char pv) ?{)
13426 str-p (equal (string-to-char pv) ?\")
13427 time-p (save-match-data
13428 (string-match "^\"[[<].*[]>]\"$" pv))
13429 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13430 (if time-p (setq pv (org-matcher-time pv)))
13431 (setq po (org-op-to-function po (if time-p 'time str-p)))
13432 (cond
13433 ((equal pn "CATEGORY")
13434 (setq gv '(get-text-property (point) 'org-category)))
13435 ((equal pn "TODO")
13436 (setq gv 'todo))
13438 (setq gv `(org-cached-entry-get nil ,pn))))
13439 (if re-p
13440 (if (eq po 'org<>)
13441 `(not (string-match ,pv (or ,gv "")))
13442 `(string-match ,pv (or ,gv "")))
13443 (if str-p
13444 `(,po (or ,gv "") ,pv)
13445 `(,po (string-to-number (or ,gv ""))
13446 ,(string-to-number pv) ))))
13447 (t `(member ,tag tags-list)))
13448 mm (if minus (list 'not mm) mm)
13449 term rest)
13450 (push mm tagsmatcher))
13451 (push (if (> (length tagsmatcher) 1)
13452 (cons 'and tagsmatcher)
13453 (car tagsmatcher))
13454 orlist)
13455 (setq tagsmatcher nil))
13456 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13457 (setq tagsmatcher
13458 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13459 ;; Make the todo matcher
13460 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13461 (setq todomatcher t)
13462 (setq orterms (org-split-string todomatch "|") orlist nil)
13463 (while (setq term (pop orterms))
13464 (while (string-match re term)
13465 (setq minus (and (match-end 1)
13466 (equal (match-string 1 term) "-"))
13467 kwd (match-string 2 term)
13468 re-p (equal (string-to-char kwd) ?{)
13469 term (substring term (match-end 0))
13470 mm (if re-p
13471 `(string-match ,(substring kwd 1 -1) todo)
13472 (list 'equal 'todo kwd))
13473 mm (if minus (list 'not mm) mm))
13474 (push mm todomatcher))
13475 (push (if (> (length todomatcher) 1)
13476 (cons 'and todomatcher)
13477 (car todomatcher))
13478 orlist)
13479 (setq todomatcher nil))
13480 (setq todomatcher (if (> (length orlist) 1)
13481 (cons 'or orlist) (car orlist))))
13483 ;; Return the string and lisp forms of the matcher
13484 (setq matcher (if todomatcher
13485 (list 'and tagsmatcher todomatcher)
13486 tagsmatcher))
13487 (when todo-only
13488 (setq matcher (list 'and '(member todo org-not-done-keywords)
13489 matcher)))
13490 (cons match0 matcher)))
13492 (defun org-op-to-function (op &optional stringp)
13493 "Turn an operator into the appropriate function."
13494 (setq op
13495 (cond
13496 ((equal op "<" ) '(< string< org-time<))
13497 ((equal op ">" ) '(> org-string> org-time>))
13498 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13499 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13500 ((member op '("=" "==")) '(= string= org-time=))
13501 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13502 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13504 (defun org<> (a b) (not (= a b)))
13505 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13506 (defun org-string>= (a b) (not (string< a b)))
13507 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13508 (defun org-string<> (a b) (not (string= a b)))
13509 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13510 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13511 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13512 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13513 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13514 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13515 (defun org-2ft (s)
13516 "Convert S to a floating point time.
13517 If S is already a number, just return it. If it is a string, parse
13518 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13519 (cond
13520 ((numberp s) s)
13521 ((stringp s)
13522 (condition-case nil
13523 (float-time (apply 'encode-time (org-parse-time-string s)))
13524 (error 0.)))
13525 (t 0.)))
13527 (defun org-time-today ()
13528 "Time in seconds today at 0:00.
13529 Returns the float number of seconds since the beginning of the
13530 epoch to the beginning of today (00:00)."
13531 (float-time (apply 'encode-time
13532 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13534 (defun org-matcher-time (s)
13535 "Interpret a time comparison value."
13536 (save-match-data
13537 (cond
13538 ((string= s "<now>") (float-time))
13539 ((string= s "<today>") (org-time-today))
13540 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13541 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13542 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13543 (+ (org-time-today)
13544 (* (string-to-number (match-string 1 s))
13545 (cdr (assoc (match-string 2 s)
13546 '(("d" . 86400.0) ("w" . 604800.0)
13547 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13548 (t (org-2ft s)))))
13550 (defun org-match-any-p (re list)
13551 "Does re match any element of list?"
13552 (setq list (mapcar (lambda (x) (string-match re x)) list))
13553 (delq nil list))
13555 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13556 (defvar org-tags-overlay (make-overlay 1 1))
13557 (org-detach-overlay org-tags-overlay)
13559 (defun org-get-local-tags-at (&optional pos)
13560 "Get a list of tags defined in the current headline."
13561 (org-get-tags-at pos 'local))
13563 (defun org-get-local-tags ()
13564 "Get a list of tags defined in the current headline."
13565 (org-get-tags-at nil 'local))
13567 (defun org-get-tags-at (&optional pos local)
13568 "Get a list of all headline tags applicable at POS.
13569 POS defaults to point. If tags are inherited, the list contains
13570 the targets in the same sequence as the headlines appear, i.e.
13571 the tags of the current headline come last.
13572 When LOCAL is non-nil, only return tags from the current headline,
13573 ignore inherited ones."
13574 (interactive)
13575 (if (and org-trust-scanner-tags
13576 (or (not pos) (equal pos (point)))
13577 (not local))
13578 org-scanner-tags
13579 (let (tags ltags lastpos parent)
13580 (save-excursion
13581 (save-restriction
13582 (widen)
13583 (goto-char (or pos (point)))
13584 (save-match-data
13585 (catch 'done
13586 (condition-case nil
13587 (progn
13588 (org-back-to-heading t)
13589 (while (not (equal lastpos (point)))
13590 (setq lastpos (point))
13591 (when (looking-at
13592 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13593 (setq ltags (org-split-string
13594 (org-match-string-no-properties 1) ":"))
13595 (when parent
13596 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13597 (setq tags (append
13598 (if parent
13599 (org-remove-uninherited-tags ltags)
13600 ltags)
13601 tags)))
13602 (or org-use-tag-inheritance (throw 'done t))
13603 (if local (throw 'done t))
13604 (or (org-up-heading-safe) (error nil))
13605 (setq parent t)))
13606 (error nil)))))
13607 (if local
13608 tags
13609 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13611 (defun org-add-prop-inherited (s)
13612 (add-text-properties 0 (length s) '(inherited t) s)
13615 (defun org-toggle-tag (tag &optional onoff)
13616 "Toggle the tag TAG for the current line.
13617 If ONOFF is `on' or `off', don't toggle but set to this state."
13618 (let (res current)
13619 (save-excursion
13620 (org-back-to-heading t)
13621 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13622 (point-at-eol) t)
13623 (progn
13624 (setq current (match-string 1))
13625 (replace-match ""))
13626 (setq current ""))
13627 (setq current (nreverse (org-split-string current ":")))
13628 (cond
13629 ((eq onoff 'on)
13630 (setq res t)
13631 (or (member tag current) (push tag current)))
13632 ((eq onoff 'off)
13633 (or (not (member tag current)) (setq current (delete tag current))))
13634 (t (if (member tag current)
13635 (setq current (delete tag current))
13636 (setq res t)
13637 (push tag current))))
13638 (end-of-line 1)
13639 (if current
13640 (progn
13641 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13642 (org-set-tags nil t))
13643 (delete-horizontal-space))
13644 (run-hooks 'org-after-tags-change-hook))
13645 res))
13647 (defun org-align-tags-here (to-col)
13648 ;; Assumes that this is a headline
13649 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13650 (beginning-of-line 1)
13651 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13652 (< pos (match-beginning 2)))
13653 (progn
13654 (setq tags-l (- (match-end 2) (match-beginning 2)))
13655 (goto-char (match-beginning 1))
13656 (insert " ")
13657 (delete-region (point) (1+ (match-beginning 2)))
13658 (setq ncol (max (current-column)
13659 (1+ col)
13660 (if (> to-col 0)
13661 to-col
13662 (- (abs to-col) tags-l))))
13663 (setq p (point))
13664 (insert (make-string (- ncol (current-column)) ?\ ))
13665 (setq ncol (current-column))
13666 (when indent-tabs-mode (tabify p (point-at-eol)))
13667 (org-move-to-column (min ncol col) t))
13668 (goto-char pos))))
13670 (defun org-set-tags-command (&optional arg just-align)
13671 "Call the set-tags command for the current entry."
13672 (interactive "P")
13673 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13674 (org-set-tags arg just-align)
13675 (save-excursion
13676 (org-back-to-heading t)
13677 (org-set-tags arg just-align))))
13679 (defun org-set-tags-to (data)
13680 "Set the tags of the current entry to DATA, replacing the current tags.
13681 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13682 If DATA is nil or the empty string, any tags will be removed."
13683 (interactive "sTags: ")
13684 (setq data
13685 (cond
13686 ((eq data nil) "")
13687 ((equal data "") "")
13688 ((stringp data)
13689 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13690 ":"))
13691 ((listp data)
13692 (concat ":" (mapconcat 'identity data ":") ":"))))
13693 (when data
13694 (save-excursion
13695 (org-back-to-heading t)
13696 (when (looking-at org-complex-heading-regexp)
13697 (if (match-end 5)
13698 (progn
13699 (goto-char (match-beginning 5))
13700 (insert data)
13701 (delete-region (point) (point-at-eol))
13702 (org-set-tags nil 'align))
13703 (goto-char (point-at-eol))
13704 (insert " " data)
13705 (org-set-tags nil 'align)))
13706 (beginning-of-line 1)
13707 (if (looking-at ".*?\\([ \t]+\\)$")
13708 (delete-region (match-beginning 1) (match-end 1))))))
13710 (defun org-align-all-tags ()
13711 "Align the tags i all headings."
13712 (interactive)
13713 (save-excursion
13714 (or (ignore-errors (org-back-to-heading t))
13715 (outline-next-heading))
13716 (if (org-at-heading-p)
13717 (org-set-tags t)
13718 (message "No headings"))))
13720 (defvar org-indent-indentation-per-level)
13721 (defun org-set-tags (&optional arg just-align)
13722 "Set the tags for the current headline.
13723 With prefix ARG, realign all tags in headings in the current buffer."
13724 (interactive "P")
13725 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13726 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13727 'region-start-level 'region))
13728 org-loop-over-headlines-in-active-region)
13729 (org-map-entries
13730 ;; We don't use ARG and JUST-ALIGN here these args are not
13731 ;; useful when looping over headlines
13732 `(org-set-tags)
13733 org-loop-over-headlines-in-active-region
13734 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13735 (let* ((re org-outline-regexp-bol)
13736 (current (unless arg (org-get-tags-string)))
13737 (col (current-column))
13738 (org-setting-tags t)
13739 table current-tags inherited-tags ; computed below when needed
13740 tags p0 c0 c1 rpl di tc level)
13741 (if arg
13742 (save-excursion
13743 (goto-char (point-min))
13744 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13745 (while (re-search-forward re nil t)
13746 (org-set-tags nil t)
13747 (end-of-line 1)))
13748 (message "All tags realigned to column %d" org-tags-column))
13749 (if just-align
13750 (setq tags current)
13751 ;; Get a new set of tags from the user
13752 (save-excursion
13753 (setq table (append org-tag-persistent-alist
13754 (or org-tag-alist (org-get-buffer-tags))
13755 (and
13756 org-complete-tags-always-offer-all-agenda-tags
13757 (org-global-tags-completion-table
13758 (org-agenda-files))))
13759 org-last-tags-completion-table table
13760 current-tags (org-split-string current ":")
13761 inherited-tags (nreverse
13762 (nthcdr (length current-tags)
13763 (nreverse (org-get-tags-at))))
13764 tags
13765 (if (or (eq t org-use-fast-tag-selection)
13766 (and org-use-fast-tag-selection
13767 (delq nil (mapcar 'cdr table))))
13768 (org-fast-tag-selection
13769 current-tags inherited-tags table
13770 (if org-fast-tag-selection-include-todo
13771 org-todo-key-alist))
13772 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13773 (org-trim
13774 (org-icompleting-read "Tags: "
13775 'org-tags-completion-function
13776 nil nil current 'org-tags-history))))))
13777 (while (string-match "[-+&]+" tags)
13778 ;; No boolean logic, just a list
13779 (setq tags (replace-match ":" t t tags))))
13781 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13783 (if org-tags-sort-function
13784 (setq tags (mapconcat 'identity
13785 (sort (org-split-string
13786 tags (org-re "[^[:alnum:]_@#%]+"))
13787 org-tags-sort-function) ":")))
13789 (if (string-match "\\`[\t ]*\\'" tags)
13790 (setq tags "")
13791 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13792 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13794 ;; Insert new tags at the correct column
13795 (beginning-of-line 1)
13796 (setq level (or (and (looking-at org-outline-regexp)
13797 (- (match-end 0) (point) 1))
13799 (cond
13800 ((and (equal current "") (equal tags "")))
13801 ((re-search-forward
13802 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13803 (point-at-eol) t)
13804 (if (equal tags "")
13805 (setq rpl "")
13806 (goto-char (match-beginning 0))
13807 (setq c0 (current-column)
13808 ;; compute offset for the case of org-indent-mode active
13809 di (if org-indent-mode
13810 (* (1- org-indent-indentation-per-level) (1- level))
13812 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13813 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13814 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13815 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13816 (replace-match rpl t t)
13817 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13818 tags)
13819 (t (error "Tags alignment failed")))
13820 (org-move-to-column col)
13821 (unless just-align
13822 (run-hooks 'org-after-tags-change-hook))))))
13824 (defun org-change-tag-in-region (beg end tag off)
13825 "Add or remove TAG for each entry in the region.
13826 This works in the agenda, and also in an org-mode buffer."
13827 (interactive
13828 (list (region-beginning) (region-end)
13829 (let ((org-last-tags-completion-table
13830 (if (derived-mode-p 'org-mode)
13831 (org-get-buffer-tags)
13832 (org-global-tags-completion-table))))
13833 (org-icompleting-read
13834 "Tag: " 'org-tags-completion-function nil nil nil
13835 'org-tags-history))
13836 (progn
13837 (message "[s]et or [r]emove? ")
13838 (equal (read-char-exclusive) ?r))))
13839 (if (fboundp 'deactivate-mark) (deactivate-mark))
13840 (let ((agendap (equal major-mode 'org-agenda-mode))
13841 l1 l2 m buf pos newhead (cnt 0))
13842 (goto-char end)
13843 (setq l2 (1- (org-current-line)))
13844 (goto-char beg)
13845 (setq l1 (org-current-line))
13846 (loop for l from l1 to l2 do
13847 (org-goto-line l)
13848 (setq m (get-text-property (point) 'org-hd-marker))
13849 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13850 (and agendap m))
13851 (setq buf (if agendap (marker-buffer m) (current-buffer))
13852 pos (if agendap m (point)))
13853 (with-current-buffer buf
13854 (save-excursion
13855 (save-restriction
13856 (goto-char pos)
13857 (setq cnt (1+ cnt))
13858 (org-toggle-tag tag (if off 'off 'on))
13859 (setq newhead (org-get-heading)))))
13860 (and agendap (org-agenda-change-all-lines newhead m))))
13861 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13863 (defun org-tags-completion-function (string predicate &optional flag)
13864 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13865 (confirm (lambda (x) (stringp (car x)))))
13866 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13867 (setq s1 (match-string 1 string)
13868 s2 (match-string 2 string))
13869 (setq s1 "" s2 string))
13870 (cond
13871 ((eq flag nil)
13872 ;; try completion
13873 (setq rtn (try-completion s2 ctable confirm))
13874 (if (stringp rtn)
13875 (setq rtn
13876 (concat s1 s2 (substring rtn (length s2))
13877 (if (and org-add-colon-after-tag-completion
13878 (assoc rtn ctable))
13879 ":" ""))))
13880 rtn)
13881 ((eq flag t)
13882 ;; all-completions
13883 (all-completions s2 ctable confirm)
13885 ((eq flag 'lambda)
13886 ;; exact match?
13887 (assoc s2 ctable)))
13890 (defun org-fast-tag-insert (kwd tags face &optional end)
13891 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13892 (insert (format "%-12s" (concat kwd ":"))
13893 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13894 (or end "")))
13896 (defun org-fast-tag-show-exit (flag)
13897 (save-excursion
13898 (org-goto-line 3)
13899 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13900 (replace-match ""))
13901 (when flag
13902 (end-of-line 1)
13903 (org-move-to-column (- (window-width) 19) t)
13904 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13906 (defun org-set-current-tags-overlay (current prefix)
13907 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13908 (if (featurep 'xemacs)
13909 (org-overlay-display org-tags-overlay (concat prefix s)
13910 'secondary-selection)
13911 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13912 (org-overlay-display org-tags-overlay (concat prefix s)))))
13914 (defvar org-last-tag-selection-key nil)
13915 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13916 "Fast tag selection with single keys.
13917 CURRENT is the current list of tags in the headline, INHERITED is the
13918 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13919 possibly with grouping information. TODO-TABLE is a similar table with
13920 TODO keywords, should these have keys assigned to them.
13921 If the keys are nil, a-z are automatically assigned.
13922 Returns the new tags string, or nil to not change the current settings."
13923 (let* ((fulltable (append table todo-table))
13924 (maxlen (apply 'max (mapcar
13925 (lambda (x)
13926 (if (stringp (car x)) (string-width (car x)) 0))
13927 fulltable)))
13928 (buf (current-buffer))
13929 (expert (eq org-fast-tag-selection-single-key 'expert))
13930 (buffer-tags nil)
13931 (fwidth (+ maxlen 3 1 3))
13932 (ncol (/ (- (window-width) 4) fwidth))
13933 (i-face 'org-done)
13934 (c-face 'org-todo)
13935 tg cnt e c char c1 c2 ntable tbl rtn
13936 ov-start ov-end ov-prefix
13937 (exit-after-next org-fast-tag-selection-single-key)
13938 (done-keywords org-done-keywords)
13939 groups ingroup)
13940 (save-excursion
13941 (beginning-of-line 1)
13942 (if (looking-at
13943 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13944 (setq ov-start (match-beginning 1)
13945 ov-end (match-end 1)
13946 ov-prefix "")
13947 (setq ov-start (1- (point-at-eol))
13948 ov-end (1+ ov-start))
13949 (skip-chars-forward "^\n\r")
13950 (setq ov-prefix
13951 (concat
13952 (buffer-substring (1- (point)) (point))
13953 (if (> (current-column) org-tags-column)
13955 (make-string (- org-tags-column (current-column)) ?\ ))))))
13956 (move-overlay org-tags-overlay ov-start ov-end)
13957 (save-window-excursion
13958 (if expert
13959 (set-buffer (get-buffer-create " *Org tags*"))
13960 (delete-other-windows)
13961 (split-window-vertically)
13962 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13963 (erase-buffer)
13964 (org-set-local 'org-done-keywords done-keywords)
13965 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13966 (org-fast-tag-insert "Current" current c-face "\n\n")
13967 (org-fast-tag-show-exit exit-after-next)
13968 (org-set-current-tags-overlay current ov-prefix)
13969 (setq tbl fulltable char ?a cnt 0)
13970 (while (setq e (pop tbl))
13971 (cond
13972 ((equal (car e) :startgroup)
13973 (push '() groups) (setq ingroup t)
13974 (when (not (= cnt 0))
13975 (setq cnt 0)
13976 (insert "\n"))
13977 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13978 ((equal (car e) :endgroup)
13979 (setq ingroup nil cnt 0)
13980 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13981 ((equal e '(:newline))
13982 (when (not (= cnt 0))
13983 (setq cnt 0)
13984 (insert "\n")
13985 (setq e (car tbl))
13986 (while (equal (car tbl) '(:newline))
13987 (insert "\n")
13988 (setq tbl (cdr tbl)))))
13990 (setq tg (copy-sequence (car e)) c2 nil)
13991 (if (cdr e)
13992 (setq c (cdr e))
13993 ;; automatically assign a character.
13994 (setq c1 (string-to-char
13995 (downcase (substring
13996 tg (if (= (string-to-char tg) ?@) 1 0)))))
13997 (if (or (rassoc c1 ntable) (rassoc c1 table))
13998 (while (or (rassoc char ntable) (rassoc char table))
13999 (setq char (1+ char)))
14000 (setq c2 c1))
14001 (setq c (or c2 char)))
14002 (if ingroup (push tg (car groups)))
14003 (setq tg (org-add-props tg nil 'face
14004 (cond
14005 ((not (assoc tg table))
14006 (org-get-todo-face tg))
14007 ((member tg current) c-face)
14008 ((member tg inherited) i-face))))
14009 (if (and (= cnt 0) (not ingroup)) (insert " "))
14010 (insert "[" c "] " tg (make-string
14011 (- fwidth 4 (length tg)) ?\ ))
14012 (push (cons tg c) ntable)
14013 (when (= (setq cnt (1+ cnt)) ncol)
14014 (insert "\n")
14015 (if ingroup (insert " "))
14016 (setq cnt 0)))))
14017 (setq ntable (nreverse ntable))
14018 (insert "\n")
14019 (goto-char (point-min))
14020 (if (not expert) (org-fit-window-to-buffer))
14021 (setq rtn
14022 (catch 'exit
14023 (while t
14024 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14025 (if (not groups) "no " "")
14026 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14027 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14028 (setq org-last-tag-selection-key c)
14029 (cond
14030 ((= c ?\r) (throw 'exit t))
14031 ((= c ?!)
14032 (setq groups (not groups))
14033 (goto-char (point-min))
14034 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14035 ((= c ?\C-c)
14036 (if (not expert)
14037 (org-fast-tag-show-exit
14038 (setq exit-after-next (not exit-after-next)))
14039 (setq expert nil)
14040 (delete-other-windows)
14041 (set-window-buffer (split-window-vertically) " *Org tags*")
14042 (org-switch-to-buffer-other-window " *Org tags*")
14043 (org-fit-window-to-buffer)))
14044 ((or (= c ?\C-g)
14045 (and (= c ?q) (not (rassoc c ntable))))
14046 (org-detach-overlay org-tags-overlay)
14047 (setq quit-flag t))
14048 ((= c ?\ )
14049 (setq current nil)
14050 (if exit-after-next (setq exit-after-next 'now)))
14051 ((= c ?\t)
14052 (condition-case nil
14053 (setq tg (org-icompleting-read
14054 "Tag: "
14055 (or buffer-tags
14056 (with-current-buffer buf
14057 (org-get-buffer-tags)))))
14058 (quit (setq tg "")))
14059 (when (string-match "\\S-" tg)
14060 (add-to-list 'buffer-tags (list tg))
14061 (if (member tg current)
14062 (setq current (delete tg current))
14063 (push tg current)))
14064 (if exit-after-next (setq exit-after-next 'now)))
14065 ((setq e (rassoc c todo-table) tg (car e))
14066 (with-current-buffer buf
14067 (save-excursion (org-todo tg)))
14068 (if exit-after-next (setq exit-after-next 'now)))
14069 ((setq e (rassoc c ntable) tg (car e))
14070 (if (member tg current)
14071 (setq current (delete tg current))
14072 (loop for g in groups do
14073 (if (member tg g)
14074 (mapc (lambda (x)
14075 (setq current (delete x current)))
14076 g)))
14077 (push tg current))
14078 (if exit-after-next (setq exit-after-next 'now))))
14080 ;; Create a sorted list
14081 (setq current
14082 (sort current
14083 (lambda (a b)
14084 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14085 (if (eq exit-after-next 'now) (throw 'exit t))
14086 (goto-char (point-min))
14087 (beginning-of-line 2)
14088 (delete-region (point) (point-at-eol))
14089 (org-fast-tag-insert "Current" current c-face)
14090 (org-set-current-tags-overlay current ov-prefix)
14091 (while (re-search-forward
14092 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14093 (setq tg (match-string 1))
14094 (add-text-properties
14095 (match-beginning 1) (match-end 1)
14096 (list 'face
14097 (cond
14098 ((member tg current) c-face)
14099 ((member tg inherited) i-face)
14100 (t (get-text-property (match-beginning 1) 'face))))))
14101 (goto-char (point-min)))))
14102 (org-detach-overlay org-tags-overlay)
14103 (if rtn
14104 (mapconcat 'identity current ":")
14105 nil))))
14107 (defun org-get-tags-string ()
14108 "Get the TAGS string in the current headline."
14109 (unless (org-at-heading-p t)
14110 (error "Not on a heading"))
14111 (save-excursion
14112 (beginning-of-line 1)
14113 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14114 (org-match-string-no-properties 1)
14115 "")))
14117 (defun org-get-tags ()
14118 "Get the list of tags specified in the current headline."
14119 (org-split-string (org-get-tags-string) ":"))
14121 (defun org-get-buffer-tags ()
14122 "Get a table of all tags used in the buffer, for completion."
14123 (let (tags)
14124 (save-excursion
14125 (goto-char (point-min))
14126 (while (re-search-forward
14127 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14128 (when (equal (char-after (point-at-bol 0)) ?*)
14129 (mapc (lambda (x) (add-to-list 'tags x))
14130 (org-split-string (org-match-string-no-properties 1) ":")))))
14131 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14132 (mapcar 'list tags)))
14134 ;;;; The mapping API
14136 ;;;###autoload
14137 (defun org-map-entries (func &optional match scope &rest skip)
14138 "Call FUNC at each headline selected by MATCH in SCOPE.
14140 FUNC is a function or a lisp form. The function will be called without
14141 arguments, with the cursor positioned at the beginning of the headline.
14142 The return values of all calls to the function will be collected and
14143 returned as a list.
14145 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14146 does not need to preserve point. After evaluation, the cursor will be
14147 moved to the end of the line (presumably of the headline of the
14148 processed entry) and search continues from there. Under some
14149 circumstances, this may not produce the wanted results. For example,
14150 if you have removed (e.g. archived) the current (sub)tree it could
14151 mean that the next entry will be skipped entirely. In such cases, you
14152 can specify the position from where search should continue by making
14153 FUNC set the variable `org-map-continue-from' to the desired buffer
14154 position.
14156 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14157 Only headlines that are matched by this query will be considered during
14158 the iteration. When MATCH is nil or t, all headlines will be
14159 visited by the iteration.
14161 SCOPE determines the scope of this command. It can be any of:
14163 nil The current buffer, respecting the restriction if any
14164 tree The subtree started with the entry at point
14165 region The entries within the active region, if any
14166 region-start-level
14167 The entries within the active region, but only those at
14168 the same level than the first one.
14169 file The current buffer, without restriction
14170 file-with-archives
14171 The current buffer, and any archives associated with it
14172 agenda All agenda files
14173 agenda-with-archives
14174 All agenda files with any archive files associated with them
14175 \(file1 file2 ...)
14176 If this is a list, all files in the list will be scanned
14178 The remaining args are treated as settings for the skipping facilities of
14179 the scanner. The following items can be given here:
14181 archive skip trees with the archive tag.
14182 comment skip trees with the COMMENT keyword
14183 function or Emacs Lisp form:
14184 will be used as value for `org-agenda-skip-function', so whenever
14185 the function returns t, FUNC will not be called for that
14186 entry and search will continue from the point where the
14187 function leaves it.
14189 If your function needs to retrieve the tags including inherited tags
14190 at the *current* entry, you can use the value of the variable
14191 `org-scanner-tags' which will be much faster than getting the value
14192 with `org-get-tags-at'. If your function gets properties with
14193 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14194 to t around the call to `org-entry-properties' to get the same speedup.
14195 Note that if your function moves around to retrieve tags and properties at
14196 a *different* entry, you cannot use these techniques."
14197 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14198 (not (org-region-active-p)))
14199 (let* ((org-agenda-archives-mode nil) ; just to make sure
14200 (org-agenda-skip-archived-trees (memq 'archive skip))
14201 (org-agenda-skip-comment-trees (memq 'comment skip))
14202 (org-agenda-skip-function
14203 (car (org-delete-all '(comment archive) skip)))
14204 (org-tags-match-list-sublevels t)
14205 (start-level (eq scope 'region-start-level))
14206 matcher file res
14207 org-todo-keywords-for-agenda
14208 org-done-keywords-for-agenda
14209 org-todo-keyword-alist-for-agenda
14210 org-drawers-for-agenda
14211 org-tag-alist-for-agenda
14212 todo-only)
14214 (cond
14215 ((eq match t) (setq matcher t))
14216 ((eq match nil) (setq matcher t))
14217 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14219 (save-excursion
14220 (save-restriction
14221 (cond ((eq scope 'tree)
14222 (org-back-to-heading t)
14223 (org-narrow-to-subtree)
14224 (setq scope nil))
14225 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14226 (org-region-active-p))
14227 ;; If needed, set start-level to a string like "2"
14228 (when start-level
14229 (save-excursion
14230 (goto-char (region-beginning))
14231 (unless (org-at-heading-p) (outline-next-heading))
14232 (setq start-level (org-current-level))))
14233 (narrow-to-region (region-beginning)
14234 (save-excursion
14235 (goto-char (region-end))
14236 (unless (and (bolp) (org-at-heading-p))
14237 (outline-next-heading))
14238 (point)))
14239 (setq scope nil)))
14241 (if (not scope)
14242 (progn
14243 (org-agenda-prepare-buffers
14244 (list (buffer-file-name (current-buffer))))
14245 (setq res (org-scan-tags func matcher todo-only start-level)))
14246 ;; Get the right scope
14247 (cond
14248 ((and scope (listp scope) (symbolp (car scope)))
14249 (setq scope (eval scope)))
14250 ((eq scope 'agenda)
14251 (setq scope (org-agenda-files t)))
14252 ((eq scope 'agenda-with-archives)
14253 (setq scope (org-agenda-files t))
14254 (setq scope (org-add-archive-files scope)))
14255 ((eq scope 'file)
14256 (setq scope (list (buffer-file-name))))
14257 ((eq scope 'file-with-archives)
14258 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14259 (org-agenda-prepare-buffers scope)
14260 (while (setq file (pop scope))
14261 (with-current-buffer (org-find-base-buffer-visiting file)
14262 (save-excursion
14263 (save-restriction
14264 (widen)
14265 (goto-char (point-min))
14266 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14267 res)))
14269 ;;;; Properties
14271 ;;; Setting and retrieving properties
14273 (defconst org-special-properties
14274 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14275 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14276 "The special properties valid in Org-mode.
14278 These are properties that are not defined in the property drawer,
14279 but in some other way.")
14281 (defconst org-default-properties
14282 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14283 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14284 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14285 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14286 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14287 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14288 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14289 "Some properties that are used by Org-mode for various purposes.
14290 Being in this list makes sure that they are offered for completion.")
14292 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14293 "Regular expression matching the first line of a property drawer.")
14295 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14296 "Regular expression matching the last line of a property drawer.")
14298 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14299 "Regular expression matching the first line of a property drawer.")
14301 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14302 "Regular expression matching the first line of a property drawer.")
14304 (defconst org-property-drawer-re
14305 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14306 org-property-end-re "\\)\n?")
14307 "Matches an entire property drawer.")
14309 (defconst org-clock-drawer-re
14310 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14311 org-property-end-re "\\)\n?")
14312 "Matches an entire clock drawer.")
14314 (defsubst org-re-property (property)
14315 "Return a regexp matching a PROPERTY line.
14316 Match group 1 will be set to the value."
14317 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14319 (defsubst org-re-property-keyword (property)
14320 "Return a regexp matching a PROPERTY line, possibly with no
14321 value for the property."
14322 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14324 (defun org-property-action ()
14325 "Do an action on properties."
14326 (interactive)
14327 (let (c)
14328 (org-at-property-p)
14329 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14330 (setq c (read-char-exclusive))
14331 (cond
14332 ((equal c ?s)
14333 (call-interactively 'org-set-property))
14334 ((equal c ?d)
14335 (call-interactively 'org-delete-property))
14336 ((equal c ?D)
14337 (call-interactively 'org-delete-property-globally))
14338 ((equal c ?c)
14339 (call-interactively 'org-compute-property-at-point))
14340 (t (error "No such property action %c" c)))))
14342 (defun org-inc-effort ()
14343 "Increment the value of the effort property in the current entry."
14344 (interactive)
14345 (org-set-effort nil t))
14347 (defun org-set-effort (&optional value increment)
14348 "Set the effort property of the current entry.
14349 With numerical prefix arg, use the nth allowed value, 0 stands for the
14350 10th allowed value.
14352 When INCREMENT is non-nil, set the property to the next allowed value."
14353 (interactive "P")
14354 (if (equal value 0) (setq value 10))
14355 (let* ((completion-ignore-case t)
14356 (prop org-effort-property)
14357 (cur (org-entry-get nil prop))
14358 (allowed (org-property-get-allowed-values nil prop 'table))
14359 (existing (mapcar 'list (org-property-values prop)))
14361 (val (cond
14362 ((stringp value) value)
14363 ((and allowed (integerp value))
14364 (or (car (nth (1- value) allowed))
14365 (car (org-last allowed))))
14366 ((and allowed increment)
14367 (or (caadr (member (list cur) allowed))
14368 (error "Allowed effort values are not set")))
14369 (allowed
14370 (message "Select 1-9,0, [RET%s]: %s"
14371 (if cur (concat "=" cur) "")
14372 (mapconcat 'car allowed " "))
14373 (setq rpl (read-char-exclusive))
14374 (if (equal rpl ?\r)
14376 (setq rpl (- rpl ?0))
14377 (if (equal rpl 0) (setq rpl 10))
14378 (if (and (> rpl 0) (<= rpl (length allowed)))
14379 (car (nth (1- rpl) allowed))
14380 (org-completing-read "Effort: " allowed nil))))
14382 (let (org-completion-use-ido org-completion-use-iswitchb)
14383 (org-completing-read
14384 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14385 (concat "[" cur "]") "")
14386 ": ")
14387 existing nil nil "" nil cur))))))
14388 (unless (equal (org-entry-get nil prop) val)
14389 (org-entry-put nil prop val))
14390 (message "%s is now %s" prop val)))
14392 (defun org-at-property-p ()
14393 "Is cursor inside a property drawer?"
14394 (save-excursion
14395 (beginning-of-line 1)
14396 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14397 (save-match-data ;; Used by calling procedures
14398 (let ((p (point))
14399 (range (unless (org-before-first-heading-p)
14400 (org-get-property-block))))
14401 (and range (<= (car range) p) (< p (cdr range))))))))
14403 (defun org-get-property-block (&optional beg end force)
14404 "Return the (beg . end) range of the body of the property drawer.
14405 BEG and END are the beginning and end of the current subtree, or of
14406 the part before the first headline. If they are not given, they will
14407 be found. If the drawer does not exist and FORCE is non-nil, create
14408 the drawer."
14409 (catch 'exit
14410 (save-excursion
14411 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14412 (progn (org-back-to-heading t) (point))))
14413 (end (or end (and (not (outline-next-heading)) (point-max))
14414 (point))))
14415 (goto-char beg)
14416 (if (re-search-forward org-property-start-re end t)
14417 (setq beg (1+ (match-end 0)))
14418 (if force
14419 (save-excursion
14420 (org-insert-property-drawer)
14421 (setq end (progn (outline-next-heading) (point))))
14422 (throw 'exit nil))
14423 (goto-char beg)
14424 (if (re-search-forward org-property-start-re end t)
14425 (setq beg (1+ (match-end 0)))))
14426 (if (re-search-forward org-property-end-re end t)
14427 (setq end (match-beginning 0))
14428 (or force (throw 'exit nil))
14429 (goto-char beg)
14430 (setq end beg)
14431 (org-indent-line)
14432 (insert ":END:\n"))
14433 (cons beg end)))))
14435 (defun org-entry-properties (&optional pom which specific)
14436 "Get all properties of the entry at point-or-marker POM.
14437 This includes the TODO keyword, the tags, time strings for deadline,
14438 scheduled, and clocking, and any additional properties defined in the
14439 entry. The return value is an alist, keys may occur multiple times
14440 if the property key was used several times.
14441 POM may also be nil, in which case the current entry is used.
14442 If WHICH is nil or `all', get all properties. If WHICH is
14443 `special' or `standard', only get that subclass. If WHICH
14444 is a string only get exactly this property. SPECIFIC can be a string, the
14445 specific property we are interested in. Specifying it can speed
14446 things up because then unnecessary parsing is avoided."
14447 (setq which (or which 'all))
14448 (org-with-point-at pom
14449 (let ((clockstr (substring org-clock-string 0 -1))
14450 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14451 (case-fold-search nil)
14452 beg end range props sum-props key key1 value string clocksum clocksumt)
14453 (save-excursion
14454 (when (condition-case nil
14455 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14456 (error nil))
14457 (setq beg (point))
14458 (setq sum-props (get-text-property (point) 'org-summaries))
14459 (setq clocksum (get-text-property (point) :org-clock-minutes)
14460 clocksumt (get-text-property (point) :org-clock-minutes-today))
14461 (outline-next-heading)
14462 (setq end (point))
14463 (when (memq which '(all special))
14464 ;; Get the special properties, like TODO and tags
14465 (goto-char beg)
14466 (when (and (or (not specific) (string= specific "TODO"))
14467 (looking-at org-todo-line-regexp) (match-end 2))
14468 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14469 (when (and (or (not specific) (string= specific "PRIORITY"))
14470 (looking-at org-priority-regexp))
14471 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14472 (when (or (not specific) (string= specific "FILE"))
14473 (push (cons "FILE" buffer-file-name) props))
14474 (when (and (or (not specific) (string= specific "TAGS"))
14475 (setq value (org-get-tags-string))
14476 (string-match "\\S-" value))
14477 (push (cons "TAGS" value) props))
14478 (when (and (or (not specific) (string= specific "ALLTAGS"))
14479 (setq value (org-get-tags-at)))
14480 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14481 ":"))
14482 props))
14483 (when (or (not specific) (string= specific "BLOCKED"))
14484 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14485 (when (or (not specific)
14486 (member specific
14487 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14488 "TIMESTAMP" "TIMESTAMP_IA")))
14489 (catch 'match
14490 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14491 (setq key (if (match-end 1)
14492 (substring (org-match-string-no-properties 1)
14493 0 -1))
14494 string (if (equal key clockstr)
14495 (org-trim
14496 (buffer-substring-no-properties
14497 (match-beginning 3) (goto-char
14498 (point-at-eol))))
14499 (substring (org-match-string-no-properties 3)
14500 1 -1)))
14501 ;; Get the correct property name from the key. This is
14502 ;; necessary if the user has configured time keywords.
14503 (setq key1 (concat key ":"))
14504 (cond
14505 ((not key)
14506 (setq key
14507 (if (= (char-after (match-beginning 3)) ?\[)
14508 "TIMESTAMP_IA" "TIMESTAMP")))
14509 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14510 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14511 ((equal key1 org-closed-string) (setq key "CLOSED"))
14512 ((equal key1 org-clock-string) (setq key "CLOCK")))
14513 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14514 (progn
14515 (push (cons key string) props)
14516 ;; no need to search further if match is found
14517 (throw 'match t))
14518 (when (or (equal key "CLOCK") (not (assoc key props)))
14519 (push (cons key string) props)))))))
14521 (when (memq which '(all standard))
14522 ;; Get the standard properties, like :PROP: ...
14523 (setq range (org-get-property-block beg end))
14524 (when range
14525 (goto-char (car range))
14526 (while (re-search-forward
14527 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14528 (cdr range) t)
14529 (setq key (org-match-string-no-properties 1)
14530 value (org-trim (or (org-match-string-no-properties 2) "")))
14531 (unless (member key excluded)
14532 (push (cons key (or value "")) props)))))
14533 (if clocksum
14534 (push (cons "CLOCKSUM"
14535 (org-columns-number-to-string (/ (float clocksum) 60.)
14536 'add_times))
14537 props))
14538 (if clocksumt
14539 (push (cons "CLOCKSUM_T"
14540 (org-columns-number-to-string (/ (float clocksumt) 60.)
14541 'add_times))
14542 props))
14543 (unless (assoc "CATEGORY" props)
14544 (push (cons "CATEGORY" (org-get-category)) props))
14545 (append sum-props (nreverse props)))))))
14547 (defun org-entry-get (pom property &optional inherit literal-nil)
14548 "Get value of PROPERTY for entry or content at point-or-marker POM.
14549 If INHERIT is non-nil and the entry does not have the property,
14550 then also check higher levels of the hierarchy.
14551 If INHERIT is the symbol `selective', use inheritance only if the setting
14552 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14553 If the property is present but empty, the return value is the empty string.
14554 If the property is not present at all, nil is returned.
14556 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14557 do not interpret it as the list atom nil. This is used for inheritance
14558 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14559 (org-with-point-at pom
14560 (if (and inherit (if (eq inherit 'selective)
14561 (org-property-inherit-p property)
14563 (org-entry-get-with-inheritance property literal-nil)
14564 (if (member property org-special-properties)
14565 ;; We need a special property. Use `org-entry-properties' to
14566 ;; retrieve it, but specify the wanted property
14567 (cdr (assoc property (org-entry-properties nil 'special property)))
14568 (let* ((range (org-get-property-block))
14569 (props (list (or (assoc property org-file-properties)
14570 (assoc property org-global-properties)
14571 (assoc property org-global-properties-fixed))))
14572 (ap (lambda (key)
14573 (when (re-search-forward
14574 (org-re-property key) (cdr range) t)
14575 (setq props
14576 (org-update-property-plist
14578 (if (match-end 1)
14579 (org-match-string-no-properties 1) "")
14580 props)))))
14581 val)
14582 (when (and range (goto-char (car range)))
14583 (funcall ap property)
14584 (goto-char (car range))
14585 (while (funcall ap (concat property "+")))
14586 (setq val (cdr (assoc property props)))
14587 (when val (if literal-nil val (org-not-nil val)))))))))
14589 (defun org-property-or-variable-value (var &optional inherit)
14590 "Check if there is a property fixing the value of VAR.
14591 If yes, return this value. If not, return the current value of the variable."
14592 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14593 (if (and prop (stringp prop) (string-match "\\S-" prop))
14594 (read prop)
14595 (symbol-value var))))
14597 (defun org-entry-delete (pom property)
14598 "Delete the property PROPERTY from entry at point-or-marker POM."
14599 (org-with-point-at pom
14600 (if (member property org-special-properties)
14601 nil ; cannot delete these properties.
14602 (let ((range (org-get-property-block)))
14603 (if (and range
14604 (goto-char (car range))
14605 (re-search-forward
14606 (org-re-property property)
14607 (cdr range) t))
14608 (progn
14609 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14611 nil)))))
14613 ;; Multi-values properties are properties that contain multiple values
14614 ;; These values are assumed to be single words, separated by whitespace.
14615 (defun org-entry-add-to-multivalued-property (pom property value)
14616 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14617 (let* ((old (org-entry-get pom property))
14618 (values (and old (org-split-string old "[ \t]"))))
14619 (setq value (org-entry-protect-space value))
14620 (unless (member value values)
14621 (setq values (cons value values))
14622 (org-entry-put pom property
14623 (mapconcat 'identity values " ")))))
14625 (defun org-entry-remove-from-multivalued-property (pom property value)
14626 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14627 (let* ((old (org-entry-get pom property))
14628 (values (and old (org-split-string old "[ \t]"))))
14629 (setq value (org-entry-protect-space value))
14630 (when (member value values)
14631 (setq values (delete value values))
14632 (org-entry-put pom property
14633 (mapconcat 'identity values " ")))))
14635 (defun org-entry-member-in-multivalued-property (pom property value)
14636 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14637 (let* ((old (org-entry-get pom property))
14638 (values (and old (org-split-string old "[ \t]"))))
14639 (setq value (org-entry-protect-space value))
14640 (member value values)))
14642 (defun org-entry-get-multivalued-property (pom property)
14643 "Return a list of values in a multivalued property."
14644 (let* ((value (org-entry-get pom property))
14645 (values (and value (org-split-string value "[ \t]"))))
14646 (mapcar 'org-entry-restore-space values)))
14648 (defun org-entry-put-multivalued-property (pom property &rest values)
14649 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14650 VALUES should be a list of strings. Spaces will be protected."
14651 (org-entry-put pom property
14652 (mapconcat 'org-entry-protect-space values " "))
14653 (let* ((value (org-entry-get pom property))
14654 (values (and value (org-split-string value "[ \t]"))))
14655 (mapcar 'org-entry-restore-space values)))
14657 (defun org-entry-protect-space (s)
14658 "Protect spaces and newline in string S."
14659 (while (string-match " " s)
14660 (setq s (replace-match "%20" t t s)))
14661 (while (string-match "\n" s)
14662 (setq s (replace-match "%0A" t t s)))
14665 (defun org-entry-restore-space (s)
14666 "Restore spaces and newline in string S."
14667 (while (string-match "%20" s)
14668 (setq s (replace-match " " t t s)))
14669 (while (string-match "%0A" s)
14670 (setq s (replace-match "\n" t t s)))
14673 (defvar org-entry-property-inherited-from (make-marker)
14674 "Marker pointing to the entry from where a property was inherited.
14675 Each call to `org-entry-get-with-inheritance' will set this marker to the
14676 location of the entry where the inheritance search matched. If there was
14677 no match, the marker will point nowhere.
14678 Note that also `org-entry-get' calls this function, if the INHERIT flag
14679 is set.")
14681 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14682 "Get PROPERTY of entry or content at point, search higher levels if needed.
14683 The search will stop at the first ancestor which has the property defined.
14684 If the value found is \"nil\", return nil to show that the property
14685 should be considered as undefined (this is the meaning of nil here).
14686 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14687 (move-marker org-entry-property-inherited-from nil)
14688 (let (tmp)
14689 (save-excursion
14690 (save-restriction
14691 (widen)
14692 (catch 'ex
14693 (while t
14694 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14695 (or (ignore-errors (org-back-to-heading t))
14696 (goto-char (point-min)))
14697 (move-marker org-entry-property-inherited-from (point))
14698 (throw 'ex tmp))
14699 (or (ignore-errors (org-up-heading-safe))
14700 (throw 'ex nil))))))
14701 (setq tmp (or tmp
14702 (cdr (assoc property org-file-properties))
14703 (cdr (assoc property org-global-properties))
14704 (cdr (assoc property org-global-properties-fixed))))
14705 (if literal-nil tmp (org-not-nil tmp))))
14707 (defvar org-property-changed-functions nil
14708 "Hook called when the value of a property has changed.
14709 Each hook function should accept two arguments, the name of the property
14710 and the new value.")
14712 (defun org-entry-put (pom property value)
14713 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14714 (org-with-point-at pom
14715 (org-back-to-heading t)
14716 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14717 range)
14718 (cond
14719 ((equal property "TODO")
14720 (when (and (stringp value) (string-match "\\S-" value)
14721 (not (member value org-todo-keywords-1)))
14722 (error "\"%s\" is not a valid TODO state" value))
14723 (if (or (not value)
14724 (not (string-match "\\S-" value)))
14725 (setq value 'none))
14726 (org-todo value)
14727 (org-set-tags nil 'align))
14728 ((equal property "PRIORITY")
14729 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14730 (string-to-char value) ?\ ))
14731 (org-set-tags nil 'align))
14732 ((equal property "SCHEDULED")
14733 (if (re-search-forward org-scheduled-time-regexp end t)
14734 (cond
14735 ((eq value 'earlier) (org-timestamp-change -1 'day))
14736 ((eq value 'later) (org-timestamp-change 1 'day))
14737 (t (call-interactively 'org-schedule)))
14738 (call-interactively 'org-schedule)))
14739 ((equal property "DEADLINE")
14740 (if (re-search-forward org-deadline-time-regexp end t)
14741 (cond
14742 ((eq value 'earlier) (org-timestamp-change -1 'day))
14743 ((eq value 'later) (org-timestamp-change 1 'day))
14744 (t (call-interactively 'org-deadline)))
14745 (call-interactively 'org-deadline)))
14746 ((member property org-special-properties)
14747 (error "The %s property can not yet be set with `org-entry-put'"
14748 property))
14749 (t ; a non-special property
14750 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14751 (setq range (org-get-property-block beg end 'force))
14752 (goto-char (car range))
14753 (if (re-search-forward
14754 (org-re-property-keyword property) (cdr range) t)
14755 (progn
14756 (delete-region (match-beginning 0) (match-end 0))
14757 (goto-char (match-beginning 0)))
14758 (goto-char (cdr range))
14759 (insert "\n")
14760 (backward-char 1)
14761 (org-indent-line))
14762 (insert ":" property ":")
14763 (and value (insert " " value))
14764 (org-indent-line)))))
14765 (run-hook-with-args 'org-property-changed-functions property value)))
14767 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14768 "Get all property keys in the current buffer.
14769 With INCLUDE-SPECIALS, also list the special properties that reflect things
14770 like tags and TODO state.
14771 With INCLUDE-DEFAULTS, also include properties that has special meaning
14772 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14773 and others.
14774 With INCLUDE-COLUMNS, also include property names given in COLUMN
14775 formats in the current buffer."
14776 (let (rtn range cfmt s p)
14777 (save-excursion
14778 (save-restriction
14779 (widen)
14780 (goto-char (point-min))
14781 (while (re-search-forward org-property-start-re nil t)
14782 (setq range (org-get-property-block))
14783 (goto-char (car range))
14784 (while (re-search-forward
14785 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14786 (cdr range) t)
14787 (add-to-list 'rtn (org-match-string-no-properties 1)))
14788 (outline-next-heading))))
14790 (when include-specials
14791 (setq rtn (append org-special-properties rtn)))
14793 (when include-defaults
14794 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14795 (add-to-list 'rtn org-effort-property))
14797 (when include-columns
14798 (save-excursion
14799 (save-restriction
14800 (widen)
14801 (goto-char (point-min))
14802 (while (re-search-forward
14803 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14804 nil t)
14805 (setq cfmt (match-string 2) s 0)
14806 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14807 cfmt s)
14808 (setq s (match-end 0)
14809 p (match-string 1 cfmt))
14810 (unless (or (equal p "ITEM")
14811 (member p org-special-properties))
14812 (add-to-list 'rtn (match-string 1 cfmt))))))))
14814 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14816 (defun org-property-values (key)
14817 "Return a list of all values of property KEY in the current buffer."
14818 (save-excursion
14819 (save-restriction
14820 (widen)
14821 (goto-char (point-min))
14822 (let ((re (org-re-property key))
14823 values)
14824 (while (re-search-forward re nil t)
14825 (add-to-list 'values (org-trim (match-string 1))))
14826 (delete "" values)))))
14828 (defun org-insert-property-drawer ()
14829 "Insert a property drawer into the current entry."
14830 (org-back-to-heading t)
14831 (looking-at org-outline-regexp)
14832 (let ((indent (if org-adapt-indentation
14833 (- (match-end 0) (match-beginning 0))
14835 (beg (point))
14836 (re (concat "^[ \t]*" org-keyword-time-regexp))
14837 end hiddenp)
14838 (outline-next-heading)
14839 (setq end (point))
14840 (goto-char beg)
14841 (while (re-search-forward re end t))
14842 (setq hiddenp (outline-invisible-p))
14843 (end-of-line 1)
14844 (and (equal (char-after) ?\n) (forward-char 1))
14845 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14846 (if (member (match-string 1) '("CLOCK:" ":END:"))
14847 ;; just skip this line
14848 (beginning-of-line 2)
14849 ;; Drawer start, find the end
14850 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14851 (beginning-of-line 1)))
14852 (org-skip-over-state-notes)
14853 (skip-chars-backward " \t\n\r")
14854 (if (eq (char-before) ?*) (forward-char 1))
14855 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14856 (beginning-of-line 0)
14857 (org-indent-to-column indent)
14858 (beginning-of-line 2)
14859 (org-indent-to-column indent)
14860 (beginning-of-line 0)
14861 (if hiddenp
14862 (save-excursion
14863 (org-back-to-heading t)
14864 (hide-entry))
14865 (org-flag-drawer t))))
14867 (defun org-insert-drawer (&optional arg drawer)
14868 "Insert a drawer at point.
14870 Optional argument DRAWER, when non-nil, is a string representing
14871 drawer's name. Otherwise, the user is prompted for a name.
14873 If a region is active, insert the drawer around that region
14874 instead.
14876 Point is left between drawer's boundaries."
14877 (interactive "P")
14878 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14879 "LOGBOOK"))
14880 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14881 ;; internally by Org. They are meant to be inserted
14882 ;; automatically.
14883 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14884 ;; Remove system drawers from list. Note: For some reason,
14885 ;; `org-completing-read' ignores the predicate while
14886 ;; `completing-read' handles it fine.
14887 (drawer (if arg "PROPERTIES"
14888 (or drawer
14889 (completing-read
14890 "Drawer: " org-drawers
14891 (lambda (d) (not (member d system-drawers))))))))
14892 (cond
14893 ;; With C-u, fall back on `org-insert-property-drawer'
14894 (arg (org-insert-property-drawer))
14895 ;; With an active region, insert a drawer at point.
14896 ((not (org-region-active-p))
14897 (progn
14898 (unless (bolp) (insert "\n"))
14899 (insert (format ":%s:\n\n:END:\n" drawer))
14900 (forward-line -2)))
14901 ;; Otherwise, insert the drawer at point
14903 (let ((rbeg (region-beginning))
14904 (rend (copy-marker (region-end))))
14905 (unwind-protect
14906 (progn
14907 (goto-char rbeg)
14908 (beginning-of-line)
14909 (when (save-excursion
14910 (re-search-forward org-outline-regexp-bol rend t))
14911 (error "Drawers cannot contain headlines"))
14912 ;; Position point at the beginning of the first
14913 ;; non-blank line in region. Insert drawer's opening
14914 ;; there, then indent it.
14915 (org-skip-whitespace)
14916 (beginning-of-line)
14917 (insert ":" drawer ":\n")
14918 (forward-line -1)
14919 (indent-for-tab-command)
14920 ;; Move point to the beginning of the first blank line
14921 ;; after the last non-blank line in region. Insert
14922 ;; drawer's closing, then indent it.
14923 (goto-char rend)
14924 (skip-chars-backward " \r\t\n")
14925 (insert "\n:END:")
14926 (deactivate-mark t)
14927 (indent-for-tab-command)
14928 (unless (eolp) (insert "\n")))
14929 ;; Clear marker, whatever the outcome of insertion is.
14930 (set-marker rend nil)))))))
14932 (defvar org-property-set-functions-alist nil
14933 "Property set function alist.
14934 Each entry should have the following format:
14936 (PROPERTY . READ-FUNCTION)
14938 The read function will be called with the same argument as
14939 `org-completing-read'.")
14941 (defun org-set-property-function (property)
14942 "Get the function that should be used to set PROPERTY.
14943 This is computed according to `org-property-set-functions-alist'."
14944 (or (cdr (assoc property org-property-set-functions-alist))
14945 'org-completing-read))
14947 (defun org-read-property-value (property)
14948 "Read PROPERTY value from user."
14949 (let* ((completion-ignore-case t)
14950 (allowed (org-property-get-allowed-values nil property 'table))
14951 (cur (org-entry-get nil property))
14952 (prompt (concat property " value"
14953 (if (and cur (string-match "\\S-" cur))
14954 (concat " [" cur "]") "") ": "))
14955 (set-function (org-set-property-function property))
14956 (val (if allowed
14957 (funcall set-function prompt allowed nil
14958 (not (get-text-property 0 'org-unrestricted
14959 (caar allowed))))
14960 (let (org-completion-use-ido org-completion-use-iswitchb)
14961 (funcall set-function prompt
14962 (mapcar 'list (org-property-values property))
14963 nil nil "" nil cur)))))
14964 (if (equal val "")
14966 val)))
14968 (defvar org-last-set-property nil)
14969 (defun org-read-property-name ()
14970 "Read a property name."
14971 (let* ((completion-ignore-case t)
14972 (keys (org-buffer-property-keys nil t t))
14973 (default-prop (or (save-excursion
14974 (save-match-data
14975 (beginning-of-line)
14976 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14977 (null (string= (match-string 1) "END"))
14978 (match-string 1))))
14979 org-last-set-property))
14980 (property (org-icompleting-read
14981 (concat "Property"
14982 (if default-prop (concat " [" default-prop "]") "")
14983 ": ")
14984 (mapcar 'list keys)
14985 nil nil nil nil
14986 default-prop
14988 (if (member property keys)
14989 property
14990 (or (cdr (assoc (downcase property)
14991 (mapcar (lambda (x) (cons (downcase x) x))
14992 keys)))
14993 property))))
14995 (defun org-set-property (property value)
14996 "In the current entry, set PROPERTY to VALUE.
14997 When called interactively, this will prompt for a property name, offering
14998 completion on existing and default properties. And then it will prompt
14999 for a value, offering completion either on allowed values (via an inherited
15000 xxx_ALL property) or on existing values in other instances of this property
15001 in the current file."
15002 (interactive (list nil nil))
15003 (let* ((property (or property (org-read-property-name)))
15004 (value (or value (org-read-property-value property)))
15005 (fn (cdr (assoc property org-properties-postprocess-alist))))
15006 (setq org-last-set-property property)
15007 ;; Possibly postprocess the inserted value:
15008 (when fn (setq value (funcall fn value)))
15009 (unless (equal (org-entry-get nil property) value)
15010 (org-entry-put nil property value))))
15012 (defun org-delete-property (property)
15013 "In the current entry, delete PROPERTY."
15014 (interactive
15015 (let* ((completion-ignore-case t)
15016 (prop (org-icompleting-read "Property: "
15017 (org-entry-properties nil 'standard))))
15018 (list prop)))
15019 (message "Property %s %s" property
15020 (if (org-entry-delete nil property)
15021 "deleted"
15022 "was not present in the entry")))
15024 (defun org-delete-property-globally (property)
15025 "Remove PROPERTY globally, from all entries."
15026 (interactive
15027 (let* ((completion-ignore-case t)
15028 (prop (org-icompleting-read
15029 "Globally remove property: "
15030 (mapcar 'list (org-buffer-property-keys)))))
15031 (list prop)))
15032 (save-excursion
15033 (save-restriction
15034 (widen)
15035 (goto-char (point-min))
15036 (let ((cnt 0))
15037 (while (re-search-forward
15038 (org-re-property property)
15039 nil t)
15040 (setq cnt (1+ cnt))
15041 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15042 (message "Property \"%s\" removed from %d entries" property cnt)))))
15044 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15046 (defun org-compute-property-at-point ()
15047 "Compute the property at point.
15048 This looks for an enclosing column format, extracts the operator and
15049 then applies it to the property in the column format's scope."
15050 (interactive)
15051 (unless (org-at-property-p)
15052 (error "Not at a property"))
15053 (let ((prop (org-match-string-no-properties 2)))
15054 (org-columns-get-format-and-top-level)
15055 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15056 (error "No operator defined for property %s" prop))
15057 (org-columns-compute prop)))
15059 (defvar org-property-allowed-value-functions nil
15060 "Hook for functions supplying allowed values for a specific property.
15061 The functions must take a single argument, the name of the property, and
15062 return a flat list of allowed values. If \":ETC\" is one of
15063 the values, this means that these values are intended as defaults for
15064 completion, but that other values should be allowed too.
15065 The functions must return nil if they are not responsible for this
15066 property.")
15068 (defun org-property-get-allowed-values (pom property &optional table)
15069 "Get allowed values for the property PROPERTY.
15070 When TABLE is non-nil, return an alist that can directly be used for
15071 completion."
15072 (let (vals)
15073 (cond
15074 ((equal property "TODO")
15075 (setq vals (org-with-point-at pom
15076 (append org-todo-keywords-1 '("")))))
15077 ((equal property "PRIORITY")
15078 (let ((n org-lowest-priority))
15079 (while (>= n org-highest-priority)
15080 (push (char-to-string n) vals)
15081 (setq n (1- n)))))
15082 ((member property org-special-properties))
15083 ((setq vals (run-hook-with-args-until-success
15084 'org-property-allowed-value-functions property)))
15086 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15087 (when (and vals (string-match "\\S-" vals))
15088 (setq vals (car (read-from-string (concat "(" vals ")"))))
15089 (setq vals (mapcar (lambda (x)
15090 (cond ((stringp x) x)
15091 ((numberp x) (number-to-string x))
15092 ((symbolp x) (symbol-name x))
15093 (t "???")))
15094 vals)))))
15095 (when (member ":ETC" vals)
15096 (setq vals (remove ":ETC" vals))
15097 (org-add-props (car vals) '(org-unrestricted t)))
15098 (if table (mapcar 'list vals) vals)))
15100 (defun org-property-previous-allowed-value (&optional previous)
15101 "Switch to the next allowed value for this property."
15102 (interactive)
15103 (org-property-next-allowed-value t))
15105 (defun org-property-next-allowed-value (&optional previous)
15106 "Switch to the next allowed value for this property."
15107 (interactive)
15108 (unless (org-at-property-p)
15109 (error "Not at a property"))
15110 (let* ((key (match-string 2))
15111 (value (match-string 3))
15112 (allowed (or (org-property-get-allowed-values (point) key)
15113 (and (member value '("[ ]" "[-]" "[X]"))
15114 '("[ ]" "[X]"))))
15115 nval)
15116 (unless allowed
15117 (error "Allowed values for this property have not been defined"))
15118 (if previous (setq allowed (reverse allowed)))
15119 (if (member value allowed)
15120 (setq nval (car (cdr (member value allowed)))))
15121 (setq nval (or nval (car allowed)))
15122 (if (equal nval value)
15123 (error "Only one allowed value for this property"))
15124 (org-at-property-p)
15125 (replace-match (concat " :" key ": " nval) t t)
15126 (org-indent-line)
15127 (beginning-of-line 1)
15128 (skip-chars-forward " \t")
15129 (run-hook-with-args 'org-property-changed-functions key nval)))
15131 (defun org-find-olp (path &optional this-buffer)
15132 "Return a marker pointing to the entry at outline path OLP.
15133 If anything goes wrong, throw an error.
15134 You can wrap this call to catch the error like this:
15136 (condition-case msg
15137 (org-mobile-locate-entry (match-string 4))
15138 (error (nth 1 msg)))
15140 The return value will then be either a string with the error message,
15141 or a marker if everything is OK.
15143 If THIS-BUFFER is set, the outline path does not contain a file,
15144 only headings."
15145 (let* ((file (if this-buffer buffer-file-name (pop path)))
15146 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15147 (level 1)
15148 (lmin 1)
15149 (lmax 1)
15150 limit re end found pos heading cnt flevel)
15151 (unless buffer (error "File not found :%s" file))
15152 (with-current-buffer buffer
15153 (save-excursion
15154 (save-restriction
15155 (widen)
15156 (setq limit (point-max))
15157 (goto-char (point-min))
15158 (while (setq heading (pop path))
15159 (setq re (format org-complex-heading-regexp-format
15160 (regexp-quote heading)))
15161 (setq cnt 0 pos (point))
15162 (while (re-search-forward re end t)
15163 (setq level (- (match-end 1) (match-beginning 1)))
15164 (if (and (>= level lmin) (<= level lmax))
15165 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15166 (when (= cnt 0) (error "Heading not found on level %d: %s"
15167 lmax heading))
15168 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15169 lmax heading))
15170 (goto-char found)
15171 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15172 (setq end (save-excursion (org-end-of-subtree t t))))
15173 (when (org-at-heading-p)
15174 (move-marker (make-marker) (point))))))))
15176 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15177 "Find node HEADING in BUFFER.
15178 Return a marker to the heading if it was found, or nil if not.
15179 If POS-ONLY is set, return just the position instead of a marker.
15181 The heading text must match exact, but it may have a TODO keyword,
15182 a priority cookie and tags in the standard locations."
15183 (with-current-buffer (or buffer (current-buffer))
15184 (save-excursion
15185 (save-restriction
15186 (widen)
15187 (goto-char (point-min))
15188 (let (case-fold-search)
15189 (if (re-search-forward
15190 (format org-complex-heading-regexp-format
15191 (regexp-quote heading)) nil t)
15192 (if pos-only
15193 (match-beginning 0)
15194 (move-marker (make-marker) (match-beginning 0)))))))))
15196 (defun org-find-exact-heading-in-directory (heading &optional dir)
15197 "Find Org node headline HEADING in all .org files in directory DIR.
15198 When the target headline is found, return a marker to this location."
15199 (let ((files (directory-files (or dir default-directory)
15200 nil "\\`[^.#].*\\.org\\'"))
15201 file visiting m buffer)
15202 (catch 'found
15203 (while (setq file (pop files))
15204 (message "trying %s" file)
15205 (setq visiting (org-find-base-buffer-visiting file))
15206 (setq buffer (or visiting (find-file-noselect file)))
15207 (setq m (org-find-exact-headline-in-buffer
15208 heading buffer))
15209 (when (and (not m) (not visiting)) (kill-buffer buffer))
15210 (and m (throw 'found m))))))
15212 (defun org-find-entry-with-id (ident)
15213 "Locate the entry that contains the ID property with exact value IDENT.
15214 IDENT can be a string, a symbol or a number, this function will search for
15215 the string representation of it.
15216 Return the position where this entry starts, or nil if there is no such entry."
15217 (interactive "sID: ")
15218 (let ((id (cond
15219 ((stringp ident) ident)
15220 ((symbol-name ident) (symbol-name ident))
15221 ((numberp ident) (number-to-string ident))
15222 (t (error "IDENT %s must be a string, symbol or number" ident))))
15223 (case-fold-search nil))
15224 (save-excursion
15225 (save-restriction
15226 (widen)
15227 (goto-char (point-min))
15228 (when (re-search-forward
15229 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15230 nil t)
15231 (org-back-to-heading t)
15232 (point))))))
15234 ;;;; Timestamps
15236 (defvar org-last-changed-timestamp nil)
15237 (defvar org-last-inserted-timestamp nil
15238 "The last time stamp inserted with `org-insert-time-stamp'.")
15239 (defvar org-time-was-given) ; dynamically scoped parameter
15240 (defvar org-end-time-was-given) ; dynamically scoped parameter
15241 (defvar org-ts-what) ; dynamically scoped parameter
15243 (defun org-time-stamp (arg &optional inactive)
15244 "Prompt for a date/time and insert a time stamp.
15245 If the user specifies a time like HH:MM or if this command is
15246 called with at least one prefix argument, the time stamp contains
15247 the date and the time. Otherwise, only the date is be included.
15249 All parts of a date not specified by the user is filled in from
15250 the current date/time. So if you just press return without
15251 typing anything, the time stamp will represent the current
15252 date/time.
15254 If there is already a timestamp at the cursor, it will be
15255 modified.
15257 With two universal prefix arguments, insert an active timestamp
15258 with the current time without prompting the user."
15259 (interactive "P")
15260 (let* ((ts nil)
15261 (default-time
15262 ;; Default time is either today, or, when entering a range,
15263 ;; the range start.
15264 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15265 (save-excursion
15266 (re-search-backward
15267 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15268 (- (point) 20) t)))
15269 (apply 'encode-time (org-parse-time-string (match-string 1)))
15270 (current-time)))
15271 (default-input (and ts (org-get-compact-tod ts)))
15272 (repeater (save-excursion
15273 (save-match-data
15274 (beginning-of-line)
15275 (when (re-search-forward
15276 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15277 (save-excursion (progn (end-of-line) (point))) t)
15278 (match-string 0)))))
15279 org-time-was-given org-end-time-was-given time)
15280 (cond
15281 ((and (org-at-timestamp-p t)
15282 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15283 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15284 (insert "--")
15285 (setq time (let ((this-command this-command))
15286 (org-read-date arg 'totime nil nil
15287 default-time default-input inactive)))
15288 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15289 ((org-at-timestamp-p t)
15290 (setq time (let ((this-command this-command))
15291 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15292 (when (org-at-timestamp-p t) ; just to get the match data
15293 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15294 (replace-match "")
15295 (setq org-last-changed-timestamp
15296 (org-insert-time-stamp
15297 time (or org-time-was-given arg)
15298 inactive nil nil (list org-end-time-was-given)))
15299 (when repeater (goto-char (1- (point))) (insert " " repeater)
15300 (setq org-last-changed-timestamp
15301 (concat (substring org-last-inserted-timestamp 0 -1)
15302 " " repeater ">"))))
15303 (message "Timestamp updated"))
15304 ((equal arg '(16))
15305 (org-insert-time-stamp (current-time) t))
15307 (setq time (let ((this-command this-command))
15308 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15309 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15310 nil nil (list org-end-time-was-given))))))
15312 ;; FIXME: can we use this for something else, like computing time differences?
15313 (defun org-get-compact-tod (s)
15314 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15315 (let* ((t1 (match-string 1 s))
15316 (h1 (string-to-number (match-string 2 s)))
15317 (m1 (string-to-number (match-string 3 s)))
15318 (t2 (and (match-end 4) (match-string 5 s)))
15319 (h2 (and t2 (string-to-number (match-string 6 s))))
15320 (m2 (and t2 (string-to-number (match-string 7 s))))
15321 dh dm)
15322 (if (not t2)
15324 (setq dh (- h2 h1) dm (- m2 m1))
15325 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15326 (concat t1 "+" (number-to-string dh)
15327 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15329 (defun org-time-stamp-inactive (&optional arg)
15330 "Insert an inactive time stamp.
15331 An inactive time stamp is enclosed in square brackets instead of angle
15332 brackets. It is inactive in the sense that it does not trigger agenda entries,
15333 does not link to the calendar and cannot be changed with the S-cursor keys.
15334 So these are more for recording a certain time/date."
15335 (interactive "P")
15336 (org-time-stamp arg 'inactive))
15338 (defvar org-date-ovl (make-overlay 1 1))
15339 (overlay-put org-date-ovl 'face 'org-date-selected)
15340 (org-detach-overlay org-date-ovl)
15342 (defvar org-ans1) ; dynamically scoped parameter
15343 (defvar org-ans2) ; dynamically scoped parameter
15345 (defvar org-plain-time-of-day-regexp) ; defined below
15347 (defvar org-overriding-default-time nil) ; dynamically scoped
15348 (defvar org-read-date-overlay nil)
15349 (defvar org-dcst nil) ; dynamically scoped
15350 (defvar org-read-date-history nil)
15351 (defvar org-read-date-final-answer nil)
15352 (defvar org-read-date-analyze-futurep nil)
15353 (defvar org-read-date-analyze-forced-year nil)
15354 (defvar org-read-date-inactive)
15356 (defun org-read-date (&optional org-with-time to-time from-string prompt
15357 default-time default-input inactive)
15358 "Read a date, possibly a time, and make things smooth for the user.
15359 The prompt will suggest to enter an ISO date, but you can also enter anything
15360 which will at least partially be understood by `parse-time-string'.
15361 Unrecognized parts of the date will default to the current day, month, year,
15362 hour and minute. If this command is called to replace a timestamp at point,
15363 or to enter the second timestamp of a range, the default time is taken
15364 from the existing stamp. Furthermore, the command prefers the future,
15365 so if you are giving a date where the year is not given, and the day-month
15366 combination is already past in the current year, it will assume you
15367 mean next year. For details, see the manual. A few examples:
15369 3-2-5 --> 2003-02-05
15370 feb 15 --> currentyear-02-15
15371 2/15 --> currentyear-02-15
15372 sep 12 9 --> 2009-09-12
15373 12:45 --> today 12:45
15374 22 sept 0:34 --> currentyear-09-22 0:34
15375 12 --> currentyear-currentmonth-12
15376 Fri --> nearest Friday (today or later)
15377 etc.
15379 Furthermore you can specify a relative date by giving, as the *first* thing
15380 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15381 change in days weeks, months, years.
15382 With a single plus or minus, the date is relative to today. With a double
15383 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15384 +4d --> four days from today
15385 +4 --> same as above
15386 +2w --> two weeks from today
15387 ++5 --> five days from default date
15389 The function understands only English month and weekday abbreviations.
15391 While prompting, a calendar is popped up - you can also select the
15392 date with the mouse (button 1). The calendar shows a period of three
15393 months. To scroll it to other months, use the keys `>' and `<'.
15394 If you don't like the calendar, turn it off with
15395 \(setq org-read-date-popup-calendar nil)
15397 With optional argument TO-TIME, the date will immediately be converted
15398 to an internal time.
15399 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15400 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15401 still enter a time, and this function will inform the calling routine
15402 about this change. The calling routine may then choose to change the
15403 format used to insert the time stamp into the buffer to include the time.
15404 With optional argument FROM-STRING, read from this string instead from
15405 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15406 the time/date that is used for everything that is not specified by the
15407 user."
15408 (require 'parse-time)
15409 (let* ((org-time-stamp-rounding-minutes
15410 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15411 (org-dcst org-display-custom-times)
15412 (ct (org-current-time))
15413 (org-def (or org-overriding-default-time default-time ct))
15414 (org-defdecode (decode-time org-def))
15415 (dummy (progn
15416 (when (< (nth 2 org-defdecode) org-extend-today-until)
15417 (setcar (nthcdr 2 org-defdecode) -1)
15418 (setcar (nthcdr 1 org-defdecode) 59)
15419 (setq org-def (apply 'encode-time org-defdecode)
15420 org-defdecode (decode-time org-def)))))
15421 (calendar-frame-setup nil)
15422 (calendar-setup nil)
15423 (calendar-move-hook nil)
15424 (calendar-view-diary-initially-flag nil)
15425 (calendar-view-holidays-initially-flag nil)
15426 (timestr (format-time-string
15427 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15428 (prompt (concat (if prompt (concat prompt " ") "")
15429 (format "Date+time [%s]: " timestr)))
15430 ans (org-ans0 "") org-ans1 org-ans2 final)
15432 (cond
15433 (from-string (setq ans from-string))
15434 (org-read-date-popup-calendar
15435 (save-excursion
15436 (save-window-excursion
15437 (calendar)
15438 (org-eval-in-calendar '(setq cursor-type nil) t)
15439 (unwind-protect
15440 (progn
15441 (calendar-forward-day (- (time-to-days org-def)
15442 (calendar-absolute-from-gregorian
15443 (calendar-current-date))))
15444 (org-eval-in-calendar nil t)
15445 (let* ((old-map (current-local-map))
15446 (map (copy-keymap calendar-mode-map))
15447 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15448 (org-defkey map (kbd "RET") 'org-calendar-select)
15449 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15450 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15451 (org-defkey minibuffer-local-map [(meta shift left)]
15452 (lambda () (interactive)
15453 (org-eval-in-calendar '(calendar-backward-month 1))))
15454 (org-defkey minibuffer-local-map [(meta shift right)]
15455 (lambda () (interactive)
15456 (org-eval-in-calendar '(calendar-forward-month 1))))
15457 (org-defkey minibuffer-local-map [(meta shift up)]
15458 (lambda () (interactive)
15459 (org-eval-in-calendar '(calendar-backward-year 1))))
15460 (org-defkey minibuffer-local-map [(meta shift down)]
15461 (lambda () (interactive)
15462 (org-eval-in-calendar '(calendar-forward-year 1))))
15463 (org-defkey minibuffer-local-map [?\e (shift left)]
15464 (lambda () (interactive)
15465 (org-eval-in-calendar '(calendar-backward-month 1))))
15466 (org-defkey minibuffer-local-map [?\e (shift right)]
15467 (lambda () (interactive)
15468 (org-eval-in-calendar '(calendar-forward-month 1))))
15469 (org-defkey minibuffer-local-map [?\e (shift up)]
15470 (lambda () (interactive)
15471 (org-eval-in-calendar '(calendar-backward-year 1))))
15472 (org-defkey minibuffer-local-map [?\e (shift down)]
15473 (lambda () (interactive)
15474 (org-eval-in-calendar '(calendar-forward-year 1))))
15475 (org-defkey minibuffer-local-map [(shift up)]
15476 (lambda () (interactive)
15477 (org-eval-in-calendar '(calendar-backward-week 1))))
15478 (org-defkey minibuffer-local-map [(shift down)]
15479 (lambda () (interactive)
15480 (org-eval-in-calendar '(calendar-forward-week 1))))
15481 (org-defkey minibuffer-local-map [(shift left)]
15482 (lambda () (interactive)
15483 (org-eval-in-calendar '(calendar-backward-day 1))))
15484 (org-defkey minibuffer-local-map [(shift right)]
15485 (lambda () (interactive)
15486 (org-eval-in-calendar '(calendar-forward-day 1))))
15487 (org-defkey minibuffer-local-map ">"
15488 (lambda () (interactive)
15489 (org-eval-in-calendar '(scroll-calendar-left 1))))
15490 (org-defkey minibuffer-local-map "<"
15491 (lambda () (interactive)
15492 (org-eval-in-calendar '(scroll-calendar-right 1))))
15493 (org-defkey minibuffer-local-map "\C-v"
15494 (lambda () (interactive)
15495 (org-eval-in-calendar
15496 '(calendar-scroll-left-three-months 1))))
15497 (org-defkey minibuffer-local-map "\M-v"
15498 (lambda () (interactive)
15499 (org-eval-in-calendar
15500 '(calendar-scroll-right-three-months 1))))
15501 (run-hooks 'org-read-date-minibuffer-setup-hook)
15502 (unwind-protect
15503 (progn
15504 (use-local-map map)
15505 (setq org-read-date-inactive inactive)
15506 (add-hook 'post-command-hook 'org-read-date-display)
15507 (setq org-ans0 (read-string prompt default-input
15508 'org-read-date-history nil))
15509 ;; org-ans0: from prompt
15510 ;; org-ans1: from mouse click
15511 ;; org-ans2: from calendar motion
15512 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15513 (remove-hook 'post-command-hook 'org-read-date-display)
15514 (use-local-map old-map)
15515 (when org-read-date-overlay
15516 (delete-overlay org-read-date-overlay)
15517 (setq org-read-date-overlay nil)))))
15518 (bury-buffer "*Calendar*")))))
15520 (t ; Naked prompt only
15521 (unwind-protect
15522 (setq ans (read-string prompt default-input
15523 'org-read-date-history timestr))
15524 (when org-read-date-overlay
15525 (delete-overlay org-read-date-overlay)
15526 (setq org-read-date-overlay nil)))))
15528 (setq final (org-read-date-analyze ans org-def org-defdecode))
15530 (when org-read-date-analyze-forced-year
15531 (message "Year was forced into %s"
15532 (if org-read-date-force-compatible-dates
15533 "compatible range (1970-2037)"
15534 "range representable on this machine"))
15535 (ding))
15537 ;; One round trip to get rid of 34th of August and stuff like that....
15538 (setq final (decode-time (apply 'encode-time final)))
15540 (setq org-read-date-final-answer ans)
15542 (if to-time
15543 (apply 'encode-time final)
15544 (if (and (boundp 'org-time-was-given) org-time-was-given)
15545 (format "%04d-%02d-%02d %02d:%02d"
15546 (nth 5 final) (nth 4 final) (nth 3 final)
15547 (nth 2 final) (nth 1 final))
15548 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15550 (defvar org-def)
15551 (defvar org-defdecode)
15552 (defvar org-with-time)
15553 (defun org-read-date-display ()
15554 "Display the current date prompt interpretation in the minibuffer."
15555 (when org-read-date-display-live
15556 (when org-read-date-overlay
15557 (delete-overlay org-read-date-overlay))
15558 (when (minibufferp (current-buffer))
15559 (save-excursion
15560 (end-of-line 1)
15561 (while (not (equal (buffer-substring
15562 (max (point-min) (- (point) 4)) (point))
15563 " "))
15564 (insert " ")))
15565 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15566 " " (or org-ans1 org-ans2)))
15567 (org-end-time-was-given nil)
15568 (f (org-read-date-analyze ans org-def org-defdecode))
15569 (fmts (if org-dcst
15570 org-time-stamp-custom-formats
15571 org-time-stamp-formats))
15572 (fmt (if (or org-with-time
15573 (and (boundp 'org-time-was-given) org-time-was-given))
15574 (cdr fmts)
15575 (car fmts)))
15576 (txt (format-time-string fmt (apply 'encode-time f)))
15577 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15578 (txt (concat "=> " txt)))
15579 (when (and org-end-time-was-given
15580 (string-match org-plain-time-of-day-regexp txt))
15581 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15582 org-end-time-was-given
15583 (substring txt (match-end 0)))))
15584 (when org-read-date-analyze-futurep
15585 (setq txt (concat txt " (=>F)")))
15586 (setq org-read-date-overlay
15587 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15588 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15590 (defun org-read-date-analyze (ans org-def org-defdecode)
15591 "Analyze the combined answer of the date prompt."
15592 ;; FIXME: cleanup and comment
15593 (let ((nowdecode (decode-time (current-time)))
15594 delta deltan deltaw deltadef year month day
15595 hour minute second wday pm h2 m2 tl wday1
15596 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15597 (setq org-read-date-analyze-futurep nil
15598 org-read-date-analyze-forced-year nil)
15599 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15600 (setq ans "+0"))
15602 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15603 (setq ans (replace-match "" t t ans)
15604 deltan (car delta)
15605 deltaw (nth 1 delta)
15606 deltadef (nth 2 delta)))
15608 ;; Check if there is an iso week date in there. If yes, store the
15609 ;; info and postpone interpreting it until the rest of the parsing
15610 ;; is done.
15611 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15612 (setq iso-year (if (match-end 1)
15613 (org-small-year-to-year
15614 (string-to-number (match-string 1 ans))))
15615 iso-weekday (if (match-end 3)
15616 (string-to-number (match-string 3 ans)))
15617 iso-week (string-to-number (match-string 2 ans)))
15618 (setq ans (replace-match "" t t ans)))
15620 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15621 (when (string-match
15622 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15623 (setq year (if (match-end 2)
15624 (string-to-number (match-string 2 ans))
15625 (progn (setq kill-year t)
15626 (string-to-number (format-time-string "%Y"))))
15627 month (string-to-number (match-string 3 ans))
15628 day (string-to-number (match-string 4 ans)))
15629 (if (< year 100) (setq year (+ 2000 year)))
15630 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15631 t nil ans)))
15633 ;; Help matching dotted european dates
15634 (when (string-match
15635 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15636 (setq year (if (match-end 3)
15637 (string-to-number (match-string 3 ans))
15638 (progn (setq kill-year t)
15639 (string-to-number (format-time-string "%Y"))))
15640 day (string-to-number (match-string 1 ans))
15641 month (string-to-number (match-string 2 ans))
15642 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15643 t nil ans)))
15645 ;; Help matching american dates, like 5/30 or 5/30/7
15646 (when (string-match
15647 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15648 (setq year (if (match-end 4)
15649 (string-to-number (match-string 4 ans))
15650 (progn (setq kill-year t)
15651 (string-to-number (format-time-string "%Y"))))
15652 month (string-to-number (match-string 1 ans))
15653 day (string-to-number (match-string 2 ans)))
15654 (if (< year 100) (setq year (+ 2000 year)))
15655 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15656 t nil ans)))
15657 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15658 ;; If there is a time with am/pm, and *no* time without it, we convert
15659 ;; so that matching will be successful.
15660 (loop for i from 1 to 2 do ; twice, for end time as well
15661 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15662 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15663 (setq hour (string-to-number (match-string 1 ans))
15664 minute (if (match-end 3)
15665 (string-to-number (match-string 3 ans))
15667 pm (equal ?p
15668 (string-to-char (downcase (match-string 4 ans)))))
15669 (if (and (= hour 12) (not pm))
15670 (setq hour 0)
15671 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15672 (setq ans (replace-match (format "%02d:%02d" hour minute)
15673 t t ans))))
15675 ;; Check if a time range is given as a duration
15676 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15677 (setq hour (string-to-number (match-string 1 ans))
15678 h2 (+ hour (string-to-number (match-string 3 ans)))
15679 minute (string-to-number (match-string 2 ans))
15680 m2 (+ minute (if (match-end 5) (string-to-number
15681 (match-string 5 ans))0)))
15682 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15683 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15684 t t ans)))
15686 ;; Check if there is a time range
15687 (when (boundp 'org-end-time-was-given)
15688 (setq org-time-was-given nil)
15689 (when (and (string-match org-plain-time-of-day-regexp ans)
15690 (match-end 8))
15691 (setq org-end-time-was-given (match-string 8 ans))
15692 (setq ans (concat (substring ans 0 (match-beginning 7))
15693 (substring ans (match-end 7))))))
15695 (setq tl (parse-time-string ans)
15696 day (or (nth 3 tl) (nth 3 org-defdecode))
15697 month (or (nth 4 tl)
15698 (if (and org-read-date-prefer-future
15699 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15700 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15701 (nth 4 org-defdecode)))
15702 year (or (and (not kill-year) (nth 5 tl))
15703 (if (and org-read-date-prefer-future
15704 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15705 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15706 (nth 5 org-defdecode)))
15707 hour (or (nth 2 tl) (nth 2 org-defdecode))
15708 minute (or (nth 1 tl) (nth 1 org-defdecode))
15709 second (or (nth 0 tl) 0)
15710 wday (nth 6 tl))
15712 (when (and (eq org-read-date-prefer-future 'time)
15713 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15714 (equal day (nth 3 nowdecode))
15715 (equal month (nth 4 nowdecode))
15716 (equal year (nth 5 nowdecode))
15717 (nth 2 tl)
15718 (or (< (nth 2 tl) (nth 2 nowdecode))
15719 (and (= (nth 2 tl) (nth 2 nowdecode))
15720 (nth 1 tl)
15721 (< (nth 1 tl) (nth 1 nowdecode)))))
15722 (setq day (1+ day)
15723 futurep t))
15725 ;; Special date definitions below
15726 (cond
15727 (iso-week
15728 ;; There was an iso week
15729 (require 'cal-iso)
15730 (setq futurep nil)
15731 (setq year (or iso-year year)
15732 day (or iso-weekday wday 1)
15733 wday nil ; to make sure that the trigger below does not match
15734 iso-date (calendar-gregorian-from-absolute
15735 (calendar-absolute-from-iso
15736 (list iso-week day year))))
15737 ; FIXME: Should we also push ISO weeks into the future?
15738 ; (when (and org-read-date-prefer-future
15739 ; (not iso-year)
15740 ; (< (calendar-absolute-from-gregorian iso-date)
15741 ; (time-to-days (current-time))))
15742 ; (setq year (1+ year)
15743 ; iso-date (calendar-gregorian-from-absolute
15744 ; (calendar-absolute-from-iso
15745 ; (list iso-week day year)))))
15746 (setq month (car iso-date)
15747 year (nth 2 iso-date)
15748 day (nth 1 iso-date)))
15749 (deltan
15750 (setq futurep nil)
15751 (unless deltadef
15752 (let ((now (decode-time (current-time))))
15753 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15754 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15755 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15756 ((equal deltaw "m") (setq month (+ month deltan)))
15757 ((equal deltaw "y") (setq year (+ year deltan)))))
15758 ((and wday (not (nth 3 tl)))
15759 ;; Weekday was given, but no day, so pick that day in the week
15760 ;; on or after the derived date.
15761 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15762 (unless (equal wday wday1)
15763 (setq day (+ day (% (- wday wday1 -7) 7))))))
15764 (if (and (boundp 'org-time-was-given)
15765 (nth 2 tl))
15766 (setq org-time-was-given t))
15767 (if (< year 100) (setq year (+ 2000 year)))
15768 ;; Check of the date is representable
15769 (if org-read-date-force-compatible-dates
15770 (progn
15771 (if (< year 1970)
15772 (setq year 1970 org-read-date-analyze-forced-year t))
15773 (if (> year 2037)
15774 (setq year 2037 org-read-date-analyze-forced-year t)))
15775 (condition-case nil
15776 (ignore (encode-time second minute hour day month year))
15777 (error
15778 (setq year (nth 5 org-defdecode))
15779 (setq org-read-date-analyze-forced-year t))))
15780 (setq org-read-date-analyze-futurep futurep)
15781 (list second minute hour day month year)))
15783 (defvar parse-time-weekdays)
15784 (defun org-read-date-get-relative (s today default)
15785 "Check string S for special relative date string.
15786 TODAY and DEFAULT are internal times, for today and for a default.
15787 Return shift list (N what def-flag)
15788 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15789 N is the number of WHATs to shift.
15790 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15791 the DEFAULT date rather than TODAY."
15792 (require 'parse-time)
15793 (when (and
15794 (string-match
15795 (concat
15796 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15797 "\\([0-9]+\\)?"
15798 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15799 "\\([ \t]\\|$\\)") s)
15800 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15801 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15802 (string-to-char (substring (match-string 1 s) -1))
15803 ?+))
15804 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15805 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15806 (what (if (match-end 3) (match-string 3 s) "d"))
15807 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15808 (date (if rel default today))
15809 (wday (nth 6 (decode-time date)))
15810 delta)
15811 (if wday1
15812 (progn
15813 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15814 (if (= dir ?-) (setq delta (- delta 7)))
15815 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15816 (list delta "d" rel))
15817 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15819 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15820 "Turn a user-specified date into the internal representation.
15821 The internal representation needed by the calendar is (month day year).
15822 This is a wrapper to handle the brain-dead convention in calendar that
15823 user function argument order change dependent on argument order."
15824 (if (boundp 'calendar-date-style)
15825 (cond
15826 ((eq calendar-date-style 'american)
15827 (list arg1 arg2 arg3))
15828 ((eq calendar-date-style 'european)
15829 (list arg2 arg1 arg3))
15830 ((eq calendar-date-style 'iso)
15831 (list arg2 arg3 arg1)))
15832 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15833 (if (org-bound-and-true-p european-calendar-style)
15834 (list arg2 arg1 arg3)
15835 (list arg1 arg2 arg3)))))
15837 (defun org-eval-in-calendar (form &optional keepdate)
15838 "Eval FORM in the calendar window and return to current window.
15839 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15840 otherwise stick to the current value of `org-ans2'."
15841 (let ((sf (selected-frame))
15842 (sw (selected-window)))
15843 (select-window (get-buffer-window "*Calendar*" t))
15844 (eval form)
15845 (when (and (not keepdate) (calendar-cursor-to-date))
15846 (let* ((date (calendar-cursor-to-date))
15847 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15848 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15849 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15850 (select-window sw)
15851 (org-select-frame-set-input-focus sf)))
15853 (defun org-calendar-select ()
15854 "Return to `org-read-date' with the date currently selected.
15855 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15856 (interactive)
15857 (when (calendar-cursor-to-date)
15858 (let* ((date (calendar-cursor-to-date))
15859 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15860 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15861 (if (active-minibuffer-window) (exit-minibuffer))))
15863 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15864 "Insert a date stamp for the date given by the internal TIME.
15865 WITH-HM means use the stamp format that includes the time of the day.
15866 INACTIVE means use square brackets instead of angular ones, so that the
15867 stamp will not contribute to the agenda.
15868 PRE and POST are optional strings to be inserted before and after the
15869 stamp.
15870 The command returns the inserted time stamp."
15871 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15872 stamp)
15873 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15874 (insert-before-markers (or pre ""))
15875 (when (listp extra)
15876 (setq extra (car extra))
15877 (if (and (stringp extra)
15878 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15879 (setq extra (format "-%02d:%02d"
15880 (string-to-number (match-string 1 extra))
15881 (string-to-number (match-string 2 extra))))
15882 (setq extra nil)))
15883 (when extra
15884 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15885 (insert-before-markers (setq stamp (format-time-string fmt time)))
15886 (insert-before-markers (or post ""))
15887 (setq org-last-inserted-timestamp stamp)))
15889 (defun org-toggle-time-stamp-overlays ()
15890 "Toggle the use of custom time stamp formats."
15891 (interactive)
15892 (setq org-display-custom-times (not org-display-custom-times))
15893 (unless org-display-custom-times
15894 (let ((p (point-min)) (bmp (buffer-modified-p)))
15895 (while (setq p (next-single-property-change p 'display))
15896 (if (and (get-text-property p 'display)
15897 (eq (get-text-property p 'face) 'org-date))
15898 (remove-text-properties
15899 p (setq p (next-single-property-change p 'display))
15900 '(display t))))
15901 (set-buffer-modified-p bmp)))
15902 (if (featurep 'xemacs)
15903 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15904 (org-restart-font-lock)
15905 (setq org-table-may-need-update t)
15906 (if org-display-custom-times
15907 (message "Time stamps are overlaid with custom format")
15908 (message "Time stamp overlays removed")))
15910 (defun org-display-custom-time (beg end)
15911 "Overlay modified time stamp format over timestamp between BEG and END."
15912 (let* ((ts (buffer-substring beg end))
15913 t1 w1 with-hm tf time str w2 (off 0))
15914 (save-match-data
15915 (setq t1 (org-parse-time-string ts t))
15916 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15917 (setq off (- (match-end 0) (match-beginning 0)))))
15918 (setq end (- end off))
15919 (setq w1 (- end beg)
15920 with-hm (and (nth 1 t1) (nth 2 t1))
15921 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15922 time (org-fix-decoded-time t1)
15923 str (org-add-props
15924 (format-time-string
15925 (substring tf 1 -1) (apply 'encode-time time))
15926 nil 'mouse-face 'highlight)
15927 w2 (length str))
15928 (if (not (= w2 w1))
15929 (add-text-properties (1+ beg) (+ 2 beg)
15930 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15931 (if (featurep 'xemacs)
15932 (progn
15933 (put-text-property beg end 'invisible t)
15934 (put-text-property beg end 'end-glyph (make-glyph str)))
15935 (put-text-property beg end 'display str))))
15937 (defun org-translate-time (string)
15938 "Translate all timestamps in STRING to custom format.
15939 But do this only if the variable `org-display-custom-times' is set."
15940 (when org-display-custom-times
15941 (save-match-data
15942 (let* ((start 0)
15943 (re org-ts-regexp-both)
15944 t1 with-hm inactive tf time str beg end)
15945 (while (setq start (string-match re string start))
15946 (setq beg (match-beginning 0)
15947 end (match-end 0)
15948 t1 (save-match-data
15949 (org-parse-time-string (substring string beg end) t))
15950 with-hm (and (nth 1 t1) (nth 2 t1))
15951 inactive (equal (substring string beg (1+ beg)) "[")
15952 tf (funcall (if with-hm 'cdr 'car)
15953 org-time-stamp-custom-formats)
15954 time (org-fix-decoded-time t1)
15955 str (format-time-string
15956 (concat
15957 (if inactive "[" "<") (substring tf 1 -1)
15958 (if inactive "]" ">"))
15959 (apply 'encode-time time))
15960 string (replace-match str t t string)
15961 start (+ start (length str)))))))
15962 string)
15964 (defun org-fix-decoded-time (time)
15965 "Set 0 instead of nil for the first 6 elements of time.
15966 Don't touch the rest."
15967 (let ((n 0))
15968 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15970 (defun org-days-to-time (timestamp-string)
15971 "Difference between TIMESTAMP-STRING and now in days."
15972 (- (time-to-days (org-time-string-to-time timestamp-string))
15973 (time-to-days (current-time))))
15975 (defun org-deadline-close (timestamp-string &optional ndays)
15976 "Is the time in TIMESTAMP-STRING close to the current date?"
15977 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15978 (and (< (org-days-to-time timestamp-string) ndays)
15979 (not (org-entry-is-done-p))))
15981 (defun org-get-wdays (ts)
15982 "Get the deadline lead time appropriate for timestring TS."
15983 (cond
15984 ((<= org-deadline-warning-days 0)
15985 ;; 0 or negative, enforce this value no matter what
15986 (- org-deadline-warning-days))
15987 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15988 ;; lead time is specified.
15989 (floor (* (string-to-number (match-string 1 ts))
15990 (cdr (assoc (match-string 2 ts)
15991 '(("d" . 1) ("w" . 7)
15992 ("m" . 30.4) ("y" . 365.25)))))))
15993 ;; go for the default.
15994 (t org-deadline-warning-days)))
15996 (defun org-calendar-select-mouse (ev)
15997 "Return to `org-read-date' with the date currently selected.
15998 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15999 (interactive "e")
16000 (mouse-set-point ev)
16001 (when (calendar-cursor-to-date)
16002 (let* ((date (calendar-cursor-to-date))
16003 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16004 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16005 (if (active-minibuffer-window) (exit-minibuffer))))
16007 (defun org-check-deadlines (ndays)
16008 "Check if there are any deadlines due or past due.
16009 A deadline is considered due if it happens within `org-deadline-warning-days'
16010 days from today's date. If the deadline appears in an entry marked DONE,
16011 it is not shown. The prefix arg NDAYS can be used to test that many
16012 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16013 (interactive "P")
16014 (let* ((org-warn-days
16015 (cond
16016 ((equal ndays '(4)) 100000)
16017 (ndays (prefix-numeric-value ndays))
16018 (t (abs org-deadline-warning-days))))
16019 (case-fold-search nil)
16020 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16021 (callback
16022 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16024 (message "%d deadlines past-due or due within %d days"
16025 (org-occur regexp nil callback)
16026 org-warn-days)))
16028 (defsubst org-re-timestamp (type)
16029 "Return a regexp for timestamp TYPE.
16030 Allowed values for TYPE are:
16032 all: all timestamps
16033 active: only active timestamps (<...>)
16034 inactive: only inactive timestamps ([...])
16035 scheduled: only scheduled timestamps
16036 deadline: only deadline timestamps
16038 When TYPE is nil, fall back on returning a regexp that matches
16039 both scheduled and deadline timestamps."
16040 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16041 ((eq type 'active) org-ts-regexp)
16042 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16043 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16044 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16045 ((eq type 'scheduled-or-deadline)
16046 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16048 (defun org-check-before-date (date)
16049 "Check if there are deadlines or scheduled entries before DATE."
16050 (interactive (list (org-read-date)))
16051 (let ((case-fold-search nil)
16052 (regexp (org-re-timestamp org-ts-type))
16053 (callback
16054 (lambda () (time-less-p
16055 (org-time-string-to-time (match-string 1))
16056 (org-time-string-to-time date)))))
16057 (message "%d entries before %s"
16058 (org-occur regexp nil callback) date)))
16060 (defun org-check-after-date (date)
16061 "Check if there are deadlines or scheduled entries after DATE."
16062 (interactive (list (org-read-date)))
16063 (let ((case-fold-search nil)
16064 (regexp (org-re-timestamp org-ts-type))
16065 (callback
16066 (lambda () (not
16067 (time-less-p
16068 (org-time-string-to-time (match-string 1))
16069 (org-time-string-to-time date))))))
16070 (message "%d entries after %s"
16071 (org-occur regexp nil callback) date)))
16073 (defun org-check-dates-range (start-date end-date)
16074 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16075 (interactive (list (org-read-date nil nil nil "Range starts")
16076 (org-read-date nil nil nil "Range end")))
16077 (let ((case-fold-search nil)
16078 (regexp (org-re-timestamp org-ts-type))
16079 (callback
16080 (lambda ()
16081 (let ((match (match-string 1)))
16082 (and
16083 (not (time-less-p
16084 (org-time-string-to-time match)
16085 (org-time-string-to-time start-date)))
16086 (time-less-p
16087 (org-time-string-to-time match)
16088 (org-time-string-to-time end-date)))))))
16089 (message "%d entries between %s and %s"
16090 (org-occur regexp nil callback) start-date end-date)))
16092 (defun org-evaluate-time-range (&optional to-buffer)
16093 "Evaluate a time range by computing the difference between start and end.
16094 Normally the result is just printed in the echo area, but with prefix arg
16095 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16096 If the time range is actually in a table, the result is inserted into the
16097 next column.
16098 For time difference computation, a year is assumed to be exactly 365
16099 days in order to avoid rounding problems."
16100 (interactive "P")
16102 (org-clock-update-time-maybe)
16103 (save-excursion
16104 (unless (org-at-date-range-p t)
16105 (goto-char (point-at-bol))
16106 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16107 (if (not (org-at-date-range-p t))
16108 (error "Not at a time-stamp range, and none found in current line")))
16109 (let* ((ts1 (match-string 1))
16110 (ts2 (match-string 2))
16111 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16112 (match-end (match-end 0))
16113 (time1 (org-time-string-to-time ts1))
16114 (time2 (org-time-string-to-time ts2))
16115 (t1 (org-float-time time1))
16116 (t2 (org-float-time time2))
16117 (diff (abs (- t2 t1)))
16118 (negative (< (- t2 t1) 0))
16119 ;; (ys (floor (* 365 24 60 60)))
16120 (ds (* 24 60 60))
16121 (hs (* 60 60))
16122 (fy "%dy %dd %02d:%02d")
16123 (fy1 "%dy %dd")
16124 (fd "%dd %02d:%02d")
16125 (fd1 "%dd")
16126 (fh "%02d:%02d")
16127 y d h m align)
16128 (if havetime
16129 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16131 d (floor (/ diff ds)) diff (mod diff ds)
16132 h (floor (/ diff hs)) diff (mod diff hs)
16133 m (floor (/ diff 60)))
16134 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16136 d (floor (+ (/ diff ds) 0.5))
16137 h 0 m 0))
16138 (if (not to-buffer)
16139 (message "%s" (org-make-tdiff-string y d h m))
16140 (if (org-at-table-p)
16141 (progn
16142 (goto-char match-end)
16143 (setq align t)
16144 (and (looking-at " *|") (goto-char (match-end 0))))
16145 (goto-char match-end))
16146 (if (looking-at
16147 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16148 (replace-match ""))
16149 (if negative (insert " -"))
16150 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16151 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16152 (insert " " (format fh h m))))
16153 (if align (org-table-align))
16154 (message "Time difference inserted")))))
16156 (defun org-make-tdiff-string (y d h m)
16157 (let ((fmt "")
16158 (l nil))
16159 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16160 l (push y l)))
16161 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16162 l (push d l)))
16163 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16164 l (push h l)))
16165 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16166 l (push m l)))
16167 (apply 'format fmt (nreverse l))))
16169 (defun org-time-string-to-time (s &optional buffer pos)
16170 "Convert a timestamp string into internal time."
16171 (condition-case errdata
16172 (apply 'encode-time (org-parse-time-string s))
16173 (error (error "Bad timestamp `%s'%s\nError was: %s"
16174 s (if (not (and buffer pos))
16176 (format " at %d in buffer `%s'" pos buffer))
16177 (cdr errdata)))))
16179 (defun org-time-string-to-seconds (s)
16180 "Convert a timestamp string to a number of seconds."
16181 (org-float-time (org-time-string-to-time s)))
16183 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16184 "Convert a time stamp to an absolute day number.
16185 If there is a specifier for a cyclic time stamp, get the closest date to
16186 DAYNR.
16187 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16188 The variable date is bound by the calendar when this is called."
16189 (cond
16190 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16191 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16192 daynr
16193 (+ daynr 1000)))
16194 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16195 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16196 (time-to-days (current-time))) (match-string 0 s)
16197 prefer show-all))
16198 (t (time-to-days
16199 (condition-case errdata
16200 (apply 'encode-time (org-parse-time-string s))
16201 (error (error "Bad timestamp `%s'%s\nError was: %s"
16202 s (if (not (and buffer pos))
16204 (format " at %d in buffer `%s'" pos buffer))
16205 (cdr errdata))))))))
16207 (defun org-days-to-iso-week (days)
16208 "Return the iso week number."
16209 (require 'cal-iso)
16210 (car (calendar-iso-from-absolute days)))
16212 (defun org-small-year-to-year (year)
16213 "Convert 2-digit years into 4-digit years.
16214 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16215 The year 2000 cannot be abbreviated. Any year larger than 99
16216 is returned unchanged."
16217 (if (< year 38)
16218 (setq year (+ 2000 year))
16219 (if (< year 100)
16220 (setq year (+ 1900 year))))
16221 year)
16223 (defun org-time-from-absolute (d)
16224 "Return the time corresponding to date D.
16225 D may be an absolute day number, or a calendar-type list (month day year)."
16226 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16227 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16229 (defun org-calendar-holiday ()
16230 "List of holidays, for Diary display in Org-mode."
16231 (require 'holidays)
16232 (let ((hl (funcall
16233 (if (fboundp 'calendar-check-holidays)
16234 'calendar-check-holidays 'check-calendar-holidays) date)))
16235 (if hl (mapconcat 'identity hl "; "))))
16237 (defun org-diary-sexp-entry (sexp entry date)
16238 "Process a SEXP diary ENTRY for DATE."
16239 (require 'diary-lib)
16240 (let ((result (if calendar-debug-sexp
16241 (let ((stack-trace-on-error t))
16242 (eval (car (read-from-string sexp))))
16243 (condition-case nil
16244 (eval (car (read-from-string sexp)))
16245 (error
16246 (beep)
16247 (message "Bad sexp at line %d in %s: %s"
16248 (org-current-line)
16249 (buffer-file-name) sexp)
16250 (sleep-for 2))))))
16251 (cond ((stringp result) (split-string result "; "))
16252 ((and (consp result)
16253 (not (consp (cdr result)))
16254 (stringp (cdr result))) (cdr result))
16255 ((and (consp result)
16256 (stringp (car result))) result)
16257 (result entry))))
16259 (defun org-diary-to-ical-string (frombuf)
16260 "Get iCalendar entries from diary entries in buffer FROMBUF.
16261 This uses the icalendar.el library."
16262 (let* ((tmpdir (if (featurep 'xemacs)
16263 (temp-directory)
16264 temporary-file-directory))
16265 (tmpfile (make-temp-name
16266 (expand-file-name "orgics" tmpdir)))
16267 buf rtn b e)
16268 (with-current-buffer frombuf
16269 (icalendar-export-region (point-min) (point-max) tmpfile)
16270 (setq buf (find-buffer-visiting tmpfile))
16271 (set-buffer buf)
16272 (goto-char (point-min))
16273 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16274 (setq b (match-beginning 0)))
16275 (goto-char (point-max))
16276 (if (re-search-backward "^END:VEVENT" nil t)
16277 (setq e (match-end 0)))
16278 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16279 (kill-buffer buf)
16280 (delete-file tmpfile)
16281 rtn))
16283 (defun org-closest-date (start current change prefer show-all)
16284 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16285 When PREFER is `past', return a date that is either CURRENT or past.
16286 When PREFER is `future', return a date that is either CURRENT or future.
16287 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16288 ;; Make the proper lists from the dates
16289 (catch 'exit
16290 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16291 dn dw sday cday n1 n2 n0
16292 d m y y1 y2 date1 date2 nmonths nm ny m2)
16294 (setq start (org-date-to-gregorian start)
16295 current (org-date-to-gregorian
16296 (if show-all
16297 current
16298 (time-to-days (current-time))))
16299 sday (calendar-absolute-from-gregorian start)
16300 cday (calendar-absolute-from-gregorian current))
16302 (if (<= cday sday) (throw 'exit sday))
16304 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16305 (setq dn (string-to-number (match-string 1 change))
16306 dw (cdr (assoc (match-string 2 change) a1)))
16307 (error "Invalid change specifier: %s" change))
16308 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16309 (cond
16310 ((eq dw 'day)
16311 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16312 n2 (+ n1 dn)))
16313 ((eq dw 'year)
16314 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16315 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16316 (setq date1 (list m d y1)
16317 n1 (calendar-absolute-from-gregorian date1)
16318 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16319 n2 (calendar-absolute-from-gregorian date2)))
16320 ((eq dw 'month)
16321 ;; approx number of month between the two dates
16322 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16323 ;; How often does dn fit in there?
16324 (setq d (nth 1 start) m (car start) y (nth 2 start)
16325 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16326 m (+ m nm)
16327 ny (floor (/ m 12))
16328 y (+ y ny)
16329 m (- m (* ny 12)))
16330 (while (> m 12) (setq m (- m 12) y (1+ y)))
16331 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16332 (setq m2 (+ m dn) y2 y)
16333 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16334 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16335 (while (<= n2 cday)
16336 (setq n1 n2 m m2 y y2)
16337 (setq m2 (+ m dn) y2 y)
16338 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16339 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16340 ;; Make sure n1 is the earlier date
16341 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16342 (if show-all
16343 (cond
16344 ((eq prefer 'past) (if (= cday n2) n2 n1))
16345 ((eq prefer 'future) (if (= cday n1) n1 n2))
16346 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16347 (cond
16348 ((eq prefer 'past) (if (= cday n2) n2 n1))
16349 ((eq prefer 'future) (if (= cday n1) n1 n2))
16350 (t (if (= cday n1) n1 n2)))))))
16352 (defun org-date-to-gregorian (date)
16353 "Turn any specification of DATE into a Gregorian date for the calendar."
16354 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16355 ((and (listp date) (= (length date) 3)) date)
16356 ((stringp date)
16357 (setq date (org-parse-time-string date))
16358 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16359 ((listp date)
16360 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16362 (defun org-parse-time-string (s &optional nodefault)
16363 "Parse the standard Org-mode time string.
16364 This should be a lot faster than the normal `parse-time-string'.
16365 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16366 hour and minute fields will be nil if not given."
16367 (if (string-match org-ts-regexp0 s)
16368 (list 0
16369 (if (or (match-beginning 8) (not nodefault))
16370 (string-to-number (or (match-string 8 s) "0")))
16371 (if (or (match-beginning 7) (not nodefault))
16372 (string-to-number (or (match-string 7 s) "0")))
16373 (string-to-number (match-string 4 s))
16374 (string-to-number (match-string 3 s))
16375 (string-to-number (match-string 2 s))
16376 nil nil nil)
16377 (error "Not a standard Org-mode time string: %s" s)))
16379 (defun org-timestamp-up (&optional arg)
16380 "Increase the date item at the cursor by one.
16381 If the cursor is on the year, change the year. If it is on the month,
16382 the day or the time, change that.
16383 With prefix ARG, change by that many units."
16384 (interactive "p")
16385 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16387 (defun org-timestamp-down (&optional arg)
16388 "Decrease the date item at the cursor by one.
16389 If the cursor is on the year, change the year. If it is on the month,
16390 the day or the time, change that.
16391 With prefix ARG, change by that many units."
16392 (interactive "p")
16393 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16395 (defun org-timestamp-up-day (&optional arg)
16396 "Increase the date in the time stamp by one day.
16397 With prefix ARG, change that many days."
16398 (interactive "p")
16399 (if (and (not (org-at-timestamp-p t))
16400 (org-at-heading-p))
16401 (org-todo 'up)
16402 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16404 (defun org-timestamp-down-day (&optional arg)
16405 "Decrease the date in the time stamp by one day.
16406 With prefix ARG, change that many days."
16407 (interactive "p")
16408 (if (and (not (org-at-timestamp-p t))
16409 (org-at-heading-p))
16410 (org-todo 'down)
16411 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16413 (defun org-at-timestamp-p (&optional inactive-ok)
16414 "Determine if the cursor is in or at a timestamp."
16415 (interactive)
16416 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16417 (pos (point))
16418 (ans (or (looking-at tsr)
16419 (save-excursion
16420 (skip-chars-backward "^[<\n\r\t")
16421 (if (> (point) (point-min)) (backward-char 1))
16422 (and (looking-at tsr)
16423 (> (- (match-end 0) pos) -1))))))
16424 (and ans
16425 (boundp 'org-ts-what)
16426 (setq org-ts-what
16427 (cond
16428 ((= pos (match-beginning 0)) 'bracket)
16429 ;; Point is considered to be "on the bracket" whether
16430 ;; it's really on it or right after it.
16431 ((= pos (1- (match-end 0))) 'bracket)
16432 ((= pos (match-end 0)) 'after)
16433 ((org-pos-in-match-range pos 2) 'year)
16434 ((org-pos-in-match-range pos 3) 'month)
16435 ((org-pos-in-match-range pos 7) 'hour)
16436 ((org-pos-in-match-range pos 8) 'minute)
16437 ((or (org-pos-in-match-range pos 4)
16438 (org-pos-in-match-range pos 5)) 'day)
16439 ((and (> pos (or (match-end 8) (match-end 5)))
16440 (< pos (match-end 0)))
16441 (- pos (or (match-end 8) (match-end 5))))
16442 (t 'day))))
16443 ans))
16445 (defun org-toggle-timestamp-type ()
16446 "Toggle the type (<active> or [inactive]) of a time stamp."
16447 (interactive)
16448 (when (org-at-timestamp-p t)
16449 (let ((beg (match-beginning 0)) (end (match-end 0))
16450 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16451 (save-excursion
16452 (goto-char beg)
16453 (while (re-search-forward "[][<>]" end t)
16454 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16455 t t)))
16456 (message "Timestamp is now %sactive"
16457 (if (equal (char-after beg) ?<) "" "in")))))
16459 (defvar org-clock-history) ; defined in org-clock.el
16460 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16461 (defun org-timestamp-change (n &optional what updown)
16462 "Change the date in the time stamp at point.
16463 The date will be changed by N times WHAT. WHAT can be `day', `month',
16464 `year', `minute', `second'. If WHAT is not given, the cursor position
16465 in the timestamp determines what will be changed."
16466 (let ((origin (point)) origin-cat
16467 with-hm inactive
16468 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16469 org-ts-what
16470 extra rem
16471 ts time time0 fixnext clrgx)
16472 (if (not (org-at-timestamp-p t))
16473 (error "Not at a timestamp"))
16474 (if (and (not what) (eq org-ts-what 'bracket))
16475 (org-toggle-timestamp-type)
16476 ;; Point isn't on brackets. Remember the part of the time-stamp
16477 ;; the point was in. Indeed, size of time-stamps may change,
16478 ;; but point must be kept in the same category nonetheless.
16479 (setq origin-cat org-ts-what)
16480 (if (and (not what) (not (eq org-ts-what 'day))
16481 org-display-custom-times
16482 (get-text-property (point) 'display)
16483 (not (get-text-property (1- (point)) 'display)))
16484 (setq org-ts-what 'day))
16485 (setq org-ts-what (or what org-ts-what)
16486 inactive (= (char-after (match-beginning 0)) ?\[)
16487 ts (match-string 0))
16488 (replace-match "")
16489 (if (string-match
16490 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16492 (setq extra (match-string 1 ts)))
16493 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16494 (setq with-hm t))
16495 (setq time0 (org-parse-time-string ts))
16496 (when (and updown
16497 (eq org-ts-what 'minute)
16498 (not current-prefix-arg))
16499 ;; This looks like s-up and s-down. Change by one rounding step.
16500 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16501 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16502 (setcar (cdr time0) (+ (nth 1 time0)
16503 (if (> n 0) (- rem) (- dm rem))))))
16504 (setq time
16505 (encode-time (or (car time0) 0)
16506 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16507 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16508 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16509 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16510 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16511 (nthcdr 6 time0)))
16512 (when (and (member org-ts-what '(hour minute))
16513 extra
16514 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16515 (setq extra (org-modify-ts-extra
16516 extra
16517 (if (eq org-ts-what 'hour) 2 5)
16518 n dm)))
16519 (when (integerp org-ts-what)
16520 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16521 (if (eq what 'calendar)
16522 (let ((cal-date (org-get-date-from-calendar)))
16523 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16524 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16525 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16526 (setcar time0 (or (car time0) 0))
16527 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16528 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16529 (setq time (apply 'encode-time time0))))
16530 ;; Insert the new time-stamp, and ensure point stays in the same
16531 ;; category as before (i.e. not after the last position in that
16532 ;; category).
16533 (let ((pos (point)))
16534 ;; Stay before inserted string. `save-excursion' is of no use.
16535 (setq org-last-changed-timestamp
16536 (org-insert-time-stamp time with-hm inactive nil nil extra))
16537 (goto-char pos))
16538 (save-match-data
16539 (looking-at org-ts-regexp3)
16540 (goto-char (cond
16541 ;; `day' category ends before `hour' if any, or at
16542 ;; the end of the day name.
16543 ((eq origin-cat 'day)
16544 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16545 ((eq origin-cat 'hour) (min (match-end 7) origin))
16546 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16547 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16548 ;; `year' and `month' have both fixed size: point
16549 ;; couldn't have moved into another part.
16550 (t origin))))
16551 ;; Update clock if on a CLOCK line.
16552 (org-clock-update-time-maybe)
16553 ;; Maybe adjust the closest clock in `org-clock-history'
16554 (when org-clock-adjust-closest
16555 (if (not (and (org-at-clock-log-p)
16556 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16557 org-clock-history))))))
16558 (message "No clock to adjust")
16559 (cond ((save-excursion ; fix previous clock?
16560 (re-search-backward org-ts-regexp0 nil t)
16561 (org-looking-back (concat org-clock-string " \\[")))
16562 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16563 ((save-excursion ; fix next clock?
16564 (re-search-backward org-ts-regexp0 nil t)
16565 (looking-at (concat org-ts-regexp0 "\\] =>")))
16566 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16567 (save-window-excursion
16568 ;; Find closest clock to point, adjust the previous/next one in history
16569 (let* ((p (save-excursion (org-back-to-heading t)))
16570 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16571 (clfixnth
16572 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16573 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16574 (if (not clfixpos)
16575 (message "No clock to adjust")
16576 (save-excursion
16577 (org-goto-marker-or-bmk clfixpos)
16578 (org-show-subtree)
16579 (when (re-search-forward clrgx nil t)
16580 (goto-char (match-beginning 1))
16581 (let (org-clock-adjust-closest)
16582 (org-timestamp-change n org-ts-what updown))
16583 (message "Clock adjusted in %s for heading: %s"
16584 (file-name-nondirectory (buffer-file-name))
16585 (org-get-heading t t)))))))))
16586 ;; Try to recenter the calendar window, if any.
16587 (if (and org-calendar-follow-timestamp-change
16588 (get-buffer-window "*Calendar*" t)
16589 (memq org-ts-what '(day month year)))
16590 (org-recenter-calendar (time-to-days time))))))
16592 (defun org-modify-ts-extra (s pos n dm)
16593 "Change the different parts of the lead-time and repeat fields in timestamp."
16594 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16595 ng h m new rem)
16596 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16597 (cond
16598 ((or (org-pos-in-match-range pos 2)
16599 (org-pos-in-match-range pos 3))
16600 (setq m (string-to-number (match-string 3 s))
16601 h (string-to-number (match-string 2 s)))
16602 (if (org-pos-in-match-range pos 2)
16603 (setq h (+ h n))
16604 (setq n (* dm (org-no-warnings (signum n))))
16605 (when (not (= 0 (setq rem (% m dm))))
16606 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16607 (setq m (+ m n)))
16608 (if (< m 0) (setq m (+ m 60) h (1- h)))
16609 (if (> m 59) (setq m (- m 60) h (1+ h)))
16610 (setq h (min 24 (max 0 h)))
16611 (setq ng 1 new (format "-%02d:%02d" h m)))
16612 ((org-pos-in-match-range pos 6)
16613 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16614 ((org-pos-in-match-range pos 5)
16615 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16617 ((org-pos-in-match-range pos 9)
16618 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16619 ((org-pos-in-match-range pos 8)
16620 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16622 (when ng
16623 (setq s (concat
16624 (substring s 0 (match-beginning ng))
16626 (substring s (match-end ng))))))
16629 (defun org-recenter-calendar (date)
16630 "If the calendar is visible, recenter it to DATE."
16631 (let ((cwin (get-buffer-window "*Calendar*" t)))
16632 (when cwin
16633 (let ((calendar-move-hook nil))
16634 (with-selected-window cwin
16635 (calendar-goto-date (if (listp date) date
16636 (calendar-gregorian-from-absolute date))))))))
16638 (defun org-goto-calendar (&optional arg)
16639 "Go to the Emacs calendar at the current date.
16640 If there is a time stamp in the current line, go to that date.
16641 A prefix ARG can be used to force the current date."
16642 (interactive "P")
16643 (let ((tsr org-ts-regexp) diff
16644 (calendar-move-hook nil)
16645 (calendar-view-holidays-initially-flag nil)
16646 (calendar-view-diary-initially-flag nil))
16647 (if (or (org-at-timestamp-p)
16648 (save-excursion
16649 (beginning-of-line 1)
16650 (looking-at (concat ".*" tsr))))
16651 (let ((d1 (time-to-days (current-time)))
16652 (d2 (time-to-days
16653 (org-time-string-to-time (match-string 1)))))
16654 (setq diff (- d2 d1))))
16655 (calendar)
16656 (calendar-goto-today)
16657 (if (and diff (not arg)) (calendar-forward-day diff))))
16659 (defun org-get-date-from-calendar ()
16660 "Return a list (month day year) of date at point in calendar."
16661 (with-current-buffer "*Calendar*"
16662 (save-match-data
16663 (calendar-cursor-to-date))))
16665 (defun org-date-from-calendar ()
16666 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16667 If there is already a time stamp at the cursor position, update it."
16668 (interactive)
16669 (if (org-at-timestamp-p t)
16670 (org-timestamp-change 0 'calendar)
16671 (let ((cal-date (org-get-date-from-calendar)))
16672 (org-insert-time-stamp
16673 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16675 (defun org-minutes-to-hh:mm-string (m)
16676 "Compute H:MM from a number of minutes."
16677 (let ((h (/ m 60)))
16678 (setq m (- m (* 60 h)))
16679 (format org-time-clocksum-format h m)))
16681 (defun org-hh:mm-string-to-minutes (s)
16682 "Convert a string H:MM to a number of minutes.
16683 If the string is just a number, interpret it as minutes.
16684 In fact, the first hh:mm or number in the string will be taken,
16685 there can be extra stuff in the string.
16686 If no number is found, the return value is 0."
16687 (cond
16688 ((integerp s) s)
16689 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16690 (+ (* (string-to-number (match-string 1 s)) 60)
16691 (string-to-number (match-string 2 s))))
16692 ((string-match "\\([0-9]+\\)" s)
16693 (string-to-number (match-string 1 s)))
16694 (t 0)))
16696 (defcustom org-effort-durations
16697 `(("h" . 60)
16698 ("d" . ,(* 60 8))
16699 ("w" . ,(* 60 8 5))
16700 ("m" . ,(* 60 8 5 4))
16701 ("y" . ,(* 60 8 5 40)))
16702 "Conversion factor to minutes for an effort modifier.
16704 Each entry has the form (MODIFIER . MINUTES).
16706 In an effort string, a number followed by MODIFIER is multiplied
16707 by the specified number of MINUTES to obtain an effort in
16708 minutes.
16710 For example, if the value of this variable is ((\"hours\" . 60)), then an
16711 effort string \"2hours\" is equivalent to 120 minutes."
16712 :group 'org-agenda
16713 :version "24.1"
16714 :type '(alist :key-type (string :tag "Modifier")
16715 :value-type (number :tag "Minutes")))
16717 (defun org-duration-string-to-minutes (s &optional output-to-string)
16718 "Convert a duration string S to minutes.
16720 A bare number is interpreted as minutes, modifiers can be set by
16721 customizing `org-effort-durations' (which see).
16723 Entries containing a colon are interpreted as H:MM by
16724 `org-hh:mm-string-to-minutes'."
16725 (let ((result 0)
16726 (re (concat "\\([0-9.]+\\) *\\("
16727 (regexp-opt (mapcar 'car org-effort-durations))
16728 "\\)")))
16729 (while (string-match re s)
16730 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16731 (string-to-number (match-string 1 s))))
16732 (setq s (replace-match "" nil t s)))
16733 (setq result (floor result))
16734 (incf result (org-hh:mm-string-to-minutes s))
16735 (if output-to-string (number-to-string result) result)))
16737 ;;;; Files
16739 (defun org-save-all-org-buffers ()
16740 "Save all Org-mode buffers without user confirmation."
16741 (interactive)
16742 (message "Saving all Org-mode buffers...")
16743 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16744 (when (featurep 'org-id) (org-id-locations-save))
16745 (message "Saving all Org-mode buffers... done"))
16747 (defun org-revert-all-org-buffers ()
16748 "Revert all Org-mode buffers.
16749 Prompt for confirmation when there are unsaved changes.
16750 Be sure you know what you are doing before letting this function
16751 overwrite your changes.
16753 This function is useful in a setup where one tracks org files
16754 with a version control system, to revert on one machine after pulling
16755 changes from another. I believe the procedure must be like this:
16757 1. M-x org-save-all-org-buffers
16758 2. Pull changes from the other machine, resolve conflicts
16759 3. M-x org-revert-all-org-buffers"
16760 (interactive)
16761 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16762 (error "Abort"))
16763 (save-excursion
16764 (save-window-excursion
16765 (mapc
16766 (lambda (b)
16767 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16768 (with-current-buffer b buffer-file-name))
16769 (org-pop-to-buffer-same-window b)
16770 (revert-buffer t 'no-confirm)))
16771 (buffer-list))
16772 (when (and (featurep 'org-id) org-id-track-globally)
16773 (org-id-locations-load)))))
16775 ;;;; Agenda files
16777 ;;;###autoload
16778 (defun org-switchb (&optional arg)
16779 "Switch between Org buffers.
16780 With one prefix argument, restrict available buffers to files.
16781 With two prefix arguments, restrict available buffers to agenda files.
16783 Defaults to `iswitchb' for buffer name completion.
16784 Set `org-completion-use-ido' to make it use ido instead."
16785 (interactive "P")
16786 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16787 ((equal arg '(16)) (org-buffer-list 'agenda))
16788 (t (org-buffer-list))))
16789 (org-completion-use-iswitchb org-completion-use-iswitchb)
16790 (org-completion-use-ido org-completion-use-ido))
16791 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16792 (setq org-completion-use-iswitchb t))
16793 (org-pop-to-buffer-same-window
16794 (org-icompleting-read "Org buffer: "
16795 (mapcar 'list (mapcar 'buffer-name blist))
16796 nil t))))
16798 ;;; Define some older names previously used for this functionality
16799 ;;;###autoload
16800 (defalias 'org-ido-switchb 'org-switchb)
16801 ;;;###autoload
16802 (defalias 'org-iswitchb 'org-switchb)
16804 (defun org-buffer-list (&optional predicate exclude-tmp)
16805 "Return a list of Org buffers.
16806 PREDICATE can be `export', `files' or `agenda'.
16808 export restrict the list to Export buffers.
16809 files restrict the list to buffers visiting Org files.
16810 agenda restrict the list to buffers visiting agenda files.
16812 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16813 (let* ((bfn nil)
16814 (agenda-files (and (eq predicate 'agenda)
16815 (mapcar 'file-truename (org-agenda-files t))))
16816 (filter
16817 (cond
16818 ((eq predicate 'files)
16819 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16820 ((eq predicate 'export)
16821 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16822 ((eq predicate 'agenda)
16823 (lambda (b)
16824 (with-current-buffer b
16825 (and (derived-mode-p 'org-mode)
16826 (setq bfn (buffer-file-name b))
16827 (member (file-truename bfn) agenda-files)))))
16828 (t (lambda (b) (with-current-buffer b
16829 (or (derived-mode-p 'org-mode)
16830 (string-match "\*Org .*Export"
16831 (buffer-name b)))))))))
16832 (delq nil
16833 (mapcar
16834 (lambda(b)
16835 (if (and (funcall filter b)
16836 (or (not exclude-tmp)
16837 (not (string-match "tmp" (buffer-name b)))))
16839 nil))
16840 (buffer-list)))))
16842 (defun org-agenda-files (&optional unrestricted archives)
16843 "Get the list of agenda files.
16844 Optional UNRESTRICTED means return the full list even if a restriction
16845 is currently in place.
16846 When ARCHIVES is t, include all archive files that are really being
16847 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16848 `org-agenda-archives-mode' is t."
16849 (let ((files
16850 (cond
16851 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16852 ((stringp org-agenda-files) (org-read-agenda-file-list))
16853 ((listp org-agenda-files) org-agenda-files)
16854 (t (error "Invalid value of `org-agenda-files'")))))
16855 (setq files (apply 'append
16856 (mapcar (lambda (f)
16857 (if (file-directory-p f)
16858 (directory-files
16859 f t org-agenda-file-regexp)
16860 (list f)))
16861 files)))
16862 (when org-agenda-skip-unavailable-files
16863 (setq files (delq nil
16864 (mapcar (function
16865 (lambda (file)
16866 (and (file-readable-p file) file)))
16867 files))))
16868 (when (or (eq archives t)
16869 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16870 (setq files (org-add-archive-files files)))
16871 files))
16873 (defun org-agenda-file-p (&optional file)
16874 "Return non-nil, if FILE is an agenda file.
16875 If FILE is omitted, use the file associated with the current
16876 buffer."
16877 (member (or file (buffer-file-name))
16878 (org-agenda-files t)))
16880 (defun org-edit-agenda-file-list ()
16881 "Edit the list of agenda files.
16882 Depending on setup, this either uses customize to edit the variable
16883 `org-agenda-files', or it visits the file that is holding the list. In the
16884 latter case, the buffer is set up in a way that saving it automatically kills
16885 the buffer and restores the previous window configuration."
16886 (interactive)
16887 (if (stringp org-agenda-files)
16888 (let ((cw (current-window-configuration)))
16889 (find-file org-agenda-files)
16890 (org-set-local 'org-window-configuration cw)
16891 (org-add-hook 'after-save-hook
16892 (lambda ()
16893 (set-window-configuration
16894 (prog1 org-window-configuration
16895 (kill-buffer (current-buffer))))
16896 (org-install-agenda-files-menu)
16897 (message "New agenda file list installed"))
16898 nil 'local)
16899 (message "%s" (substitute-command-keys
16900 "Edit list and finish with \\[save-buffer]")))
16901 (customize-variable 'org-agenda-files)))
16903 (defun org-store-new-agenda-file-list (list)
16904 "Set new value for the agenda file list and save it correctly."
16905 (if (stringp org-agenda-files)
16906 (let ((fe (org-read-agenda-file-list t)) b u)
16907 (while (setq b (find-buffer-visiting org-agenda-files))
16908 (kill-buffer b))
16909 (with-temp-file org-agenda-files
16910 (insert
16911 (mapconcat
16912 (lambda (f) ;; Keep un-expanded entries.
16913 (if (setq u (assoc f fe))
16914 (cdr u)
16916 list "\n")
16917 "\n")))
16918 (let ((org-mode-hook nil) (org-inhibit-startup t)
16919 (org-insert-mode-line-in-empty-file nil))
16920 (setq org-agenda-files list)
16921 (customize-save-variable 'org-agenda-files org-agenda-files))))
16923 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16924 "Read the list of agenda files from a file.
16925 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16926 filenames, used by `org-store-new-agenda-file-list' to write back
16927 un-expanded file names."
16928 (when (file-directory-p org-agenda-files)
16929 (error "`org-agenda-files' cannot be a single directory"))
16930 (when (stringp org-agenda-files)
16931 (with-temp-buffer
16932 (insert-file-contents org-agenda-files)
16933 (mapcar
16934 (lambda (f)
16935 (let ((e (expand-file-name (substitute-in-file-name f)
16936 org-directory)))
16937 (if pair-with-expansion
16938 (cons e f)
16939 e)))
16940 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16942 ;;;###autoload
16943 (defun org-cycle-agenda-files ()
16944 "Cycle through the files in `org-agenda-files'.
16945 If the current buffer visits an agenda file, find the next one in the list.
16946 If the current buffer does not, find the first agenda file."
16947 (interactive)
16948 (let* ((fs (org-agenda-files t))
16949 (files (append fs (list (car fs))))
16950 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16951 file)
16952 (unless files (error "No agenda files"))
16953 (catch 'exit
16954 (while (setq file (pop files))
16955 (if (equal (file-truename file) tcf)
16956 (when (car files)
16957 (find-file (car files))
16958 (throw 'exit t))))
16959 (find-file (car fs)))
16960 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16962 (defun org-agenda-file-to-front (&optional to-end)
16963 "Move/add the current file to the top of the agenda file list.
16964 If the file is not present in the list, it is added to the front. If it is
16965 present, it is moved there. With optional argument TO-END, add/move to the
16966 end of the list."
16967 (interactive "P")
16968 (let ((org-agenda-skip-unavailable-files nil)
16969 (file-alist (mapcar (lambda (x)
16970 (cons (file-truename x) x))
16971 (org-agenda-files t)))
16972 (ctf (file-truename buffer-file-name))
16973 x had)
16974 (setq x (assoc ctf file-alist) had x)
16976 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16977 (if to-end
16978 (setq file-alist (append (delq x file-alist) (list x)))
16979 (setq file-alist (cons x (delq x file-alist))))
16980 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16981 (org-install-agenda-files-menu)
16982 (message "File %s to %s of agenda file list"
16983 (if had "moved" "added") (if to-end "end" "front"))))
16985 (defun org-remove-file (&optional file)
16986 "Remove current file from the list of files in variable `org-agenda-files'.
16987 These are the files which are being checked for agenda entries.
16988 Optional argument FILE means use this file instead of the current."
16989 (interactive)
16990 (let* ((org-agenda-skip-unavailable-files nil)
16991 (file (or file buffer-file-name))
16992 (true-file (file-truename file))
16993 (afile (abbreviate-file-name file))
16994 (files (delq nil (mapcar
16995 (lambda (x)
16996 (if (equal true-file
16997 (file-truename x))
16998 nil x))
16999 (org-agenda-files t)))))
17000 (if (not (= (length files) (length (org-agenda-files t))))
17001 (progn
17002 (org-store-new-agenda-file-list files)
17003 (org-install-agenda-files-menu)
17004 (message "Removed file: %s" afile))
17005 (message "File was not in list: %s (not removed)" afile))))
17007 (defun org-file-menu-entry (file)
17008 (vector file (list 'find-file file) t))
17010 (defun org-check-agenda-file (file)
17011 "Make sure FILE exists. If not, ask user what to do."
17012 (when (not (file-exists-p file))
17013 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17014 (abbreviate-file-name file))
17015 (let ((r (downcase (read-char-exclusive))))
17016 (cond
17017 ((equal r ?r)
17018 (org-remove-file file)
17019 (throw 'nextfile t))
17020 (t (error "Abort"))))))
17022 (defun org-get-agenda-file-buffer (file)
17023 "Get a buffer visiting FILE. If the buffer needs to be created, add
17024 it to the list of buffers which might be released later."
17025 (let ((buf (org-find-base-buffer-visiting file)))
17026 (if buf
17027 buf ; just return it
17028 ;; Make a new buffer and remember it
17029 (setq buf (find-file-noselect file))
17030 (if buf (push buf org-agenda-new-buffers))
17031 buf)))
17033 (defun org-release-buffers (blist)
17034 "Release all buffers in list, asking the user for confirmation when needed.
17035 When a buffer is unmodified, it is just killed. When modified, it is saved
17036 \(if the user agrees) and then killed."
17037 (let (buf file)
17038 (while (setq buf (pop blist))
17039 (setq file (buffer-file-name buf))
17040 (when (and (buffer-modified-p buf)
17041 file
17042 (y-or-n-p (format "Save file %s? " file)))
17043 (with-current-buffer buf (save-buffer)))
17044 (kill-buffer buf))))
17046 (defun org-agenda-prepare-buffers (files)
17047 "Create buffers for all agenda files, protect archived trees and comments."
17048 (interactive)
17049 (let ((pa '(:org-archived t))
17050 (pc '(:org-comment t))
17051 (pall '(:org-archived t :org-comment t))
17052 (inhibit-read-only t)
17053 (rea (concat ":" org-archive-tag ":"))
17054 bmp file re)
17055 (save-excursion
17056 (save-restriction
17057 (while (setq file (pop files))
17058 (catch 'nextfile
17059 (if (bufferp file)
17060 (set-buffer file)
17061 (org-check-agenda-file file)
17062 (set-buffer (org-get-agenda-file-buffer file)))
17063 (widen)
17064 (setq bmp (buffer-modified-p))
17065 (org-refresh-category-properties)
17066 (setq org-todo-keywords-for-agenda
17067 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17068 (setq org-done-keywords-for-agenda
17069 (append org-done-keywords-for-agenda org-done-keywords))
17070 (setq org-todo-keyword-alist-for-agenda
17071 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17072 (setq org-drawers-for-agenda
17073 (append org-drawers-for-agenda org-drawers))
17074 (setq org-tag-alist-for-agenda
17075 (append org-tag-alist-for-agenda org-tag-alist))
17077 (save-excursion
17078 (remove-text-properties (point-min) (point-max) pall)
17079 (when org-agenda-skip-archived-trees
17080 (goto-char (point-min))
17081 (while (re-search-forward rea nil t)
17082 (if (org-at-heading-p t)
17083 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17084 (goto-char (point-min))
17085 (setq re (format org-heading-keyword-regexp-format
17086 org-comment-string))
17087 (while (re-search-forward re nil t)
17088 (add-text-properties
17089 (match-beginning 0) (org-end-of-subtree t) pc)))
17090 (set-buffer-modified-p bmp)))))
17091 (setq org-todo-keywords-for-agenda
17092 (org-uniquify org-todo-keywords-for-agenda))
17093 (setq org-todo-keyword-alist-for-agenda
17094 (org-uniquify org-todo-keyword-alist-for-agenda)
17095 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17097 ;;;; Embedded LaTeX
17099 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17100 "Keymap for the minor `org-cdlatex-mode'.")
17102 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17103 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17104 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17105 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17106 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17108 (defvar org-cdlatex-texmathp-advice-is-done nil
17109 "Flag remembering if we have applied the advice to texmathp already.")
17111 (define-minor-mode org-cdlatex-mode
17112 "Toggle the minor `org-cdlatex-mode'.
17113 This mode supports entering LaTeX environment and math in LaTeX fragments
17114 in Org-mode.
17115 \\{org-cdlatex-mode-map}"
17116 nil " OCDL" nil
17117 (when org-cdlatex-mode
17118 (require 'cdlatex)
17119 (run-hooks 'cdlatex-mode-hook)
17120 (cdlatex-compute-tables))
17121 (unless org-cdlatex-texmathp-advice-is-done
17122 (setq org-cdlatex-texmathp-advice-is-done t)
17123 (defadvice texmathp (around org-math-always-on activate)
17124 "Always return t in org-mode buffers.
17125 This is because we want to insert math symbols without dollars even outside
17126 the LaTeX math segments. If Orgmode thinks that point is actually inside
17127 an embedded LaTeX fragment, let texmathp do its job.
17128 \\[org-cdlatex-mode-map]"
17129 (interactive)
17130 (let (p)
17131 (cond
17132 ((not (derived-mode-p 'org-mode)) ad-do-it)
17133 ((eq this-command 'cdlatex-math-symbol)
17134 (setq ad-return-value t
17135 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17137 (let ((p (org-inside-LaTeX-fragment-p)))
17138 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17139 (setq ad-return-value t
17140 texmathp-why '("Org-mode embedded math" . 0))
17141 (if p ad-do-it)))))))))
17143 (defun turn-on-org-cdlatex ()
17144 "Unconditionally turn on `org-cdlatex-mode'."
17145 (org-cdlatex-mode 1))
17147 (defun org-inside-LaTeX-fragment-p ()
17148 "Test if point is inside a LaTeX fragment.
17149 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17150 sequence appearing also before point.
17151 Even though the matchers for math are configurable, this function assumes
17152 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17153 delimiters are skipped when they have been removed by customization.
17154 The return value is nil, or a cons cell with the delimiter and the
17155 position of this delimiter.
17157 This function does a reasonably good job, but can locally be fooled by
17158 for example currency specifications. For example it will assume being in
17159 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17160 fragments that are properly closed, but during editing, we have to live
17161 with the uncertainty caused by missing closing delimiters. This function
17162 looks only before point, not after."
17163 (catch 'exit
17164 (let ((pos (point))
17165 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17166 (lim (progn
17167 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17168 (point)))
17169 dd-on str (start 0) m re)
17170 (goto-char pos)
17171 (when dodollar
17172 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17173 re (nth 1 (assoc "$" org-latex-regexps)))
17174 (while (string-match re str start)
17175 (cond
17176 ((= (match-end 0) (length str))
17177 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17178 ((= (match-end 0) (- (length str) 5))
17179 (throw 'exit nil))
17180 (t (setq start (match-end 0))))))
17181 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17182 (goto-char pos)
17183 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17184 (and (match-beginning 2) (throw 'exit nil))
17185 ;; count $$
17186 (while (re-search-backward "\\$\\$" lim t)
17187 (setq dd-on (not dd-on)))
17188 (goto-char pos)
17189 (if dd-on (cons "$$" m))))))
17191 (defun org-inside-latex-macro-p ()
17192 "Is point inside a LaTeX macro or its arguments?"
17193 (save-match-data
17194 (org-in-regexp
17195 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17197 (defun org-try-cdlatex-tab ()
17198 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17199 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17200 - inside a LaTeX fragment, or
17201 - after the first word in a line, where an abbreviation expansion could
17202 insert a LaTeX environment."
17203 (when org-cdlatex-mode
17204 (cond
17205 ;; Before any word on the line: No expansion possible.
17206 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17207 ;; Just after first word on the line: Expand it. Make sure it
17208 ;; cannot happen on headlines, though.
17209 ((save-excursion
17210 (skip-chars-backward "a-zA-Z0-9*")
17211 (skip-chars-backward " \t")
17212 (and (bolp) (not (org-at-heading-p))))
17213 (cdlatex-tab) t)
17214 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17216 (defun org-cdlatex-underscore-caret (&optional arg)
17217 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17218 Revert to the normal definition outside of these fragments."
17219 (interactive "P")
17220 (if (org-inside-LaTeX-fragment-p)
17221 (call-interactively 'cdlatex-sub-superscript)
17222 (let (org-cdlatex-mode)
17223 (call-interactively (key-binding (vector last-input-event))))))
17225 (defun org-cdlatex-math-modify (&optional arg)
17226 "Execute `cdlatex-math-modify' in LaTeX fragments.
17227 Revert to the normal definition outside of these fragments."
17228 (interactive "P")
17229 (if (org-inside-LaTeX-fragment-p)
17230 (call-interactively 'cdlatex-math-modify)
17231 (let (org-cdlatex-mode)
17232 (call-interactively (key-binding (vector last-input-event))))))
17234 (defvar org-latex-fragment-image-overlays nil
17235 "List of overlays carrying the images of latex fragments.")
17236 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17238 (defun org-remove-latex-fragment-image-overlays ()
17239 "Remove all overlays with LaTeX fragment images in current buffer."
17240 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17241 (setq org-latex-fragment-image-overlays nil))
17243 (defun org-preview-latex-fragment (&optional subtree)
17244 "Preview the LaTeX fragment at point, or all locally or globally.
17245 If the cursor is in a LaTeX fragment, create the image and overlay
17246 it over the source code. If there is no fragment at point, display
17247 all fragments in the current text, from one headline to the next. With
17248 prefix SUBTREE, display all fragments in the current subtree. With a
17249 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17250 the cursor is before the first headline,
17251 display all fragments in the buffer.
17252 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17253 (interactive "P")
17254 (unless buffer-file-name
17255 (error "Can't preview LaTeX fragment in a non-file buffer"))
17256 (org-remove-latex-fragment-image-overlays)
17257 (save-excursion
17258 (save-restriction
17259 (let (beg end at msg)
17260 (cond
17261 ((or (equal subtree '(16))
17262 (not (save-excursion
17263 (re-search-backward org-outline-regexp-bol nil t))))
17264 (setq beg (point-min) end (point-max)
17265 msg "Creating images for buffer...%s"))
17266 ((equal subtree '(4))
17267 (org-back-to-heading)
17268 (setq beg (point) end (org-end-of-subtree t)
17269 msg "Creating images for subtree...%s"))
17271 (if (setq at (org-inside-LaTeX-fragment-p))
17272 (goto-char (max (point-min) (- (cdr at) 2)))
17273 (org-back-to-heading))
17274 (setq beg (point) end (progn (outline-next-heading) (point))
17275 msg (if at "Creating image...%s"
17276 "Creating images for entry...%s"))))
17277 (message msg "")
17278 (narrow-to-region beg end)
17279 (goto-char beg)
17280 (org-format-latex
17281 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17282 (file-name-nondirectory
17283 buffer-file-name)))
17284 default-directory 'overlays msg at 'forbuffer
17285 org-latex-create-formula-image-program)
17286 (message msg "done. Use `C-c C-c' to remove images.")))))
17288 (defvar org-latex-regexps
17289 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17290 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17291 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17292 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17293 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17294 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17295 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17296 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17297 "Regular expressions for matching embedded LaTeX.")
17299 (defvar org-export-have-math nil) ;; dynamic scoping
17300 (defun org-format-latex (prefix &optional dir overlays msg at
17301 forbuffer processing-type)
17302 "Replace LaTeX fragments with links to an image, and produce images.
17303 Some of the options can be changed using the variable
17304 `org-format-latex-options'."
17305 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17306 (let* ((prefixnodir (file-name-nondirectory prefix))
17307 (absprefix (expand-file-name prefix dir))
17308 (todir (file-name-directory absprefix))
17309 (opt org-format-latex-options)
17310 (matchers (plist-get opt :matchers))
17311 (re-list org-latex-regexps)
17312 (org-format-latex-header-extra
17313 (plist-get (org-infile-export-plist) :latex-header-extra))
17314 (cnt 0) txt hash link beg end re e checkdir
17315 executables-checked string
17316 m n block-type block linkfile movefile ov)
17317 ;; Check the different regular expressions
17318 (while (setq e (pop re-list))
17319 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17320 block (if block-type "\n\n" ""))
17321 (when (member m matchers)
17322 (goto-char (point-min))
17323 (while (re-search-forward re nil t)
17324 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17325 (not (get-text-property (match-beginning n)
17326 'org-protected))
17327 (or (not overlays)
17328 (not (eq (get-char-property (match-beginning n)
17329 'org-overlay-type)
17330 'org-latex-overlay))))
17331 (setq org-export-have-math t)
17332 (cond
17333 ((eq processing-type 'verbatim)
17334 ;; Leave the text verbatim, just protect it
17335 (add-text-properties (match-beginning n) (match-end n)
17336 '(org-protected t)))
17337 ((eq processing-type 'mathjax)
17338 ;; Prepare for MathJax processing
17339 (setq string (match-string n))
17340 (if (member m '("$" "$1"))
17341 (save-excursion
17342 (delete-region (match-beginning n) (match-end n))
17343 (goto-char (match-beginning n))
17344 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17345 "\\)")
17346 '(org-protected t))))
17347 (add-text-properties (match-beginning n) (match-end n)
17348 '(org-protected t))))
17349 ((or (eq processing-type 'dvipng)
17350 (eq processing-type 'imagemagick))
17351 ;; Process to an image
17352 (setq txt (match-string n)
17353 beg (match-beginning n) end (match-end n)
17354 cnt (1+ cnt))
17355 (let (print-length print-level) ; make sure full list is printed
17356 (setq hash (sha1 (prin1-to-string
17357 (list org-format-latex-header
17358 org-format-latex-header-extra
17359 org-export-latex-default-packages-alist
17360 org-export-latex-packages-alist
17361 org-format-latex-options
17362 forbuffer txt)))
17363 linkfile (format "%s_%s.png" prefix hash)
17364 movefile (format "%s_%s.png" absprefix hash)))
17365 (setq link (concat block "[[file:" linkfile "]]" block))
17366 (if msg (message msg cnt))
17367 (goto-char beg)
17368 (unless checkdir ; make sure the directory exists
17369 (setq checkdir t)
17370 (or (file-directory-p todir) (make-directory todir t)))
17371 (cond
17372 ((eq processing-type 'dvipng)
17373 (unless executables-checked
17374 (org-check-external-command
17375 "latex" "needed to convert LaTeX fragments to images")
17376 (org-check-external-command
17377 "dvipng" "needed to convert LaTeX fragments to images")
17378 (setq executables-checked t))
17379 (unless (file-exists-p movefile)
17380 (org-create-formula-image-with-dvipng
17381 txt movefile opt forbuffer)))
17382 ((eq processing-type 'imagemagick)
17383 (unless executables-checked
17384 (org-check-external-command
17385 "convert" "you need to install imagemagick")
17386 (setq executables-checked t))
17387 (unless (file-exists-p movefile)
17388 (org-create-formula-image-with-imagemagick
17389 txt movefile opt forbuffer))))
17390 (if overlays
17391 (progn
17392 (mapc (lambda (o)
17393 (if (eq (overlay-get o 'org-overlay-type)
17394 'org-latex-overlay)
17395 (delete-overlay o)))
17396 (overlays-in beg end))
17397 (setq ov (make-overlay beg end))
17398 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17399 (if (featurep 'xemacs)
17400 (progn
17401 (overlay-put ov 'invisible t)
17402 (overlay-put
17403 ov 'end-glyph
17404 (make-glyph (vector 'png :file movefile))))
17405 (overlay-put
17406 ov 'display
17407 (list 'image :type 'png :file movefile :ascent 'center)))
17408 (push ov org-latex-fragment-image-overlays)
17409 (goto-char end))
17410 (delete-region beg end)
17411 (insert (org-add-props link
17412 (list 'org-latex-src
17413 (replace-regexp-in-string
17414 "\"" "" txt)
17415 'org-latex-src-embed-type
17416 (if block-type 'paragraph 'character))))))
17417 ((eq processing-type 'mathml)
17418 ;; Process to MathML
17419 (unless executables-checked
17420 (unless (save-match-data (org-format-latex-mathml-available-p))
17421 (error "LaTeX to MathML converter not configured"))
17422 (setq executables-checked t))
17423 (setq txt (match-string n)
17424 beg (match-beginning n) end (match-end n)
17425 cnt (1+ cnt))
17426 (if msg (message msg cnt))
17427 (goto-char beg)
17428 (delete-region beg end)
17429 (insert (org-format-latex-as-mathml
17430 txt block-type prefix dir)))
17432 (error "Unknown conversion type %s for latex fragments"
17433 processing-type)))))))))
17435 (defun org-create-math-formula (latex-frag &optional mathml-file)
17436 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17437 Use `org-latex-to-mathml-convert-command'. If the conversion is
17438 sucessful, return the portion between \"<math...> </math>\"
17439 elements otherwise return nil. When MATHML-FILE is specified,
17440 write the results in to that file. When invoked as an
17441 interactive command, prompt for LATEX-FRAG, with initial value
17442 set to the current active region and echo the results for user
17443 inspection."
17444 (interactive (list (let ((frag (when (org-region-active-p)
17445 (buffer-substring-no-properties
17446 (region-beginning) (region-end)))))
17447 (read-string "LaTeX Fragment: " frag nil frag))))
17448 (unless latex-frag (error "Invalid latex-frag"))
17449 (let* ((tmp-in-file (file-relative-name
17450 (make-temp-name (expand-file-name "ltxmathml-in"))))
17451 (ignore (write-region latex-frag nil tmp-in-file))
17452 (tmp-out-file (file-relative-name
17453 (make-temp-name (expand-file-name "ltxmathml-out"))))
17454 (cmd (format-spec
17455 org-latex-to-mathml-convert-command
17456 `((?j . ,(shell-quote-argument
17457 (expand-file-name org-latex-to-mathml-jar-file)))
17458 (?I . ,(shell-quote-argument tmp-in-file))
17459 (?o . ,(shell-quote-argument tmp-out-file)))))
17460 mathml shell-command-output)
17461 (when (org-called-interactively-p 'any)
17462 (unless (org-format-latex-mathml-available-p)
17463 (error "LaTeX to MathML converter not configured")))
17464 (message "Running %s" cmd)
17465 (setq shell-command-output (shell-command-to-string cmd))
17466 (setq mathml
17467 (when (file-readable-p tmp-out-file)
17468 (with-current-buffer (find-file-noselect tmp-out-file t)
17469 (goto-char (point-min))
17470 (when (re-search-forward
17471 (concat
17472 (regexp-quote
17473 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17474 "\\(.\\|\n\\)*"
17475 (regexp-quote "</math>")) nil t)
17476 (prog1 (match-string 0) (kill-buffer))))))
17477 (cond
17478 (mathml
17479 (setq mathml
17480 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17481 (when mathml-file
17482 (write-region mathml nil mathml-file))
17483 (when (org-called-interactively-p 'any)
17484 (message mathml)))
17485 ((message "LaTeX to MathML conversion failed")
17486 (message shell-command-output)))
17487 (delete-file tmp-in-file)
17488 (when (file-exists-p tmp-out-file)
17489 (delete-file tmp-out-file))
17490 mathml))
17492 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17493 prefix &optional dir)
17494 "Use `org-create-math-formula' but check local cache first."
17495 (let* ((absprefix (expand-file-name prefix dir))
17496 (print-length nil) (print-level nil)
17497 (formula-id (concat
17498 "formula-"
17499 (sha1
17500 (prin1-to-string
17501 (list latex-frag
17502 org-latex-to-mathml-convert-command)))))
17503 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17504 (formula-cache-dir (file-name-directory formula-cache)))
17506 (unless (file-directory-p formula-cache-dir)
17507 (make-directory formula-cache-dir t))
17509 (unless (file-exists-p formula-cache)
17510 (org-create-math-formula latex-frag formula-cache))
17512 (if (file-exists-p formula-cache)
17513 ;; Successful conversion. Return the link to MathML file.
17514 (org-add-props
17515 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17516 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17517 'org-latex-src-embed-type (if latex-frag-type
17518 'paragraph 'character)))
17519 ;; Failed conversion. Return the LaTeX fragment verbatim
17520 (add-text-properties
17521 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17522 latex-frag)))
17524 ;; This function borrows from Ganesh Swami's latex2png.el
17525 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17526 "This calls dvipng."
17527 (require 'org-latex)
17528 (let* ((tmpdir (if (featurep 'xemacs)
17529 (temp-directory)
17530 temporary-file-directory))
17531 (texfilebase (make-temp-name
17532 (expand-file-name "orgtex" tmpdir)))
17533 (texfile (concat texfilebase ".tex"))
17534 (dvifile (concat texfilebase ".dvi"))
17535 (pngfile (concat texfilebase ".png"))
17536 (fnh (if (featurep 'xemacs)
17537 (font-height (face-font 'default))
17538 (face-attribute 'default :height nil)))
17539 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17540 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17541 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17542 "Black"))
17543 (bg (or (plist-get options (if buffer :background :html-background))
17544 "Transparent")))
17545 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17546 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17547 (with-temp-file texfile
17548 (insert (org-splice-latex-header
17549 org-format-latex-header
17550 org-export-latex-default-packages-alist
17551 org-export-latex-packages-alist t
17552 org-format-latex-header-extra))
17553 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17554 (require 'org-latex)
17555 (org-export-latex-fix-inputenc))
17556 (let ((dir default-directory))
17557 (condition-case nil
17558 (progn
17559 (cd tmpdir)
17560 (call-process "latex" nil nil nil texfile))
17561 (error nil))
17562 (cd dir))
17563 (if (not (file-exists-p dvifile))
17564 (progn (message "Failed to create dvi file from %s" texfile) nil)
17565 (condition-case nil
17566 (if (featurep 'xemacs)
17567 (call-process "dvipng" nil nil nil
17568 "-fg" fg "-bg" bg
17569 "-T" "tight"
17570 "-o" pngfile
17571 dvifile)
17572 (call-process "dvipng" nil nil nil
17573 "-fg" fg "-bg" bg
17574 "-D" dpi
17575 ;;"-x" scale "-y" scale
17576 "-T" "tight"
17577 "-o" pngfile
17578 dvifile))
17579 (error nil))
17580 (if (not (file-exists-p pngfile))
17581 (if org-format-latex-signal-error
17582 (error "Failed to create png file from %s" texfile)
17583 (message "Failed to create png file from %s" texfile)
17584 nil)
17585 ;; Use the requested file name and clean up
17586 (copy-file pngfile tofile 'replace)
17587 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17588 (if (file-exists-p (concat texfilebase e))
17589 (delete-file (concat texfilebase e))))
17590 pngfile))))
17592 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17593 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17594 "This calls convert, which is included into imagemagick."
17595 (require 'org-latex)
17596 (let* ((tmpdir (if (featurep 'xemacs)
17597 (temp-directory)
17598 temporary-file-directory))
17599 (texfilebase (make-temp-name
17600 (expand-file-name "orgtex" tmpdir)))
17601 (texfile (concat texfilebase ".tex"))
17602 (pdffile (concat texfilebase ".pdf"))
17603 (pngfile (concat texfilebase ".png"))
17604 (fnh (if (featurep 'xemacs)
17605 (font-height (face-font 'default))
17606 (face-attribute 'default :height nil)))
17607 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17608 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17609 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17610 "black"))
17611 (bg (or (plist-get options (if buffer :background :html-background))
17612 "white")))
17613 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17614 (setq fg (org-latex-color-format fg)))
17615 (if (eq bg 'default) (setq bg (org-latex-color :background))
17616 (setq bg (org-latex-color-format
17617 (if (string= bg "Transparent")(setq bg "white")))))
17618 (with-temp-file texfile
17619 (insert (org-splice-latex-header
17620 org-format-latex-header
17621 org-export-latex-default-packages-alist
17622 org-export-latex-packages-alist t
17623 org-format-latex-header-extra))
17624 (insert "\n\\begin{document}\n"
17625 "\\definecolor{fg}{rgb}{" fg "}\n"
17626 "\\definecolor{bg}{rgb}{" bg "}\n"
17627 "\n\\pagecolor{bg}\n"
17628 "\n{\\color{fg}\n"
17629 string
17630 "\n}\n"
17631 "\n\\end{document}\n" )
17632 (require 'org-latex)
17633 (org-export-latex-fix-inputenc))
17634 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17635 (condition-case nil
17636 (progn
17637 (cd tmpdir)
17638 (setq cmds org-latex-to-pdf-process)
17639 (while cmds
17640 (setq latex-frags-cmds (pop cmds))
17641 (if (listp latex-frags-cmds)
17642 (setq cmds nil)
17643 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17644 (while latex-frags-cmds
17645 (setq cmd (pop latex-frags-cmds))
17646 (while (string-match "%b" cmd)
17647 (setq cmd (replace-match
17648 (save-match-data
17649 (shell-quote-argument texfile))
17650 t t cmd)))
17651 (while (string-match "%f" cmd)
17652 (setq cmd (replace-match
17653 (save-match-data
17654 (shell-quote-argument (file-name-nondirectory texfile)))
17655 t t cmd)))
17656 (while (string-match "%o" cmd)
17657 (setq cmd (replace-match
17658 (save-match-data
17659 (shell-quote-argument (file-name-directory texfile)))
17660 t t cmd)))
17661 (setq cmd (split-string cmd))
17662 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17663 (error nil))
17664 (cd dir))
17665 (if (not (file-exists-p pdffile))
17666 (progn (message "Failed to create pdf file from %s" texfile) nil)
17667 (condition-case nil
17668 (if (featurep 'xemacs)
17669 (call-process "convert" nil nil nil
17670 "-density" "96"
17671 "-trim"
17672 "-antialias"
17673 pdffile
17674 "-quality" "100"
17675 ;; "-sharpen" "0x1.0"
17676 pngfile)
17677 (call-process "convert" nil nil nil
17678 "-density" dpi
17679 "-trim"
17680 "-antialias"
17681 pdffile
17682 "-quality" "100"
17683 ; "-sharpen" "0x1.0"
17684 pngfile))
17685 (error nil))
17686 (if (not (file-exists-p pngfile))
17687 (if org-format-latex-signal-error
17688 (error "Failed to create png file from %s" texfile)
17689 (message "Failed to create png file from %s" texfile)
17690 nil)
17691 ;; Use the requested file name and clean up
17692 (copy-file pngfile tofile 'replace)
17693 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17694 (if (file-exists-p (concat texfilebase e))
17695 (delete-file (concat texfilebase e))))
17696 pngfile))))
17698 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17699 "Fill a LaTeX header template TPL.
17700 In the template, the following place holders will be recognized:
17702 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17703 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17704 [PACKAGES] \\usepackage statements for PKG
17705 [NO-PACKAGES] do not include PKG
17706 [EXTRA] the string EXTRA
17707 [NO-EXTRA] do not include EXTRA
17709 For backward compatibility, if both the positive and the negative place
17710 holder is missing, the positive one (without the \"NO-\") will be
17711 assumed to be present at the end of the template.
17712 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17713 EXTRA is a string.
17714 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17715 (let (rpl (end ""))
17716 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17717 (setq rpl (if (or (match-end 1) (not def-pkg))
17718 "" (org-latex-packages-to-string def-pkg snippets-p t))
17719 tpl (replace-match rpl t t tpl))
17720 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17722 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17723 (setq rpl (if (or (match-end 1) (not pkg))
17724 "" (org-latex-packages-to-string pkg snippets-p t))
17725 tpl (replace-match rpl t t tpl))
17726 (if pkg (setq end
17727 (concat end "\n"
17728 (org-latex-packages-to-string pkg snippets-p)))))
17730 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17731 (setq rpl (if (or (match-end 1) (not extra))
17732 "" (concat extra "\n"))
17733 tpl (replace-match rpl t t tpl))
17734 (if (and extra (string-match "\\S-" extra))
17735 (setq end (concat end "\n" extra))))
17737 (if (string-match "\\S-" end)
17738 (concat tpl "\n" end)
17739 tpl)))
17741 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17742 "Turn an alist of packages into a string with the \\usepackage macros."
17743 (setq pkg (mapconcat (lambda(p)
17744 (cond
17745 ((stringp p) p)
17746 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17747 (format "%% Package %s omitted" (cadr p)))
17748 ((equal "" (car p))
17749 (format "\\usepackage{%s}" (cadr p)))
17751 (format "\\usepackage[%s]{%s}"
17752 (car p) (cadr p)))))
17754 "\n"))
17755 (if newline (concat pkg "\n") pkg))
17757 (defun org-dvipng-color (attr)
17758 "Return a RGB color specification for dvipng."
17759 (apply 'format "rgb %s %s %s"
17760 (mapcar 'org-normalize-color
17761 (if (featurep 'xemacs)
17762 (color-rgb-components
17763 (face-property 'default
17764 (cond ((eq attr :foreground) 'foreground)
17765 ((eq attr :background) 'background))))
17766 (color-values (face-attribute 'default attr nil))))))
17768 (defun org-latex-color (attr)
17769 "Return a RGB color for the LaTeX color package."
17770 (apply 'format "%s,%s,%s"
17771 (mapcar 'org-normalize-color
17772 (if (featurep 'xemacs)
17773 (color-rgb-components
17774 (face-property 'default
17775 (cond ((eq attr :foreground) 'foreground)
17776 ((eq attr :background) 'background))))
17777 (color-values (face-attribute 'default attr nil))))))
17779 (defun org-latex-color-format (color-name)
17780 "Convert COLOR-NAME to a RGB color value."
17781 (apply 'format "%s,%s,%s"
17782 (mapcar 'org-normalize-color
17783 (color-values color-name))))
17785 (defun org-normalize-color (value)
17786 "Return string to be used as color value for an RGB component."
17787 (format "%g" (/ value 65535.0)))
17789 ;; Image display
17792 (defvar org-inline-image-overlays nil)
17793 (make-variable-buffer-local 'org-inline-image-overlays)
17795 (defun org-toggle-inline-images (&optional include-linked)
17796 "Toggle the display of inline images.
17797 INCLUDE-LINKED is passed to `org-display-inline-images'."
17798 (interactive "P")
17799 (if org-inline-image-overlays
17800 (progn
17801 (org-remove-inline-images)
17802 (message "Inline image display turned off"))
17803 (org-display-inline-images include-linked)
17804 (if org-inline-image-overlays
17805 (message "%d images displayed inline"
17806 (length org-inline-image-overlays))
17807 (message "No images to display inline"))))
17809 (defun org-redisplay-inline-images ()
17810 "Refresh the display of inline images."
17811 (interactive)
17812 (if (not org-inline-image-overlays)
17813 (org-toggle-inline-images)
17814 (org-toggle-inline-images)
17815 (org-toggle-inline-images)))
17817 (defun org-display-inline-images (&optional include-linked refresh beg end)
17818 "Display inline images.
17819 Normally only links without a description part are inlined, because this
17820 is how it will work for export. When INCLUDE-LINKED is set, also links
17821 with a description part will be inlined. This can be nice for a quick
17822 look at those images, but it does not reflect what exported files will look
17823 like.
17824 When REFRESH is set, refresh existing images between BEG and END.
17825 This will create new image displays only if necessary.
17826 BEG and END default to the buffer boundaries."
17827 (interactive "P")
17828 (unless refresh
17829 (org-remove-inline-images)
17830 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17831 (save-excursion
17832 (save-restriction
17833 (widen)
17834 (setq beg (or beg (point-min)) end (or end (point-max)))
17835 (goto-char beg)
17836 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17837 (substring (org-image-file-name-regexp) 0 -2)
17838 "\\)\\]" (if include-linked "" "\\]")))
17839 old file ov img)
17840 (while (re-search-forward re end t)
17841 (setq old (get-char-property-and-overlay (match-beginning 1)
17842 'org-image-overlay))
17843 (setq file (expand-file-name
17844 (concat (or (match-string 3) "") (match-string 4))))
17845 (when (file-exists-p file)
17846 (if (and (car-safe old) refresh)
17847 (image-refresh (overlay-get (cdr old) 'display))
17848 (setq img (save-match-data (create-image file)))
17849 (when img
17850 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17851 (overlay-put ov 'display img)
17852 (overlay-put ov 'face 'default)
17853 (overlay-put ov 'org-image-overlay t)
17854 (overlay-put ov 'modification-hooks
17855 (list 'org-display-inline-remove-overlay))
17856 (push ov org-inline-image-overlays)))))))))
17858 (define-obsolete-function-alias
17859 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17861 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17862 "Remove inline-display overlay if a corresponding region is modified."
17863 (let ((inhibit-modification-hooks t))
17864 (when (and ov after)
17865 (delete ov org-inline-image-overlays)
17866 (delete-overlay ov))))
17868 (defun org-remove-inline-images ()
17869 "Remove inline display of images."
17870 (interactive)
17871 (mapc 'delete-overlay org-inline-image-overlays)
17872 (setq org-inline-image-overlays nil))
17874 ;;;; Key bindings
17876 ;; Outline functions from `outline-mode-prefix-map'
17877 ;; that can be remapped in Org:
17878 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17879 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17880 (define-key org-mode-map [remap outline-forward-same-level]
17881 'org-forward-heading-same-level)
17882 (define-key org-mode-map [remap outline-backward-same-level]
17883 'org-backward-heading-same-level)
17884 (define-key org-mode-map [remap show-branches]
17885 'org-kill-note-or-show-branches)
17886 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17887 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17888 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17890 ;; Outline functions from `outline-mode-prefix-map' that can not
17891 ;; be remapped in Org:
17893 ;; - the column "key binding" shows whether the Outline function is still
17894 ;; available in Org mode on the same key that it has been bound to in
17895 ;; Outline mode:
17896 ;; - "overridden": key used for a different functionality in Org mode
17897 ;; - else: key still bound to the same Outline function in Org mode
17899 ;; | Outline function | key binding | Org replacement |
17900 ;; |------------------------------------+-------------+-----------------------|
17901 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17902 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17903 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17904 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17905 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17906 ;; | `show-entry' | overridden | no replacement |
17907 ;; | `show-children' | `C-c C-i' | visibility cycling |
17908 ;; | `show-branches' | `C-c C-k' | still same function |
17909 ;; | `show-subtree' | overridden | visibility cycling |
17910 ;; | `show-all' | overridden | no replacement |
17911 ;; | `hide-subtree' | overridden | visibility cycling |
17912 ;; | `hide-body' | overridden | no replacement |
17913 ;; | `hide-entry' | overridden | visibility cycling |
17914 ;; | `hide-leaves' | overridden | no replacement |
17915 ;; | `hide-sublevels' | overridden | no replacement |
17916 ;; | `hide-other' | overridden | no replacement |
17918 ;; Make `C-c C-x' a prefix key
17919 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17921 ;; TAB key with modifiers
17922 (org-defkey org-mode-map "\C-i" 'org-cycle)
17923 (org-defkey org-mode-map [(tab)] 'org-cycle)
17924 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17925 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17926 ;; The following line is necessary under Suse GNU/Linux
17927 (unless (featurep 'xemacs)
17928 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17929 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17930 (define-key org-mode-map [backtab] 'org-shifttab)
17932 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17933 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17934 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17936 ;; Cursor keys with modifiers
17937 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17938 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17939 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17940 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17942 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17943 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17944 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17945 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17947 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17948 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17949 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17950 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17952 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17953 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17954 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17955 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17957 ;; Babel keys
17958 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17959 (mapc (lambda (pair)
17960 (define-key org-babel-map (car pair) (cdr pair)))
17961 org-babel-key-bindings)
17963 ;;; Extra keys for tty access.
17964 ;; We only set them when really needed because otherwise the
17965 ;; menus don't show the simple keys
17967 (when (or org-use-extra-keys
17968 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17969 (not window-system))
17970 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17971 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17972 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17973 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17974 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17975 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17976 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17977 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17978 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17979 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17980 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17981 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17982 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17983 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17984 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17985 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17986 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17987 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17988 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17989 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17990 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17991 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17992 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17993 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17994 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17995 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17996 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17997 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17999 ;; All the other keys
18001 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18002 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18003 (if (boundp 'narrow-map)
18004 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18005 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18006 (if (boundp 'narrow-map)
18007 (org-defkey narrow-map "b" 'org-narrow-to-block)
18008 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18009 (if (boundp 'narrow-map)
18010 (org-defkey narrow-map "e" 'org-narrow-to-element)
18011 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18012 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18013 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18014 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18015 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18016 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18017 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18018 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18019 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18020 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18021 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18022 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18023 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18024 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18025 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18026 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18027 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18028 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18029 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18030 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18031 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18032 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18033 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18034 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18035 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18036 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18037 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18038 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18039 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18040 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18041 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18042 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18043 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18044 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18045 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18046 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18047 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18048 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18049 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18050 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18051 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18052 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18053 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18054 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18055 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18056 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18057 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18058 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18059 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18060 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18061 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18062 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18063 (org-defkey org-mode-map "\C-c^" 'org-sort)
18064 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18065 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18066 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18067 (org-defkey org-mode-map "\C-m" 'org-return)
18068 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18069 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18070 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18071 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18072 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18073 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18074 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18075 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18076 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18077 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18078 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18079 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18080 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18081 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18082 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18083 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18084 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18085 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18086 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18087 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18088 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18089 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18090 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18092 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18093 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18094 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18096 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18097 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18098 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18099 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18100 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18101 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18102 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18103 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18104 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18105 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18106 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18107 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18108 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18109 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18110 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18111 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18112 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18113 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18114 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18115 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18116 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18117 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18119 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18120 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18121 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18122 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18123 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18125 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18127 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18129 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18130 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18132 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18135 (when (featurep 'xemacs)
18136 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18139 (defconst org-speed-commands-default
18141 ("Outline Navigation")
18142 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18143 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18144 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18145 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18146 ("u" . (org-speed-move-safe 'outline-up-heading))
18147 ("j" . org-goto)
18148 ("g" . (org-refile t))
18149 ("Outline Visibility")
18150 ("c" . org-cycle)
18151 ("C" . org-shifttab)
18152 (" " . org-display-outline-path)
18153 (":" . org-columns)
18154 ("Outline Structure Editing")
18155 ("U" . org-shiftmetaup)
18156 ("D" . org-shiftmetadown)
18157 ("r" . org-metaright)
18158 ("l" . org-metaleft)
18159 ("R" . org-shiftmetaright)
18160 ("L" . org-shiftmetaleft)
18161 ("i" . (progn (forward-char 1) (call-interactively
18162 'org-insert-heading-respect-content)))
18163 ("^" . org-sort)
18164 ("w" . org-refile)
18165 ("a" . org-archive-subtree-default-with-confirmation)
18166 ("." . org-mark-subtree)
18167 ("#" . org-toggle-comment)
18168 ("Clock Commands")
18169 ("I" . org-clock-in)
18170 ("O" . org-clock-out)
18171 ("Meta Data Editing")
18172 ("t" . org-todo)
18173 ("," . (org-priority))
18174 ("0" . (org-priority ?\ ))
18175 ("1" . (org-priority ?A))
18176 ("2" . (org-priority ?B))
18177 ("3" . (org-priority ?C))
18178 (";" . org-set-tags-command)
18179 ("e" . org-set-effort)
18180 ("E" . org-inc-effort)
18181 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18182 (org-entry-put (point) "APPT_WARNTIME" m)))
18183 ("Agenda Views etc")
18184 ("v" . org-agenda)
18185 ("/" . org-sparse-tree)
18186 ("Misc")
18187 ("o" . org-open-at-point)
18188 ("?" . org-speed-command-help)
18189 ("<" . (org-agenda-set-restriction-lock 'subtree))
18190 (">" . (org-agenda-remove-restriction-lock))
18192 "The default speed commands.")
18194 (defun org-print-speed-command (e)
18195 (if (> (length (car e)) 1)
18196 (progn
18197 (princ "\n")
18198 (princ (car e))
18199 (princ "\n")
18200 (princ (make-string (length (car e)) ?-))
18201 (princ "\n"))
18202 (princ (car e))
18203 (princ " ")
18204 (if (symbolp (cdr e))
18205 (princ (symbol-name (cdr e)))
18206 (prin1 (cdr e)))
18207 (princ "\n")))
18209 (defun org-speed-command-help ()
18210 "Show the available speed commands."
18211 (interactive)
18212 (if (not org-use-speed-commands)
18213 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18214 (with-output-to-temp-buffer "*Help*"
18215 (princ "User-defined Speed commands\n===========================\n")
18216 (mapc 'org-print-speed-command org-speed-commands-user)
18217 (princ "\n")
18218 (princ "Built-in Speed commands\n=======================\n")
18219 (mapc 'org-print-speed-command org-speed-commands-default))
18220 (with-current-buffer "*Help*"
18221 (setq truncate-lines t))))
18223 (defun org-speed-move-safe (cmd)
18224 "Execute CMD, but make sure that the cursor always ends up in a headline.
18225 If not, return to the original position and throw an error."
18226 (interactive)
18227 (let ((pos (point)))
18228 (call-interactively cmd)
18229 (unless (and (bolp) (org-at-heading-p))
18230 (goto-char pos)
18231 (error "Boundary reached while executing %s" cmd))))
18233 (defvar org-self-insert-command-undo-counter 0)
18235 (defvar org-table-auto-blank-field) ; defined in org-table.el
18236 (defvar org-speed-command nil)
18238 (define-obsolete-function-alias
18239 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18241 (defun org-speed-command-activate (keys)
18242 "Hook for activating single-letter speed commands.
18243 `org-speed-commands-default' specifies a minimal command set.
18244 Use `org-speed-commands-user' for further customization."
18245 (when (or (and (bolp) (looking-at org-outline-regexp))
18246 (and (functionp org-use-speed-commands)
18247 (funcall org-use-speed-commands)))
18248 (cdr (assoc keys (append org-speed-commands-user
18249 org-speed-commands-default)))))
18251 (define-obsolete-function-alias
18252 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18254 (defun org-babel-speed-command-activate (keys)
18255 "Hook for activating single-letter code block commands."
18256 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18257 (cdr (assoc keys org-babel-key-bindings))))
18259 (defcustom org-speed-command-hook
18260 '(org-speed-command-default-hook org-babel-speed-command-hook)
18261 "Hook for activating speed commands at strategic locations.
18262 Hook functions are called in sequence until a valid handler is
18263 found.
18265 Each hook takes a single argument, a user-pressed command key
18266 which is also a `self-insert-command' from the global map.
18268 Within the hook, examine the cursor position and the command key
18269 and return nil or a valid handler as appropriate. Handler could
18270 be one of an interactive command, a function, or a form.
18272 Set `org-use-speed-commands' to non-nil value to enable this
18273 hook. The default setting is `org-speed-command-activate'."
18274 :group 'org-structure
18275 :version "24.1"
18276 :type 'hook)
18278 (defun org-self-insert-command (N)
18279 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18280 If the cursor is in a table looking at whitespace, the whitespace is
18281 overwritten, and the table is not marked as requiring realignment."
18282 (interactive "p")
18283 (org-check-before-invisible-edit 'insert)
18284 (cond
18285 ((and org-use-speed-commands
18286 (setq org-speed-command
18287 (run-hook-with-args-until-success
18288 'org-speed-command-hook (this-command-keys))))
18289 (cond
18290 ((commandp org-speed-command)
18291 (setq this-command org-speed-command)
18292 (call-interactively org-speed-command))
18293 ((functionp org-speed-command)
18294 (funcall org-speed-command))
18295 ((and org-speed-command (listp org-speed-command))
18296 (eval org-speed-command))
18297 (t (let (org-use-speed-commands)
18298 (call-interactively 'org-self-insert-command)))))
18299 ((and
18300 (org-table-p)
18301 (progn
18302 ;; check if we blank the field, and if that triggers align
18303 (and (featurep 'org-table) org-table-auto-blank-field
18304 (member last-command
18305 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18306 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18307 ;; got extra space, this field does not determine column width
18308 (let (org-table-may-need-update) (org-table-blank-field))
18309 ;; no extra space, this field may determine column width
18310 (org-table-blank-field)))
18312 (eq N 1)
18313 (looking-at "[^|\n]* |"))
18314 (let (org-table-may-need-update)
18315 (goto-char (1- (match-end 0)))
18316 (backward-delete-char 1)
18317 (goto-char (match-beginning 0))
18318 (self-insert-command N)))
18320 (setq org-table-may-need-update t)
18321 (self-insert-command N)
18322 (org-fix-tags-on-the-fly)
18323 (if org-self-insert-cluster-for-undo
18324 (if (not (eq last-command 'org-self-insert-command))
18325 (setq org-self-insert-command-undo-counter 1)
18326 (if (>= org-self-insert-command-undo-counter 20)
18327 (setq org-self-insert-command-undo-counter 1)
18328 (and (> org-self-insert-command-undo-counter 0)
18329 buffer-undo-list (listp buffer-undo-list)
18330 (not (cadr buffer-undo-list)) ; remove nil entry
18331 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18332 (setq org-self-insert-command-undo-counter
18333 (1+ org-self-insert-command-undo-counter))))))))
18335 (defun org-check-before-invisible-edit (kind)
18336 "Check is editing if kind KIND would be dangerous with invisible text around.
18337 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18338 ;; First, try to get out of here as quickly as possible, to reduce overhead
18339 (if (and org-catch-invisible-edits
18340 (or (not (boundp 'visible-mode)) (not visible-mode))
18341 (or (get-char-property (point) 'invisible)
18342 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18343 ;; OK, we need to take a closer look
18344 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18345 (invisible-before-point (if (bobp) nil (get-char-property
18346 (1- (point)) 'invisible)))
18347 (border-and-ok-direction
18349 ;; Check if we are acting predictably before invisible text
18350 (and invisible-at-point (not invisible-before-point)
18351 (memq kind '(insert delete-backward)))
18352 ;; Check if we are acting predictably after invisible text
18353 ;; This works not well, and I have turned it off. It seems
18354 ;; better to always show and stop after invisible text.
18355 ;; (and (not invisible-at-point) invisible-before-point
18356 ;; (memq kind '(insert delete)))
18358 (when (or (memq invisible-at-point '(outline org-hide-block t))
18359 (memq invisible-before-point '(outline org-hide-block t)))
18360 (if (eq org-catch-invisible-edits 'error)
18361 (error "Editing in invisible areas is prohibited - make visible first"))
18362 (if (and org-custom-properties-overlays
18363 (y-or-n-p "Display invisible properties in this buffer? "))
18364 (org-toggle-custom-properties-visibility)
18365 ;; Make the area visible
18366 (save-excursion
18367 (if invisible-before-point
18368 (goto-char (previous-single-char-property-change
18369 (point) 'invisible)))
18370 (org-cycle))
18371 (cond
18372 ((eq org-catch-invisible-edits 'show)
18373 ;; That's it, we do the edit after showing
18374 (message
18375 "Unfolding invisible region around point before editing")
18376 (sit-for 1))
18377 ((and (eq org-catch-invisible-edits 'smart)
18378 border-and-ok-direction)
18379 (message "Unfolding invisible region around point before editing"))
18381 ;; Don't do the edit, make the user repeat it in full visibility
18382 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18384 (defun org-fix-tags-on-the-fly ()
18385 (when (and (equal (char-after (point-at-bol)) ?*)
18386 (org-at-heading-p))
18387 (org-align-tags-here org-tags-column)))
18389 (defun org-delete-backward-char (N)
18390 "Like `delete-backward-char', insert whitespace at field end in tables.
18391 When deleting backwards, in tables this function will insert whitespace in
18392 front of the next \"|\" separator, to keep the table aligned. The table will
18393 still be marked for re-alignment if the field did fill the entire column,
18394 because, in this case the deletion might narrow the column."
18395 (interactive "p")
18396 (org-check-before-invisible-edit 'delete-backward)
18397 (if (and (org-table-p)
18398 (eq N 1)
18399 (string-match "|" (buffer-substring (point-at-bol) (point)))
18400 (looking-at ".*?|"))
18401 (let ((pos (point))
18402 (noalign (looking-at "[^|\n\r]* |"))
18403 (c org-table-may-need-update))
18404 (backward-delete-char N)
18405 (if (not overwrite-mode)
18406 (progn
18407 (skip-chars-forward "^|")
18408 (insert " ")
18409 (goto-char (1- pos))))
18410 ;; noalign: if there were two spaces at the end, this field
18411 ;; does not determine the width of the column.
18412 (if noalign (setq org-table-may-need-update c)))
18413 (backward-delete-char N)
18414 (org-fix-tags-on-the-fly)))
18416 (defun org-delete-char (N)
18417 "Like `delete-char', but insert whitespace at field end in tables.
18418 When deleting characters, in tables this function will insert whitespace in
18419 front of the next \"|\" separator, to keep the table aligned. The table will
18420 still be marked for re-alignment if the field did fill the entire column,
18421 because, in this case the deletion might narrow the column."
18422 (interactive "p")
18423 (org-check-before-invisible-edit 'delete)
18424 (if (and (org-table-p)
18425 (not (bolp))
18426 (not (= (char-after) ?|))
18427 (eq N 1))
18428 (if (looking-at ".*?|")
18429 (let ((pos (point))
18430 (noalign (looking-at "[^|\n\r]* |"))
18431 (c org-table-may-need-update))
18432 (replace-match (concat
18433 (substring (match-string 0) 1 -1)
18434 " |"))
18435 (goto-char pos)
18436 ;; noalign: if there were two spaces at the end, this field
18437 ;; does not determine the width of the column.
18438 (if noalign (setq org-table-may-need-update c)))
18439 (delete-char N))
18440 (delete-char N)
18441 (org-fix-tags-on-the-fly)))
18443 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18444 (put 'org-self-insert-command 'delete-selection t)
18445 (put 'orgtbl-self-insert-command 'delete-selection t)
18446 (put 'org-delete-char 'delete-selection 'supersede)
18447 (put 'org-delete-backward-char 'delete-selection 'supersede)
18448 (put 'org-yank 'delete-selection 'yank)
18450 ;; Make `flyspell-mode' delay after some commands
18451 (put 'org-self-insert-command 'flyspell-delayed t)
18452 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18453 (put 'org-delete-char 'flyspell-delayed t)
18454 (put 'org-delete-backward-char 'flyspell-delayed t)
18456 ;; Make pabbrev-mode expand after org-mode commands
18457 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18458 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18460 ;; How to do this: Measure non-white length of current string
18461 ;; If equal to column width, we should realign.
18463 (defun org-remap (map &rest commands)
18464 "In MAP, remap the functions given in COMMANDS.
18465 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18466 (let (new old)
18467 (while commands
18468 (setq old (pop commands) new (pop commands))
18469 (if (fboundp 'command-remapping)
18470 (org-defkey map (vector 'remap old) new)
18471 (substitute-key-definition old new map global-map)))))
18473 (when (eq org-enable-table-editor 'optimized)
18474 ;; If the user wants maximum table support, we need to hijack
18475 ;; some standard editing functions
18476 (org-remap org-mode-map
18477 'self-insert-command 'org-self-insert-command
18478 'delete-char 'org-delete-char
18479 'delete-backward-char 'org-delete-backward-char)
18480 (org-defkey org-mode-map "|" 'org-force-self-insert))
18482 (defvar org-ctrl-c-ctrl-c-hook nil
18483 "Hook for functions attaching themselves to `C-c C-c'.
18485 This can be used to add additional functionality to the C-c C-c
18486 key which executes context-dependent commands. This hook is run
18487 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18488 run after the last test.
18490 Each function will be called with no arguments. The function
18491 must check if the context is appropriate for it to act. If yes,
18492 it should do its thing and then return a non-nil value. If the
18493 context is wrong, just do nothing and return nil.")
18495 (defvar org-ctrl-c-ctrl-c-final-hook nil
18496 "Hook for functions attaching themselves to `C-c C-c'.
18498 This can be used to add additional functionality to the C-c C-c
18499 key which executes context-dependent commands. This hook is run
18500 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18501 before the first test.
18503 Each function will be called with no arguments. The function
18504 must check if the context is appropriate for it to act. If yes,
18505 it should do its thing and then return a non-nil value. If the
18506 context is wrong, just do nothing and return nil.")
18508 (defvar org-tab-first-hook nil
18509 "Hook for functions to attach themselves to TAB.
18510 See `org-ctrl-c-ctrl-c-hook' for more information.
18511 This hook runs as the first action when TAB is pressed, even before
18512 `org-cycle' messes around with the `outline-regexp' to cater for
18513 inline tasks and plain list item folding.
18514 If any function in this hook returns t, any other actions that
18515 would have been caused by TAB (such as table field motion or visibility
18516 cycling) will not occur.")
18518 (defvar org-tab-after-check-for-table-hook nil
18519 "Hook for functions to attach themselves to TAB.
18520 See `org-ctrl-c-ctrl-c-hook' for more information.
18521 This hook runs after it has been established that the cursor is not in a
18522 table, but before checking if the cursor is in a headline or if global cycling
18523 should be done.
18524 If any function in this hook returns t, not other actions like visibility
18525 cycling will be done.")
18527 (defvar org-tab-after-check-for-cycling-hook nil
18528 "Hook for functions to attach themselves to TAB.
18529 See `org-ctrl-c-ctrl-c-hook' for more information.
18530 This hook runs after it has been established that not table field motion and
18531 not visibility should be done because of current context. This is probably
18532 the place where a package like yasnippets can hook in.")
18534 (defvar org-tab-before-tab-emulation-hook nil
18535 "Hook for functions to attach themselves to TAB.
18536 See `org-ctrl-c-ctrl-c-hook' for more information.
18537 This hook runs after every other options for TAB have been exhausted, but
18538 before indentation and \t insertion takes place.")
18540 (defvar org-metaleft-hook nil
18541 "Hook for functions attaching themselves to `M-left'.
18542 See `org-ctrl-c-ctrl-c-hook' for more information.")
18543 (defvar org-metaright-hook nil
18544 "Hook for functions attaching themselves to `M-right'.
18545 See `org-ctrl-c-ctrl-c-hook' for more information.")
18546 (defvar org-metaup-hook nil
18547 "Hook for functions attaching themselves to `M-up'.
18548 See `org-ctrl-c-ctrl-c-hook' for more information.")
18549 (defvar org-metadown-hook nil
18550 "Hook for functions attaching themselves to `M-down'.
18551 See `org-ctrl-c-ctrl-c-hook' for more information.")
18552 (defvar org-shiftmetaleft-hook nil
18553 "Hook for functions attaching themselves to `M-S-left'.
18554 See `org-ctrl-c-ctrl-c-hook' for more information.")
18555 (defvar org-shiftmetaright-hook nil
18556 "Hook for functions attaching themselves to `M-S-right'.
18557 See `org-ctrl-c-ctrl-c-hook' for more information.")
18558 (defvar org-shiftmetaup-hook nil
18559 "Hook for functions attaching themselves to `M-S-up'.
18560 See `org-ctrl-c-ctrl-c-hook' for more information.")
18561 (defvar org-shiftmetadown-hook nil
18562 "Hook for functions attaching themselves to `M-S-down'.
18563 See `org-ctrl-c-ctrl-c-hook' for more information.")
18564 (defvar org-metareturn-hook nil
18565 "Hook for functions attaching themselves to `M-RET'.
18566 See `org-ctrl-c-ctrl-c-hook' for more information.")
18567 (defvar org-shiftup-hook nil
18568 "Hook for functions attaching themselves to `S-up'.
18569 See `org-ctrl-c-ctrl-c-hook' for more information.")
18570 (defvar org-shiftup-final-hook nil
18571 "Hook for functions attaching themselves to `S-up'.
18572 This one runs after all other options except shift-select have been excluded.
18573 See `org-ctrl-c-ctrl-c-hook' for more information.")
18574 (defvar org-shiftdown-hook nil
18575 "Hook for functions attaching themselves to `S-down'.
18576 See `org-ctrl-c-ctrl-c-hook' for more information.")
18577 (defvar org-shiftdown-final-hook nil
18578 "Hook for functions attaching themselves to `S-down'.
18579 This one runs after all other options except shift-select have been excluded.
18580 See `org-ctrl-c-ctrl-c-hook' for more information.")
18581 (defvar org-shiftleft-hook nil
18582 "Hook for functions attaching themselves to `S-left'.
18583 See `org-ctrl-c-ctrl-c-hook' for more information.")
18584 (defvar org-shiftleft-final-hook nil
18585 "Hook for functions attaching themselves to `S-left'.
18586 This one runs after all other options except shift-select have been excluded.
18587 See `org-ctrl-c-ctrl-c-hook' for more information.")
18588 (defvar org-shiftright-hook nil
18589 "Hook for functions attaching themselves to `S-right'.
18590 See `org-ctrl-c-ctrl-c-hook' for more information.")
18591 (defvar org-shiftright-final-hook nil
18592 "Hook for functions attaching themselves to `S-right'.
18593 This one runs after all other options except shift-select have been excluded.
18594 See `org-ctrl-c-ctrl-c-hook' for more information.")
18596 (defun org-modifier-cursor-error ()
18597 "Throw an error, a modified cursor command was applied in wrong context."
18598 (error "This command is active in special context like tables, headlines or items"))
18600 (defun org-shiftselect-error ()
18601 "Throw an error because Shift-Cursor command was applied in wrong context."
18602 (if (and (boundp 'shift-select-mode) shift-select-mode)
18603 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18604 (error "This command works only in special context like headlines or timestamps")))
18606 (defun org-call-for-shift-select (cmd)
18607 (let ((this-command-keys-shift-translated t))
18608 (call-interactively cmd)))
18610 (defun org-shifttab (&optional arg)
18611 "Global visibility cycling or move to previous table field.
18612 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18613 on context.
18614 See the individual commands for more information."
18615 (interactive "P")
18616 (cond
18617 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18618 ((integerp arg)
18619 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18620 (message "Content view to level: %d" arg)
18621 (org-content (prefix-numeric-value arg2))
18622 (setq org-cycle-global-status 'overview)))
18623 (t (call-interactively 'org-global-cycle))))
18625 (defun org-shiftmetaleft ()
18626 "Promote subtree or delete table column.
18627 Calls `org-promote-subtree', `org-outdent-item-tree', or
18628 `org-table-delete-column', depending on context. See the
18629 individual commands for more information."
18630 (interactive)
18631 (cond
18632 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18633 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18634 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18635 ((if (not (org-region-active-p)) (org-at-item-p)
18636 (save-excursion (goto-char (region-beginning))
18637 (org-at-item-p)))
18638 (call-interactively 'org-outdent-item-tree))
18639 (t (org-modifier-cursor-error))))
18641 (defun org-shiftmetaright ()
18642 "Demote subtree or insert table column.
18643 Calls `org-demote-subtree', `org-indent-item-tree', or
18644 `org-table-insert-column', depending on context. See the
18645 individual commands for more information."
18646 (interactive)
18647 (cond
18648 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18649 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18650 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18651 ((if (not (org-region-active-p)) (org-at-item-p)
18652 (save-excursion (goto-char (region-beginning))
18653 (org-at-item-p)))
18654 (call-interactively 'org-indent-item-tree))
18655 (t (org-modifier-cursor-error))))
18657 (defun org-shiftmetaup (&optional arg)
18658 "Move subtree up or kill table row.
18659 Calls `org-move-subtree-up' or `org-table-kill-row' or
18660 `org-move-item-up' or `org-timestamp-up', depending on context.
18661 See the individual commands for more information."
18662 (interactive "P")
18663 (cond
18664 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18665 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18666 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18667 ((org-at-item-p) (call-interactively 'org-move-item-up))
18668 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18669 (call-interactively 'org-timestamp-up)))
18670 (t (org-modifier-cursor-error))))
18672 (defun org-shiftmetadown (&optional arg)
18673 "Move subtree down or insert table row.
18674 Calls `org-move-subtree-down' or `org-table-insert-row' or
18675 `org-move-item-down' or `org-timestamp-up', depending on context.
18676 See the individual commands for more information."
18677 (interactive "P")
18678 (cond
18679 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18680 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18681 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18682 ((org-at-item-p) (call-interactively 'org-move-item-down))
18683 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18684 (call-interactively 'org-timestamp-down)))
18685 (t (org-modifier-cursor-error))))
18687 (defsubst org-hidden-tree-error ()
18688 (error
18689 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18691 (defun org-metaleft (&optional arg)
18692 "Promote heading or move table column to left.
18693 Calls `org-do-promote' or `org-table-move-column', depending on context.
18694 With no specific context, calls the Emacs default `backward-word'.
18695 See the individual commands for more information."
18696 (interactive "P")
18697 (cond
18698 ((run-hook-with-args-until-success 'org-metaleft-hook))
18699 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18700 ((org-with-limited-levels
18701 (or (org-at-heading-p)
18702 (and (org-region-active-p)
18703 (save-excursion
18704 (goto-char (region-beginning))
18705 (org-at-heading-p)))))
18706 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18707 (call-interactively 'org-do-promote))
18708 ;; At an inline task.
18709 ((org-at-heading-p)
18710 (call-interactively 'org-inlinetask-promote))
18711 ((or (org-at-item-p)
18712 (and (org-region-active-p)
18713 (save-excursion
18714 (goto-char (region-beginning))
18715 (org-at-item-p))))
18716 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18717 (call-interactively 'org-outdent-item))
18718 (t (call-interactively 'backward-word))))
18720 (defun org-metaright (&optional arg)
18721 "Demote a subtree, a list item or move table column to right.
18722 In front of a drawer or a block keyword, indent it correctly.
18723 With no specific context, calls the Emacs default `forward-word'.
18724 See the individual commands for more information."
18725 (interactive "P")
18726 (cond
18727 ((run-hook-with-args-until-success 'org-metaright-hook))
18728 ((org-at-table-p) (call-interactively 'org-table-move-column))
18729 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18730 ((org-at-block-p) (call-interactively 'org-indent-block))
18731 ((org-with-limited-levels
18732 (or (org-at-heading-p)
18733 (and (org-region-active-p)
18734 (save-excursion
18735 (goto-char (region-beginning))
18736 (org-at-heading-p)))))
18737 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18738 (call-interactively 'org-do-demote))
18739 ;; At an inline task.
18740 ((org-at-heading-p)
18741 (call-interactively 'org-inlinetask-demote))
18742 ((or (org-at-item-p)
18743 (and (org-region-active-p)
18744 (save-excursion
18745 (goto-char (region-beginning))
18746 (org-at-item-p))))
18747 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18748 (call-interactively 'org-indent-item))
18749 (t (call-interactively 'forward-word))))
18751 (defun org-check-for-hidden (what)
18752 "Check if there are hidden headlines/items in the current visual line.
18753 WHAT can be either `headlines' or `items'. If the current line is
18754 an outline or item heading and it has a folded subtree below it,
18755 this function returns t, nil otherwise."
18756 (let ((re (cond
18757 ((eq what 'headlines) org-outline-regexp-bol)
18758 ((eq what 'items) (org-item-beginning-re))
18759 (t (error "This should not happen"))))
18760 beg end)
18761 (save-excursion
18762 (catch 'exit
18763 (unless (org-region-active-p)
18764 (setq beg (point-at-bol))
18765 (beginning-of-line 2)
18766 (while (and (not (eobp)) ;; this is like `next-line'
18767 (get-char-property (1- (point)) 'invisible))
18768 (beginning-of-line 2))
18769 (setq end (point))
18770 (goto-char beg)
18771 (goto-char (point-at-eol))
18772 (setq end (max end (point)))
18773 (while (re-search-forward re end t)
18774 (if (get-char-property (match-beginning 0) 'invisible)
18775 (throw 'exit t))))
18776 nil))))
18778 (autoload 'org-element-at-point "org-element")
18780 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18781 (declare-function org-element-type "org-element" (element))
18782 (declare-function org-element-context "org-element" ())
18783 (declare-function org-element-contents "org-element" (element))
18784 (declare-function org-element-property "org-element" (property element))
18785 (declare-function org-element-paragraph-parser "org-element" (limit))
18786 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18787 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18788 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18789 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18790 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18792 (defun org-metaup (&optional arg)
18793 "Move subtree up or move table row up.
18794 Calls `org-move-subtree-up' or `org-table-move-row' or
18795 `org-move-item-up', depending on context. See the individual commands
18796 for more information."
18797 (interactive "P")
18798 (cond
18799 ((run-hook-with-args-until-success 'org-metaup-hook))
18800 ((org-region-active-p)
18801 (let* ((a (min (region-beginning) (region-end)))
18802 (b (1- (max (region-beginning) (region-end))))
18803 (c (save-excursion (goto-char a)
18804 (move-beginning-of-line 0)))
18805 (d (save-excursion (goto-char a)
18806 (move-end-of-line 0) (point))))
18807 (transpose-regions a b c d)
18808 (goto-char c)))
18809 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18810 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18811 ((org-at-item-p) (call-interactively 'org-move-item-up))
18812 (t (org-drag-element-backward))))
18814 (defun org-metadown (&optional arg)
18815 "Move subtree down or move table row down.
18816 Calls `org-move-subtree-down' or `org-table-move-row' or
18817 `org-move-item-down', depending on context. See the individual
18818 commands for more information."
18819 (interactive "P")
18820 (cond
18821 ((run-hook-with-args-until-success 'org-metadown-hook))
18822 ((org-region-active-p)
18823 (let* ((a (min (region-beginning) (region-end)))
18824 (b (max (region-beginning) (region-end)))
18825 (c (save-excursion (goto-char b)
18826 (move-beginning-of-line 1)))
18827 (d (save-excursion (goto-char b)
18828 (move-end-of-line 1) (1+ (point)))))
18829 (transpose-regions a b c d)
18830 (goto-char d)))
18831 ((org-at-table-p) (call-interactively 'org-table-move-row))
18832 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18833 ((org-at-item-p) (call-interactively 'org-move-item-down))
18834 (t (org-drag-element-forward))))
18836 (defun org-shiftup (&optional arg)
18837 "Increase item in timestamp or increase priority of current headline.
18838 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18839 depending on context. See the individual commands for more information."
18840 (interactive "P")
18841 (cond
18842 ((run-hook-with-args-until-success 'org-shiftup-hook))
18843 ((and org-support-shift-select (org-region-active-p))
18844 (org-call-for-shift-select 'previous-line))
18845 ((org-at-timestamp-p t)
18846 (call-interactively (if org-edit-timestamp-down-means-later
18847 'org-timestamp-down 'org-timestamp-up)))
18848 ((and (not (eq org-support-shift-select 'always))
18849 org-enable-priority-commands
18850 (org-at-heading-p))
18851 (call-interactively 'org-priority-up))
18852 ((and (not org-support-shift-select) (org-at-item-p))
18853 (call-interactively 'org-previous-item))
18854 ((org-clocktable-try-shift 'up arg))
18855 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18856 (org-support-shift-select
18857 (org-call-for-shift-select 'previous-line))
18858 (t (org-shiftselect-error))))
18860 (defun org-shiftdown (&optional arg)
18861 "Decrease item in timestamp or decrease priority of current headline.
18862 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18863 depending on context. See the individual commands for more information."
18864 (interactive "P")
18865 (cond
18866 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18867 ((and org-support-shift-select (org-region-active-p))
18868 (org-call-for-shift-select 'next-line))
18869 ((org-at-timestamp-p t)
18870 (call-interactively (if org-edit-timestamp-down-means-later
18871 'org-timestamp-up 'org-timestamp-down)))
18872 ((and (not (eq org-support-shift-select 'always))
18873 org-enable-priority-commands
18874 (org-at-heading-p))
18875 (call-interactively 'org-priority-down))
18876 ((and (not org-support-shift-select) (org-at-item-p))
18877 (call-interactively 'org-next-item))
18878 ((org-clocktable-try-shift 'down arg))
18879 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18880 (org-support-shift-select
18881 (org-call-for-shift-select 'next-line))
18882 (t (org-shiftselect-error))))
18884 (defun org-shiftright (&optional arg)
18885 "Cycle the thing at point or in the current line, depending on context.
18886 Depending on context, this does one of the following:
18888 - switch a timestamp at point one day into the future
18889 - on a headline, switch to the next TODO keyword.
18890 - on an item, switch entire list to the next bullet type
18891 - on a property line, switch to the next allowed value
18892 - on a clocktable definition line, move time block into the future"
18893 (interactive "P")
18894 (cond
18895 ((run-hook-with-args-until-success 'org-shiftright-hook))
18896 ((and org-support-shift-select (org-region-active-p))
18897 (org-call-for-shift-select 'forward-char))
18898 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18899 ((and (not (eq org-support-shift-select 'always))
18900 (org-at-heading-p))
18901 (let ((org-inhibit-logging
18902 (not org-treat-S-cursor-todo-selection-as-state-change))
18903 (org-inhibit-blocking
18904 (not org-treat-S-cursor-todo-selection-as-state-change)))
18905 (org-call-with-arg 'org-todo 'right)))
18906 ((or (and org-support-shift-select
18907 (not (eq org-support-shift-select 'always))
18908 (org-at-item-bullet-p))
18909 (and (not org-support-shift-select) (org-at-item-p)))
18910 (org-call-with-arg 'org-cycle-list-bullet nil))
18911 ((and (not (eq org-support-shift-select 'always))
18912 (org-at-property-p))
18913 (call-interactively 'org-property-next-allowed-value))
18914 ((org-clocktable-try-shift 'right arg))
18915 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18916 (org-support-shift-select
18917 (org-call-for-shift-select 'forward-char))
18918 (t (org-shiftselect-error))))
18920 (defun org-shiftleft (&optional arg)
18921 "Cycle the thing at point or in the current line, depending on context.
18922 Depending on context, this does one of the following:
18924 - switch a timestamp at point one day into the past
18925 - on a headline, switch to the previous TODO keyword.
18926 - on an item, switch entire list to the previous bullet type
18927 - on a property line, switch to the previous allowed value
18928 - on a clocktable definition line, move time block into the past"
18929 (interactive "P")
18930 (cond
18931 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18932 ((and org-support-shift-select (org-region-active-p))
18933 (org-call-for-shift-select 'backward-char))
18934 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18935 ((and (not (eq org-support-shift-select 'always))
18936 (org-at-heading-p))
18937 (let ((org-inhibit-logging
18938 (not org-treat-S-cursor-todo-selection-as-state-change))
18939 (org-inhibit-blocking
18940 (not org-treat-S-cursor-todo-selection-as-state-change)))
18941 (org-call-with-arg 'org-todo 'left)))
18942 ((or (and org-support-shift-select
18943 (not (eq org-support-shift-select 'always))
18944 (org-at-item-bullet-p))
18945 (and (not org-support-shift-select) (org-at-item-p)))
18946 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18947 ((and (not (eq org-support-shift-select 'always))
18948 (org-at-property-p))
18949 (call-interactively 'org-property-previous-allowed-value))
18950 ((org-clocktable-try-shift 'left arg))
18951 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18952 (org-support-shift-select
18953 (org-call-for-shift-select 'backward-char))
18954 (t (org-shiftselect-error))))
18956 (defun org-shiftcontrolright ()
18957 "Switch to next TODO set."
18958 (interactive)
18959 (cond
18960 ((and org-support-shift-select (org-region-active-p))
18961 (org-call-for-shift-select 'forward-word))
18962 ((and (not (eq org-support-shift-select 'always))
18963 (org-at-heading-p))
18964 (org-call-with-arg 'org-todo 'nextset))
18965 (org-support-shift-select
18966 (org-call-for-shift-select 'forward-word))
18967 (t (org-shiftselect-error))))
18969 (defun org-shiftcontrolleft ()
18970 "Switch to previous TODO set."
18971 (interactive)
18972 (cond
18973 ((and org-support-shift-select (org-region-active-p))
18974 (org-call-for-shift-select 'backward-word))
18975 ((and (not (eq org-support-shift-select 'always))
18976 (org-at-heading-p))
18977 (org-call-with-arg 'org-todo 'previousset))
18978 (org-support-shift-select
18979 (org-call-for-shift-select 'backward-word))
18980 (t (org-shiftselect-error))))
18982 (defun org-shiftcontrolup ()
18983 "Change timestamps synchronously up in CLOCK log lines."
18984 (interactive)
18985 (cond ((and (not org-support-shift-select)
18986 (org-at-clock-log-p)
18987 (org-at-timestamp-p t))
18988 (org-clock-timestamps-up))
18989 (t (org-shiftselect-error))))
18991 (defun org-shiftcontroldown ()
18992 "Change timestamps synchronously down in CLOCK log lines."
18993 (interactive)
18994 (cond ((and (not org-support-shift-select)
18995 (org-at-clock-log-p)
18996 (org-at-timestamp-p t))
18997 (org-clock-timestamps-down))
18998 (t (org-shiftselect-error))))
19000 (defun org-ctrl-c-ret ()
19001 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19002 (interactive)
19003 (cond
19004 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19005 (t (call-interactively 'org-insert-heading))))
19007 (defun org-find-visible ()
19008 (let ((s (point)))
19009 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19010 (get-char-property s 'invisible)))
19012 (defun org-find-invisible ()
19013 (let ((s (point)))
19014 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19015 (not (get-char-property s 'invisible))))
19018 (defun org-copy-visible (beg end)
19019 "Copy the visible parts of the region."
19020 (interactive "r")
19021 (let (snippets s)
19022 (save-excursion
19023 (save-restriction
19024 (narrow-to-region beg end)
19025 (setq s (goto-char (point-min)))
19026 (while (not (= (point) (point-max)))
19027 (goto-char (org-find-invisible))
19028 (push (buffer-substring s (point)) snippets)
19029 (setq s (goto-char (org-find-visible))))))
19030 (kill-new (apply 'concat (nreverse snippets)))))
19032 (defun org-copy-special ()
19033 "Copy region in table or copy current subtree.
19034 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19035 See the individual commands for more information."
19036 (interactive)
19037 (call-interactively
19038 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19040 (defun org-cut-special ()
19041 "Cut region in table or cut current subtree.
19042 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19043 See the individual commands for more information."
19044 (interactive)
19045 (call-interactively
19046 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19048 (defun org-paste-special (arg)
19049 "Paste rectangular region into table, or past subtree relative to level.
19050 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19051 See the individual commands for more information."
19052 (interactive "P")
19053 (if (org-at-table-p)
19054 (org-table-paste-rectangle)
19055 (org-paste-subtree arg)))
19057 (defun org-edit-special (&optional arg)
19058 "Call a special editor for the stuff at point.
19059 When at a table, call the formula editor with `org-table-edit-formulas'.
19060 When at the first line of an src example, call `org-edit-src-code'.
19061 When in an #+include line, visit the include file. Otherwise call
19062 `ffap' to visit the file at point."
19063 (interactive)
19064 ;; possibly prep session before editing source
19065 (when arg
19066 (let* ((info (org-babel-get-src-block-info))
19067 (lang (nth 0 info))
19068 (params (nth 2 info))
19069 (session (cdr (assoc :session params))))
19070 (when (and info session) ;; we are in a source-code block with a session
19071 (funcall
19072 (intern (concat "org-babel-prep-session:" lang)) session params))))
19073 (cond ;; proceed with `org-edit-special'
19074 ((save-excursion
19075 (beginning-of-line 1)
19076 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19077 (find-file (org-trim (match-string 1))))
19078 ((org-edit-src-code))
19079 ((org-edit-fixed-width-region))
19080 ((org-at-table.el-p)
19081 (org-edit-src-code))
19082 ((or (org-at-table-p)
19083 (save-excursion
19084 (beginning-of-line 1)
19085 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19086 (call-interactively 'org-table-edit-formulas))
19087 (t (call-interactively 'ffap))))
19089 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19090 (defun org-ctrl-c-ctrl-c (&optional arg)
19091 "Set tags in headline, or update according to changed information at point.
19093 This command does many different things, depending on context:
19095 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19096 this is what we do.
19098 - If the cursor is on a statistics cookie, update it.
19100 - If the cursor is in a headline, prompt for tags and insert them
19101 into the current line, aligned to `org-tags-column'. When called
19102 with prefix arg, realign all tags in the current buffer.
19104 - If the cursor is in one of the special #+KEYWORD lines, this
19105 triggers scanning the buffer for these lines and updating the
19106 information.
19108 - If the cursor is inside a table, realign the table. This command
19109 works even if the automatic table editor has been turned off.
19111 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19112 the entire table.
19114 - If the cursor is at a footnote reference or definition, jump to
19115 the corresponding definition or references, respectively.
19117 - If the cursor is a the beginning of a dynamic block, update it.
19119 - If the current buffer is a capture buffer, close note and file it.
19121 - If the cursor is on a <<<target>>>, update radio targets and
19122 corresponding links in this buffer.
19124 - If the cursor is on a numbered item in a plain list, renumber the
19125 ordered list.
19127 - If the cursor is on a checkbox, toggle it.
19129 - If the cursor is on a code block, evaluate it. The variable
19130 `org-confirm-babel-evaluate' can be used to control prompting
19131 before code block evaluation, by default every code block
19132 evaluation requires confirmation. Code block evaluation can be
19133 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19134 (interactive "P")
19135 (let ((org-enable-table-editor t))
19136 (cond
19137 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19138 org-occur-highlights
19139 org-latex-fragment-image-overlays)
19140 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19141 (org-remove-occur-highlights)
19142 (org-remove-latex-fragment-image-overlays)
19143 (message "Temporary highlights/overlays removed from current buffer"))
19144 ((and (local-variable-p 'org-finish-function (current-buffer))
19145 (fboundp org-finish-function))
19146 (funcall org-finish-function))
19147 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19148 ((org-in-regexp org-ts-regexp-both)
19149 (org-timestamp-change 0 'day))
19150 ((or (looking-at org-property-start-re)
19151 (org-at-property-p))
19152 (call-interactively 'org-property-action))
19153 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19154 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19155 (or (org-at-heading-p) (org-at-item-p)))
19156 (call-interactively 'org-update-statistics-cookies))
19157 ((org-at-heading-p) (call-interactively 'org-set-tags))
19158 ((org-at-table.el-p)
19159 (message "Use C-c ' to edit table.el tables"))
19160 ((org-at-table-p)
19161 (org-table-maybe-eval-formula)
19162 (if arg
19163 (call-interactively 'org-table-recalculate)
19164 (org-table-maybe-recalculate-line))
19165 (call-interactively 'org-table-align)
19166 (orgtbl-send-table 'maybe))
19167 ((or (org-footnote-at-reference-p)
19168 (org-footnote-at-definition-p))
19169 (call-interactively 'org-footnote-action))
19170 ((org-at-item-checkbox-p)
19171 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19172 ;; list only if at top item.
19173 (let* ((cbox (match-string 1))
19174 (struct (org-list-struct))
19175 (old-struct (copy-tree struct))
19176 (parents (org-list-parents-alist struct))
19177 (orderedp (org-entry-get nil "ORDERED"))
19178 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19179 block-item)
19180 ;; Use a light version of `org-toggle-checkbox' to avoid
19181 ;; computing list structure twice.
19182 (let ((new-box (cond
19183 ((equal arg '(16)) "[-]")
19184 ((equal arg '(4)) nil)
19185 ((equal "[X]" cbox) "[ ]")
19186 (t "[X]"))))
19187 (if (and firstp arg)
19188 ;; If at first item of sub-list, remove check-box from
19189 ;; every item at the same level.
19190 (mapc
19191 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19192 (org-list-get-all-items
19193 (point-at-bol) struct (org-list-prevs-alist struct)))
19194 (org-list-set-checkbox (point-at-bol) struct new-box)))
19195 ;; Replicate `org-list-write-struct', while grabbing a return
19196 ;; value from `org-list-struct-fix-box'.
19197 (org-list-struct-fix-ind struct parents 2)
19198 (org-list-struct-fix-item-end struct)
19199 (let ((prevs (org-list-prevs-alist struct)))
19200 (org-list-struct-fix-bul struct prevs)
19201 (org-list-struct-fix-ind struct parents)
19202 (setq block-item
19203 (org-list-struct-fix-box struct parents prevs orderedp)))
19204 (org-list-struct-apply-struct struct old-struct)
19205 (org-update-checkbox-count-maybe)
19206 (when block-item
19207 (message
19208 "Checkboxes were removed due to unchecked box at line %d"
19209 (org-current-line block-item)))
19210 (when firstp (org-list-send-list 'maybe))))
19211 ((org-at-item-p)
19212 ;; Cursor at an item: repair list. Do checkbox related actions
19213 ;; only if function was called with an argument. Send list only
19214 ;; if at top item.
19215 (let* ((struct (org-list-struct))
19216 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19217 old-struct)
19218 (when arg
19219 (setq old-struct (copy-tree struct))
19220 (if firstp
19221 ;; If at first item of sub-list, add check-box to every
19222 ;; item at the same level.
19223 (mapc
19224 (lambda (pos)
19225 (unless (org-list-get-checkbox pos struct)
19226 (org-list-set-checkbox pos struct "[ ]")))
19227 (org-list-get-all-items
19228 (point-at-bol) struct (org-list-prevs-alist struct)))
19229 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19230 (org-list-write-struct
19231 struct (org-list-parents-alist struct) old-struct)
19232 (when arg (org-update-checkbox-count-maybe))
19233 (when firstp (org-list-send-list 'maybe))))
19234 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19235 ;; Dynamic block
19236 (beginning-of-line 1)
19237 (save-excursion (org-update-dblock)))
19238 ((save-excursion
19239 (let ((case-fold-search t))
19240 (beginning-of-line 1)
19241 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19242 (cond
19243 ((or (equal (match-string 1) "TBLFM")
19244 (equal (match-string 1) "tblfm"))
19245 ;; Recalculate the table before this line
19246 (save-excursion
19247 (beginning-of-line 1)
19248 (skip-chars-backward " \r\n\t")
19249 (if (org-at-table-p)
19250 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19252 (let ((org-inhibit-startup-visibility-stuff t)
19253 (org-startup-align-all-tables nil))
19254 (when (boundp 'org-table-coordinate-overlays)
19255 (mapc 'delete-overlay org-table-coordinate-overlays)
19256 (setq org-table-coordinate-overlays nil))
19257 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19258 (message "Local setup has been refreshed"))))
19259 ((org-clock-update-time-maybe))
19261 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19262 (error "C-c C-c can do nothing useful at this location"))))))
19264 (defun org-mode-restart ()
19265 "Restart Org-mode, to scan again for special lines.
19266 Also updates the keyword regular expressions."
19267 (interactive)
19268 (org-mode)
19269 (message "Org-mode restarted"))
19271 (defun org-kill-note-or-show-branches ()
19272 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19273 (interactive)
19274 (if (not org-finish-function)
19275 (progn
19276 (hide-subtree)
19277 (call-interactively 'show-branches))
19278 (let ((org-note-abort t))
19279 (funcall org-finish-function))))
19281 (defun org-return (&optional indent)
19282 "Goto next table row or insert a newline.
19283 Calls `org-table-next-row' or `newline', depending on context.
19284 See the individual commands for more information."
19285 (interactive)
19286 (let (org-ts-what)
19287 (cond
19288 ((or (bobp) (org-in-src-block-p))
19289 (if indent (newline-and-indent) (newline)))
19290 ((org-at-table-p)
19291 (org-table-justify-field-maybe)
19292 (call-interactively 'org-table-next-row))
19293 ;; when `newline-and-indent' is called within a list, make sure
19294 ;; text moved stays inside the item.
19295 ((and (org-in-item-p) indent)
19296 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19297 (progn
19298 (save-match-data (newline))
19299 (org-indent-line-to (length (match-string 0))))
19300 (let ((ind (org-get-indentation)))
19301 (newline)
19302 (if (org-looking-back org-list-end-re)
19303 (org-indent-line)
19304 (org-indent-line-to ind)))))
19305 ((and org-return-follows-link
19306 (org-at-timestamp-p t)
19307 (not (eq org-ts-what 'after)))
19308 (org-follow-timestamp-link))
19309 ((and org-return-follows-link
19310 (let ((tprop (get-text-property (point) 'face)))
19311 (or (eq tprop 'org-link)
19312 (and (listp tprop) (memq 'org-link tprop)))))
19313 (call-interactively 'org-open-at-point))
19314 ((and (org-at-heading-p)
19315 (looking-at
19316 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19317 (org-show-entry)
19318 (end-of-line 1)
19319 (newline))
19320 (t (if indent (newline-and-indent) (newline))))))
19322 (defun org-return-indent ()
19323 "Goto next table row or insert a newline and indent.
19324 Calls `org-table-next-row' or `newline-and-indent', depending on
19325 context. See the individual commands for more information."
19326 (interactive)
19327 (org-return t))
19329 (defun org-ctrl-c-star ()
19330 "Compute table, or change heading status of lines.
19331 Calls `org-table-recalculate' or `org-toggle-heading',
19332 depending on context."
19333 (interactive)
19334 (cond
19335 ((org-at-table-p)
19336 (call-interactively 'org-table-recalculate))
19338 ;; Convert all lines in region to list items
19339 (call-interactively 'org-toggle-heading))))
19341 (defun org-ctrl-c-minus ()
19342 "Insert separator line in table or modify bullet status of line.
19343 Also turns a plain line or a region of lines into list items.
19344 Calls `org-table-insert-hline', `org-toggle-item', or
19345 `org-cycle-list-bullet', depending on context."
19346 (interactive)
19347 (cond
19348 ((org-at-table-p)
19349 (call-interactively 'org-table-insert-hline))
19350 ((org-region-active-p)
19351 (call-interactively 'org-toggle-item))
19352 ((org-in-item-p)
19353 (call-interactively 'org-cycle-list-bullet))
19355 (call-interactively 'org-toggle-item))))
19357 (defun org-toggle-item (arg)
19358 "Convert headings or normal lines to items, items to normal lines.
19359 If there is no active region, only the current line is considered.
19361 If the first non blank line in the region is an headline, convert
19362 all headlines to items, shifting text accordingly.
19364 If it is an item, convert all items to normal lines.
19366 If it is normal text, change region into an item. With a prefix
19367 argument ARG, change each line in region into an item."
19368 (interactive "P")
19369 (let ((shift-text
19370 (function
19371 ;; Shift text in current section to IND, from point to END.
19372 ;; The function leaves point to END line.
19373 (lambda (ind end)
19374 (let ((min-i 1000) (end (copy-marker end)))
19375 ;; First determine the minimum indentation (MIN-I) of
19376 ;; the text.
19377 (save-excursion
19378 (catch 'exit
19379 (while (< (point) end)
19380 (let ((i (org-get-indentation)))
19381 (cond
19382 ;; Skip blank lines and inline tasks.
19383 ((looking-at "^[ \t]*$"))
19384 ((looking-at org-outline-regexp-bol))
19385 ;; We can't find less than 0 indentation.
19386 ((zerop i) (throw 'exit (setq min-i 0)))
19387 ((< i min-i) (setq min-i i))))
19388 (forward-line))))
19389 ;; Then indent each line so that a line indented to
19390 ;; MIN-I becomes indented to IND. Ignore blank lines
19391 ;; and inline tasks in the process.
19392 (let ((delta (- ind min-i)))
19393 (while (< (point) end)
19394 (unless (or (looking-at "^[ \t]*$")
19395 (looking-at org-outline-regexp-bol))
19396 (org-indent-line-to (+ (org-get-indentation) delta)))
19397 (forward-line)))))))
19398 (skip-blanks
19399 (function
19400 ;; Return beginning of first non-blank line, starting from
19401 ;; line at POS.
19402 (lambda (pos)
19403 (save-excursion
19404 (goto-char pos)
19405 (skip-chars-forward " \r\t\n")
19406 (point-at-bol)))))
19407 beg end)
19408 ;; Determine boundaries of changes.
19409 (if (org-region-active-p)
19410 (setq beg (funcall skip-blanks (region-beginning))
19411 end (copy-marker (region-end)))
19412 (setq beg (funcall skip-blanks (point-at-bol))
19413 end (copy-marker (point-at-eol))))
19414 ;; Depending on the starting line, choose an action on the text
19415 ;; between BEG and END.
19416 (org-with-limited-levels
19417 (save-excursion
19418 (goto-char beg)
19419 (cond
19420 ;; Case 1. Start at an item: de-itemize. Note that it only
19421 ;; happens when a region is active: `org-ctrl-c-minus'
19422 ;; would call `org-cycle-list-bullet' otherwise.
19423 ((org-at-item-p)
19424 (while (< (point) end)
19425 (when (org-at-item-p)
19426 (skip-chars-forward " \t")
19427 (delete-region (point) (match-end 0)))
19428 (forward-line)))
19429 ;; Case 2. Start at an heading: convert to items.
19430 ((org-at-heading-p)
19431 (let* ((bul (org-list-bullet-string "-"))
19432 (bul-len (length bul))
19433 ;; Indentation of the first heading. It should be
19434 ;; relative to the indentation of its parent, if any.
19435 (start-ind (save-excursion
19436 (cond
19437 ((not org-adapt-indentation) 0)
19438 ((not (outline-previous-heading)) 0)
19439 (t (length (match-string 0))))))
19440 ;; Level of first heading. Further headings will be
19441 ;; compared to it to determine hierarchy in the list.
19442 (ref-level (org-reduced-level (org-outline-level))))
19443 (while (< (point) end)
19444 (let* ((level (org-reduced-level (org-outline-level)))
19445 (delta (max 0 (- level ref-level))))
19446 ;; If current headline is less indented than the first
19447 ;; one, set it as reference, in order to preserve
19448 ;; subtrees.
19449 (when (< level ref-level) (setq ref-level level))
19450 (replace-match bul t t)
19451 (org-indent-line-to (+ start-ind (* delta bul-len)))
19452 ;; Ensure all text down to END (or SECTION-END) belongs
19453 ;; to the newly created item.
19454 (let ((section-end (save-excursion
19455 (or (outline-next-heading) (point)))))
19456 (forward-line)
19457 (funcall shift-text
19458 (+ start-ind (* (1+ delta) bul-len))
19459 (min end section-end)))))))
19460 ;; Case 3. Normal line with ARG: turn each non-item line into
19461 ;; an item.
19462 (arg
19463 (while (< (point) end)
19464 (unless (or (org-at-heading-p) (org-at-item-p))
19465 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19466 (replace-match
19467 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19468 (forward-line)))
19469 ;; Case 4. Normal line without ARG: make the first line of
19470 ;; region an item, and shift indentation of others
19471 ;; lines to set them as item's body.
19472 (t (let* ((bul (org-list-bullet-string "-"))
19473 (bul-len (length bul))
19474 (ref-ind (org-get-indentation)))
19475 (skip-chars-forward " \t")
19476 (insert bul)
19477 (forward-line)
19478 (while (< (point) end)
19479 ;; Ensure that lines less indented than first one
19480 ;; still get included in item body.
19481 (funcall shift-text
19482 (+ ref-ind bul-len)
19483 (min end (save-excursion (or (outline-next-heading)
19484 (point)))))
19485 (forward-line)))))))))
19487 (defun org-toggle-heading (&optional nstars)
19488 "Convert headings to normal text, or items or text to headings.
19489 If there is no active region, only the current line is considered.
19491 With a \\[universal-argument] prefix, convert the whole list at
19492 point into heading.
19494 In a region:
19496 - If the first non blank line is an headline, remove the stars
19497 from all headlines in the region.
19499 - If it is a normal line turn each and every normal line (i.e. not an
19500 heading or an item) in the region into a heading.
19502 - If it is a plain list item, turn all plain list items into headings.
19504 When converting a line into a heading, the number of stars is chosen
19505 such that the lines become children of the current entry. However,
19506 when a prefix argument is given, its value determines the number of
19507 stars to add."
19508 (interactive "P")
19509 (let ((skip-blanks
19510 (function
19511 ;; Return beginning of first non-blank line, starting from
19512 ;; line at POS.
19513 (lambda (pos)
19514 (save-excursion
19515 (goto-char pos)
19516 (while (org-at-comment-p) (forward-line))
19517 (skip-chars-forward " \r\t\n")
19518 (point-at-bol)))))
19519 beg end toggled)
19520 ;; Determine boundaries of changes. If a universal prefix has
19521 ;; been given, put the list in a region. If region ends at a bol,
19522 ;; do not consider the last line to be in the region.
19524 (when (and current-prefix-arg (org-at-item-p))
19525 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19526 (org-mark-element))
19528 (if (org-region-active-p)
19529 (setq beg (funcall skip-blanks (region-beginning))
19530 end (copy-marker (save-excursion
19531 (goto-char (region-end))
19532 (if (bolp) (point) (point-at-eol)))))
19533 (setq beg (funcall skip-blanks (point-at-bol))
19534 end (copy-marker (point-at-eol))))
19535 ;; Ensure inline tasks don't count as headings.
19536 (org-with-limited-levels
19537 (save-excursion
19538 (goto-char beg)
19539 (cond
19540 ;; Case 1. Started at an heading: de-star headings.
19541 ((org-at-heading-p)
19542 (while (< (point) end)
19543 (when (org-at-heading-p t)
19544 (looking-at org-outline-regexp) (replace-match "")
19545 (setq toggled t))
19546 (forward-line)))
19547 ;; Case 2. Started at an item: change items into headlines.
19548 ;; One star will be added by `org-list-to-subtree'.
19549 ((org-at-item-p)
19550 (let* ((stars (make-string
19551 (if nstars
19552 ;; subtract the star that will be added again by
19553 ;; `org-list-to-subtree'
19554 (1- (prefix-numeric-value current-prefix-arg))
19555 (or (org-current-level) 0))
19556 ?*))
19557 (add-stars
19558 (cond (nstars "") ; stars from prefix only
19559 ((equal stars "") "") ; before first heading
19560 (org-odd-levels-only "*") ; inside heading, odd
19561 (t "")))) ; inside heading, oddeven
19562 (while (< (point) end)
19563 (when (org-at-item-p)
19564 ;; Pay attention to cases when region ends before list.
19565 (let* ((struct (org-list-struct))
19566 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19567 (save-restriction
19568 (narrow-to-region (point) list-end)
19569 (insert
19570 (org-list-to-subtree
19571 (org-list-parse-list t)
19572 '(:istart (concat stars add-stars (funcall get-stars depth))
19573 :icount (concat stars add-stars (funcall get-stars depth)))))))
19574 (setq toggled t))
19575 (forward-line))))
19576 ;; Case 3. Started at normal text: make every line an heading,
19577 ;; skipping headlines and items.
19578 (t (let* ((stars (make-string
19579 (if nstars
19580 (prefix-numeric-value current-prefix-arg)
19581 (or (org-current-level) 0))
19582 ?*))
19583 (add-stars
19584 (cond (nstars "") ; stars from prefix only
19585 ((equal stars "") "*") ; before first heading
19586 (org-odd-levels-only "**") ; inside heading, odd
19587 (t "*"))) ; inside heading, oddeven
19588 (rpl (concat stars add-stars " ")))
19589 (while (< (point) end)
19590 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19591 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19592 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19593 (forward-line)))))))
19594 (unless toggled (message "Cannot toggle heading from here"))))
19596 (defun org-meta-return (&optional arg)
19597 "Insert a new heading or wrap a region in a table.
19598 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19599 See the individual commands for more information."
19600 (interactive "P")
19601 (cond
19602 ((run-hook-with-args-until-success 'org-metareturn-hook))
19603 ((or (org-at-drawer-p) (org-at-property-p))
19604 (newline-and-indent))
19605 ((org-at-table-p)
19606 (call-interactively 'org-table-wrap-region))
19607 (t (call-interactively 'org-insert-heading))))
19609 ;;; Menu entries
19611 (defsubst org-in-subtree-not-table-p ()
19612 "Are we in a subtree and not in a table?"
19613 (and (not (org-before-first-heading-p))
19614 (not (org-at-table-p))))
19616 ;; Define the Org-mode menus
19617 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19618 '("Tbl"
19619 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19620 ["Next Field" org-cycle (org-at-table-p)]
19621 ["Previous Field" org-shifttab (org-at-table-p)]
19622 ["Next Row" org-return (org-at-table-p)]
19623 "--"
19624 ["Blank Field" org-table-blank-field (org-at-table-p)]
19625 ["Edit Field" org-table-edit-field (org-at-table-p)]
19626 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19627 "--"
19628 ("Column"
19629 ["Move Column Left" org-metaleft (org-at-table-p)]
19630 ["Move Column Right" org-metaright (org-at-table-p)]
19631 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19632 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19633 ("Row"
19634 ["Move Row Up" org-metaup (org-at-table-p)]
19635 ["Move Row Down" org-metadown (org-at-table-p)]
19636 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19637 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19638 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19639 "--"
19640 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19641 ("Rectangle"
19642 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19643 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19644 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19645 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19646 "--"
19647 ("Calculate"
19648 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19649 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19650 ["Edit Formulas" org-edit-special (org-at-table-p)]
19651 "--"
19652 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19653 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19654 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19655 "--"
19656 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19657 "--"
19658 ["Sum Column/Rectangle" org-table-sum
19659 (or (org-at-table-p) (org-region-active-p))]
19660 ["Which Column?" org-table-current-column (org-at-table-p)])
19661 ["Debug Formulas"
19662 org-table-toggle-formula-debugger
19663 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19664 ["Show Col/Row Numbers"
19665 org-table-toggle-coordinate-overlays
19666 :style toggle
19667 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19668 "--"
19669 ["Create" org-table-create (and (not (org-at-table-p))
19670 org-enable-table-editor)]
19671 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19672 ["Import from File" org-table-import (not (org-at-table-p))]
19673 ["Export to File" org-table-export (org-at-table-p)]
19674 "--"
19675 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19677 (easy-menu-define org-org-menu org-mode-map "Org menu"
19678 '("Org"
19679 ("Show/Hide"
19680 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19681 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19682 ["Sparse Tree..." org-sparse-tree t]
19683 ["Reveal Context" org-reveal t]
19684 ["Show All" show-all t]
19685 "--"
19686 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19687 "--"
19688 ["New Heading" org-insert-heading t]
19689 ("Navigate Headings"
19690 ["Up" outline-up-heading t]
19691 ["Next" outline-next-visible-heading t]
19692 ["Previous" outline-previous-visible-heading t]
19693 ["Next Same Level" outline-forward-same-level t]
19694 ["Previous Same Level" outline-backward-same-level t]
19695 "--"
19696 ["Jump" org-goto t])
19697 ("Edit Structure"
19698 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19699 "--"
19700 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19701 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19702 "--"
19703 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19704 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19705 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19706 "--"
19707 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19708 "--"
19709 ["Copy visible text" org-copy-visible t]
19710 "--"
19711 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19712 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19713 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19714 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19715 "--"
19716 ["Sort Region/Children" org-sort t]
19717 "--"
19718 ["Convert to odd levels" org-convert-to-odd-levels t]
19719 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19720 ("Editing"
19721 ["Emphasis..." org-emphasize t]
19722 ["Edit Source Example" org-edit-special t]
19723 "--"
19724 ["Footnote new/jump" org-footnote-action t]
19725 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19726 ("Archive"
19727 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19728 "--"
19729 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19730 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19731 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19733 "--"
19734 ("Hyperlinks"
19735 ["Store Link (Global)" org-store-link t]
19736 ["Find existing link to here" org-occur-link-in-agenda-files t]
19737 ["Insert Link" org-insert-link t]
19738 ["Follow Link" org-open-at-point t]
19739 "--"
19740 ["Next link" org-next-link t]
19741 ["Previous link" org-previous-link t]
19742 "--"
19743 ["Descriptive Links"
19744 org-toggle-link-display
19745 :style radio
19746 :selected org-descriptive-links
19748 ["Literal Links"
19749 org-toggle-link-display
19750 :style radio
19751 :selected (not org-descriptive-links)])
19752 "--"
19753 ("TODO Lists"
19754 ["TODO/DONE/-" org-todo t]
19755 ("Select keyword"
19756 ["Next keyword" org-shiftright (org-at-heading-p)]
19757 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19758 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19759 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19760 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19761 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19762 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19763 "--"
19764 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19765 :selected org-enforce-todo-dependencies :style toggle :active t]
19766 "Settings for tree at point"
19767 ["Do Children sequentially" org-toggle-ordered-property :style radio
19768 :selected (org-entry-get nil "ORDERED")
19769 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19770 ["Do Children parallel" org-toggle-ordered-property :style radio
19771 :selected (not (org-entry-get nil "ORDERED"))
19772 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19773 "--"
19774 ["Set Priority" org-priority t]
19775 ["Priority Up" org-shiftup t]
19776 ["Priority Down" org-shiftdown t]
19777 "--"
19778 ["Get news from all feeds" org-feed-update-all t]
19779 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19780 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19781 ("TAGS and Properties"
19782 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19783 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19784 "--"
19785 ["Set property" org-set-property (not (org-before-first-heading-p))]
19786 ["Column view of properties" org-columns t]
19787 ["Insert Column View DBlock" org-insert-columns-dblock t])
19788 ("Dates and Scheduling"
19789 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19790 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19791 ("Change Date"
19792 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19793 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19794 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19795 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19796 ["Compute Time Range" org-evaluate-time-range t]
19797 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19798 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19799 "--"
19800 ["Custom time format" org-toggle-time-stamp-overlays
19801 :style radio :selected org-display-custom-times]
19802 "--"
19803 ["Goto Calendar" org-goto-calendar t]
19804 ["Date from Calendar" org-date-from-calendar t]
19805 "--"
19806 ["Start/Restart Timer" org-timer-start t]
19807 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19808 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19809 ["Insert Timer String" org-timer t]
19810 ["Insert Timer Item" org-timer-item t])
19811 ("Logging work"
19812 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19813 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19814 ["Clock out" org-clock-out t]
19815 ["Clock cancel" org-clock-cancel t]
19816 "--"
19817 ["Mark as default task" org-clock-mark-default-task t]
19818 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19819 ["Goto running clock" org-clock-goto t]
19820 "--"
19821 ["Display times" org-clock-display t]
19822 ["Create clock table" org-clock-report t]
19823 "--"
19824 ["Record DONE time"
19825 (progn (setq org-log-done (not org-log-done))
19826 (message "Switching to %s will %s record a timestamp"
19827 (car org-done-keywords)
19828 (if org-log-done "automatically" "not")))
19829 :style toggle :selected org-log-done])
19830 "--"
19831 ["Agenda Command..." org-agenda t]
19832 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19833 ("File List for Agenda")
19834 ("Special views current file"
19835 ["TODO Tree" org-show-todo-tree t]
19836 ["Check Deadlines" org-check-deadlines t]
19837 ["Timeline" org-timeline t]
19838 ["Tags/Property tree" org-match-sparse-tree t])
19839 "--"
19840 ["Export/Publish..." org-export t]
19841 ("LaTeX"
19842 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19843 :selected org-cdlatex-mode]
19844 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19845 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19846 ["Modify math symbol" org-cdlatex-math-modify
19847 (org-inside-LaTeX-fragment-p)]
19848 ["Insert citation" org-reftex-citation t]
19849 "--"
19850 ["Template for BEAMER" (progn (require 'org-beamer)
19851 (org-insert-beamer-options-template)) t])
19852 "--"
19853 ("MobileOrg"
19854 ["Push Files and Views" org-mobile-push t]
19855 ["Get Captured and Flagged" org-mobile-pull t]
19856 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19857 "--"
19858 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19859 "--"
19860 ("Documentation"
19861 ["Show Version" org-version t]
19862 ["Info Documentation" org-info t])
19863 ("Customize"
19864 ["Browse Org Group" org-customize t]
19865 "--"
19866 ["Expand This Menu" org-create-customize-menu
19867 (fboundp 'customize-menu-create)])
19868 ["Send bug report" org-submit-bug-report t]
19869 "--"
19870 ("Refresh/Reload"
19871 ["Refresh setup current buffer" org-mode-restart t]
19872 ["Reload Org (after update)" org-reload t]
19873 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19876 (defun org-info (&optional node)
19877 "Read documentation for Org-mode in the info system.
19878 With optional NODE, go directly to that node."
19879 (interactive)
19880 (info (format "(org)%s" (or node ""))))
19882 ;;;###autoload
19883 (defun org-submit-bug-report ()
19884 "Submit a bug report on Org-mode via mail.
19886 Don't hesitate to report any problems or inaccurate documentation.
19888 If you don't have setup sending mail from (X)Emacs, please copy the
19889 output buffer into your mail program, as it gives us important
19890 information about your Org-mode version and configuration."
19891 (interactive)
19892 (require 'reporter)
19893 (org-load-modules-maybe)
19894 (org-require-autoloaded-modules)
19895 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19896 (reporter-submit-bug-report
19897 "emacs-orgmode@gnu.org"
19898 (org-version nil 'full)
19899 (let (list)
19900 (save-window-excursion
19901 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19902 (delete-other-windows)
19903 (erase-buffer)
19904 (insert "You are about to submit a bug report to the Org-mode mailing list.
19906 We would like to add your full Org-mode and Outline configuration to the
19907 bug report. This greatly simplifies the work of the maintainer and
19908 other experts on the mailing list.
19910 HOWEVER, some variables you have customized may contain private
19911 information. The names of customers, colleagues, or friends, might
19912 appear in the form of file names, tags, todo states, or search strings.
19913 If you answer yes to the prompt, you might want to check and remove
19914 such private information before sending the email.")
19915 (add-text-properties (point-min) (point-max) '(face org-warning))
19916 (when (yes-or-no-p "Include your Org-mode configuration ")
19917 (mapatoms
19918 (lambda (v)
19919 (and (boundp v)
19920 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19921 (or (and (symbol-value v)
19922 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19923 (and
19924 (get v 'custom-type) (get v 'standard-value)
19925 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19926 (push v list)))))
19927 (kill-buffer (get-buffer "*Warn about privacy*"))
19928 list))
19929 nil nil
19930 "Remember to cover the basics, that is, what you expected to happen and
19931 what in fact did happen. You don't know how to make a good report? See
19933 http://orgmode.org/manual/Feedback.html#Feedback
19935 Your bug report will be posted to the Org-mode mailing list.
19936 ------------------------------------------------------------------------")
19937 (save-excursion
19938 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19939 (replace-match "\\1Bug: \\3 [\\2]")))))
19942 (defun org-install-agenda-files-menu ()
19943 (let ((bl (buffer-list)))
19944 (save-excursion
19945 (while bl
19946 (set-buffer (pop bl))
19947 (if (derived-mode-p 'org-mode) (setq bl nil)))
19948 (when (derived-mode-p 'org-mode)
19949 (easy-menu-change
19950 '("Org") "File List for Agenda"
19951 (append
19952 (list
19953 ["Edit File List" (org-edit-agenda-file-list) t]
19954 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19955 ["Remove Current File from List" org-remove-file t]
19956 ["Cycle through agenda files" org-cycle-agenda-files t]
19957 ["Occur in all agenda files" org-occur-in-agenda-files t]
19958 "--")
19959 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19961 ;;;; Documentation
19963 ;;;###autoload
19964 (defun org-require-autoloaded-modules ()
19965 (interactive)
19966 (mapc 'require
19967 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19968 org-docbook org-exp org-html org-icalendar
19969 org-id org-latex
19970 org-publish org-remember org-table
19971 org-timer org-xoxo)))
19973 ;;;###autoload
19974 (defun org-reload (&optional uncompiled)
19975 "Reload all org lisp files.
19976 With prefix arg UNCOMPILED, load the uncompiled versions."
19977 (interactive "P")
19978 (require 'find-func)
19979 (let* ((file-re "^org\\(-.*\\)?\\.el")
19980 (dir-org (file-name-directory (org-find-library-dir "org")))
19981 (dir-org-contrib (ignore-errors
19982 (file-name-directory
19983 (org-find-library-dir "org-contribdir"))))
19984 (babel-files
19985 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19986 (append (list nil "comint" "eval" "exp" "keys"
19987 "lob" "ref" "table" "tangle")
19988 (delq nil
19989 (mapcar
19990 (lambda (lang)
19991 (when (cdr lang) (symbol-name (car lang))))
19992 org-babel-load-languages)))))
19993 (files
19994 (append babel-files
19995 (and dir-org-contrib
19996 (directory-files dir-org-contrib t file-re))
19997 (directory-files dir-org t file-re)))
19998 (remove-re (concat (if (featurep 'xemacs)
19999 "org-colview" "org-colview-xemacs")
20000 "\\'")))
20001 (setq files (mapcar 'file-name-sans-extension files))
20002 (setq files (mapcar
20003 (lambda (x) (if (string-match remove-re x) nil x))
20004 files))
20005 (setq files (delq nil files))
20006 (mapc
20007 (lambda (f)
20008 (when (featurep (intern (file-name-nondirectory f)))
20009 (if (and (not uncompiled)
20010 (file-exists-p (concat f ".elc")))
20011 (load (concat f ".elc") nil nil 'nosuffix)
20012 (load (concat f ".el") nil nil 'nosuffix))))
20013 files)
20014 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20015 (org-version nil 'full 'message))
20017 ;;;###autoload
20018 (defun org-customize ()
20019 "Call the customize function with org as argument."
20020 (interactive)
20021 (org-load-modules-maybe)
20022 (org-require-autoloaded-modules)
20023 (customize-browse 'org))
20025 (defun org-create-customize-menu ()
20026 "Create a full customization menu for Org-mode, insert it into the menu."
20027 (interactive)
20028 (org-load-modules-maybe)
20029 (org-require-autoloaded-modules)
20030 (if (fboundp 'customize-menu-create)
20031 (progn
20032 (easy-menu-change
20033 '("Org") "Customize"
20034 `(["Browse Org group" org-customize t]
20035 "--"
20036 ,(customize-menu-create 'org)
20037 ["Set" Custom-set t]
20038 ["Save" Custom-save t]
20039 ["Reset to Current" Custom-reset-current t]
20040 ["Reset to Saved" Custom-reset-saved t]
20041 ["Reset to Standard Settings" Custom-reset-standard t]))
20042 (message "\"Org\"-menu now contains full customization menu"))
20043 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20045 ;;;; Miscellaneous stuff
20047 ;;; Generally useful functions
20049 (defun org-get-at-bol (property)
20050 "Get text property PROPERTY at beginning of line."
20051 (get-text-property (point-at-bol) property))
20053 (defun org-find-text-property-in-string (prop s)
20054 "Return the first non-nil value of property PROP in string S."
20055 (or (get-text-property 0 prop s)
20056 (get-text-property (or (next-single-property-change 0 prop s) 0)
20057 prop s)))
20059 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20060 "Display the given MESSAGE as a warning."
20061 (if (fboundp 'display-warning)
20062 (display-warning 'org message
20063 (if (featurep 'xemacs) 'warning :warning))
20064 (let ((buf (get-buffer-create "*Org warnings*")))
20065 (with-current-buffer buf
20066 (goto-char (point-max))
20067 (insert "Warning (Org): " message)
20068 (unless (bolp)
20069 (newline)))
20070 (display-buffer buf)
20071 (sit-for 0))))
20073 (defun org-eval (form)
20074 "Eval FORM and return result."
20075 (condition-case error
20076 (eval form)
20077 (error (format "%%![Error: %s]" error))))
20079 (defun org-in-clocktable-p ()
20080 "Check if the cursor is in a clocktable."
20081 (let ((pos (point)) start)
20082 (save-excursion
20083 (end-of-line 1)
20084 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20085 (setq start (match-beginning 0))
20086 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20087 (>= (match-end 0) pos)
20088 start))))
20090 (defun org-in-commented-line ()
20091 "Is point in a line starting with `#'?"
20092 (equal (char-after (point-at-bol)) ?#))
20094 (defun org-in-indented-comment-line ()
20095 "Is point in a line starting with `#' after some white space?"
20096 (save-excursion
20097 (save-match-data
20098 (goto-char (point-at-bol))
20099 (looking-at "[ \t]*#"))))
20101 (defun org-in-verbatim-emphasis ()
20102 (save-match-data
20103 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20105 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20106 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20107 (if (and marker (marker-buffer marker)
20108 (buffer-live-p (marker-buffer marker)))
20109 (progn
20110 (org-pop-to-buffer-same-window (marker-buffer marker))
20111 (if (or (> marker (point-max)) (< marker (point-min)))
20112 (widen))
20113 (goto-char marker)
20114 (org-show-context 'org-goto))
20115 (if bookmark
20116 (bookmark-jump bookmark)
20117 (error "Cannot find location"))))
20119 (defun org-quote-csv-field (s)
20120 "Quote field for inclusion in CSV material."
20121 (if (string-match "[\",]" s)
20122 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20125 (defun org-force-self-insert (N)
20126 "Needed to enforce self-insert under remapping."
20127 (interactive "p")
20128 (self-insert-command N))
20130 (defun org-string-width (s)
20131 "Compute width of string, ignoring invisible characters.
20132 This ignores character with invisibility property `org-link', and also
20133 characters with property `org-cwidth', because these will become invisible
20134 upon the next fontification round."
20135 (let (b l)
20136 (when (or (eq t buffer-invisibility-spec)
20137 (assq 'org-link buffer-invisibility-spec))
20138 (while (setq b (text-property-any 0 (length s)
20139 'invisible 'org-link s))
20140 (setq s (concat (substring s 0 b)
20141 (substring s (or (next-single-property-change
20142 b 'invisible s) (length s)))))))
20143 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20144 (setq s (concat (substring s 0 b)
20145 (substring s (or (next-single-property-change
20146 b 'org-cwidth s) (length s))))))
20147 (setq l (string-width s) b -1)
20148 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20149 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20152 (defun org-shorten-string (s maxlength)
20153 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20154 If the string is shorter or has length MAXLENGTH, just return the
20155 original string. If it is longer, the functions finds a space in the
20156 string, breaks this string off at that locations and adds three dots
20157 as ellipsis. Including the ellipsis, the string will not be longer
20158 than MAXLENGTH. If finding a good breaking point in the string does
20159 not work, the string is just chopped off in the middle of a word
20160 if necessary."
20161 (if (<= (length s) maxlength)
20163 (let* ((n (max (- maxlength 4) 1))
20164 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20165 (if (string-match re s)
20166 (concat (match-string 1 s) "...")
20167 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20169 (defun org-get-indentation (&optional line)
20170 "Get the indentation of the current line, interpreting tabs.
20171 When LINE is given, assume it represents a line and compute its indentation."
20172 (if line
20173 (if (string-match "^ *" (org-remove-tabs line))
20174 (match-end 0))
20175 (save-excursion
20176 (beginning-of-line 1)
20177 (skip-chars-forward " \t")
20178 (current-column))))
20180 (defun org-get-string-indentation (s)
20181 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20182 (let ((n -1) (i 0) (w tab-width) c)
20183 (catch 'exit
20184 (while (< (setq n (1+ n)) (length s))
20185 (setq c (aref s n))
20186 (cond ((= c ?\ ) (setq i (1+ i)))
20187 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20188 (t (throw 'exit t)))))
20191 (defun org-remove-tabs (s &optional width)
20192 "Replace tabulators in S with spaces.
20193 Assumes that s is a single line, starting in column 0."
20194 (setq width (or width tab-width))
20195 (while (string-match "\t" s)
20196 (setq s (replace-match
20197 (make-string
20198 (- (* width (/ (+ (match-beginning 0) width) width))
20199 (match-beginning 0)) ?\ )
20200 t t s)))
20203 (defun org-fix-indentation (line ind)
20204 "Fix indentation in LINE.
20205 IND is a cons cell with target and minimum indentation.
20206 If the current indentation in LINE is smaller than the minimum,
20207 leave it alone. If it is larger than ind, set it to the target."
20208 (let* ((l (org-remove-tabs line))
20209 (i (org-get-indentation l))
20210 (i1 (car ind)) (i2 (cdr ind)))
20211 (if (>= i i2) (setq l (substring line i2)))
20212 (if (> i1 0)
20213 (concat (make-string i1 ?\ ) l)
20214 l)))
20216 (defun org-remove-indentation (code &optional n)
20217 "Remove the maximum common indentation from the lines in CODE.
20218 N may optionally be the number of spaces to remove."
20219 (with-temp-buffer
20220 (insert code)
20221 (org-do-remove-indentation n)
20222 (buffer-string)))
20224 (defun org-do-remove-indentation (&optional n)
20225 "Remove the maximum common indentation from the buffer."
20226 (untabify (point-min) (point-max))
20227 (let ((min 10000) re)
20228 (if n
20229 (setq min n)
20230 (goto-char (point-min))
20231 (while (re-search-forward "^ *[^ \n]" nil t)
20232 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20233 (unless (or (= min 0) (= min 10000))
20234 (setq re (format "^ \\{%d\\}" min))
20235 (goto-char (point-min))
20236 (while (re-search-forward re nil t)
20237 (replace-match "")
20238 (end-of-line 1))
20239 min)))
20241 (defun org-fill-template (template alist)
20242 "Find each %key of ALIST in TEMPLATE and replace it."
20243 (let ((case-fold-search nil)
20244 entry key value)
20245 (setq alist (sort (copy-sequence alist)
20246 (lambda (a b) (< (length (car a)) (length (car b))))))
20247 (while (setq entry (pop alist))
20248 (setq template
20249 (replace-regexp-in-string
20250 (concat "%" (regexp-quote (car entry)))
20251 (or (cdr entry) "") template t t)))
20252 template))
20254 (defun org-base-buffer (buffer)
20255 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20256 (if (not buffer)
20257 buffer
20258 (or (buffer-base-buffer buffer)
20259 buffer)))
20261 (defun org-trim (s)
20262 "Remove whitespace at beginning and end of string."
20263 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20264 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20267 (defun org-wrap (string &optional width lines)
20268 "Wrap string to either a number of lines, or a width in characters.
20269 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20270 that costs. If there is a word longer than WIDTH, the text is actually
20271 wrapped to the length of that word.
20272 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20273 many lines, whatever width that takes.
20274 The return value is a list of lines, without newlines at the end."
20275 (let* ((words (org-split-string string "[ \t\n]+"))
20276 (maxword (apply 'max (mapcar 'org-string-width words)))
20277 w ll)
20278 (cond (width
20279 (org-do-wrap words (max maxword width)))
20280 (lines
20281 (setq w maxword)
20282 (setq ll (org-do-wrap words maxword))
20283 (if (<= (length ll) lines)
20285 (setq ll words)
20286 (while (> (length ll) lines)
20287 (setq w (1+ w))
20288 (setq ll (org-do-wrap words w)))
20289 ll))
20290 (t (error "Cannot wrap this")))))
20292 (defun org-do-wrap (words width)
20293 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20294 (let (lines line)
20295 (while words
20296 (setq line (pop words))
20297 (while (and words (< (+ (length line) (length (car words))) width))
20298 (setq line (concat line " " (pop words))))
20299 (setq lines (push line lines)))
20300 (nreverse lines)))
20302 (defun org-split-string (string &optional separators)
20303 "Splits STRING into substrings at SEPARATORS.
20304 No empty strings are returned if there are matches at the beginning
20305 and end of string."
20306 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20307 (start 0)
20308 notfirst
20309 (list nil))
20310 (while (and (string-match rexp string
20311 (if (and notfirst
20312 (= start (match-beginning 0))
20313 (< start (length string)))
20314 (1+ start) start))
20315 (< (match-beginning 0) (length string)))
20316 (setq notfirst t)
20317 (or (eq (match-beginning 0) 0)
20318 (and (eq (match-beginning 0) (match-end 0))
20319 (eq (match-beginning 0) start))
20320 (setq list
20321 (cons (substring string start (match-beginning 0))
20322 list)))
20323 (setq start (match-end 0)))
20324 (or (eq start (length string))
20325 (setq list
20326 (cons (substring string start)
20327 list)))
20328 (nreverse list)))
20330 (defun org-quote-vert (s)
20331 "Replace \"|\" with \"\\vert\"."
20332 (while (string-match "|" s)
20333 (setq s (replace-match "\\vert" t t s)))
20336 (defun org-uuidgen-p (s)
20337 "Is S an ID created by UUIDGEN?"
20338 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20340 (defun org-in-src-block-p nil
20341 "Whether point is in a code source block."
20342 (let (ov)
20343 (when (setq ov (overlays-at (point)))
20344 (memq 'org-block-background
20345 (overlay-properties
20346 (car ov))))))
20348 (defun org-context ()
20349 "Return a list of contexts of the current cursor position.
20350 If several contexts apply, all are returned.
20351 Each context entry is a list with a symbol naming the context, and
20352 two positions indicating start and end of the context. Possible
20353 contexts are:
20355 :headline anywhere in a headline
20356 :headline-stars on the leading stars in a headline
20357 :todo-keyword on a TODO keyword (including DONE) in a headline
20358 :tags on the TAGS in a headline
20359 :priority on the priority cookie in a headline
20360 :item on the first line of a plain list item
20361 :item-bullet on the bullet/number of a plain list item
20362 :checkbox on the checkbox in a plain list item
20363 :table in an org-mode table
20364 :table-special on a special filed in a table
20365 :table-table in a table.el table
20366 :clocktable in a clocktable
20367 :src-block in a source block
20368 :link on a hyperlink
20369 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20370 :target on a <<target>>
20371 :radio-target on a <<<radio-target>>>
20372 :latex-fragment on a LaTeX fragment
20373 :latex-preview on a LaTeX fragment with overlaid preview image
20375 This function expects the position to be visible because it uses font-lock
20376 faces as a help to recognize the following contexts: :table-special, :link,
20377 and :keyword."
20378 (let* ((f (get-text-property (point) 'face))
20379 (faces (if (listp f) f (list f)))
20380 (case-fold-search t)
20381 (p (point)) clist o)
20382 ;; First the large context
20383 (cond
20384 ((org-at-heading-p t)
20385 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20386 (when (progn
20387 (beginning-of-line 1)
20388 (looking-at org-todo-line-tags-regexp))
20389 (push (org-point-in-group p 1 :headline-stars) clist)
20390 (push (org-point-in-group p 2 :todo-keyword) clist)
20391 (push (org-point-in-group p 4 :tags) clist))
20392 (goto-char p)
20393 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20394 (if (looking-at "\\[#[A-Z0-9]\\]")
20395 (push (org-point-in-group p 0 :priority) clist)))
20397 ((org-at-item-p)
20398 (push (org-point-in-group p 2 :item-bullet) clist)
20399 (push (list :item (point-at-bol)
20400 (save-excursion (org-end-of-item) (point)))
20401 clist)
20402 (and (org-at-item-checkbox-p)
20403 (push (org-point-in-group p 0 :checkbox) clist)))
20405 ((org-at-table-p)
20406 (push (list :table (org-table-begin) (org-table-end)) clist)
20407 (if (memq 'org-formula faces)
20408 (push (list :table-special
20409 (previous-single-property-change p 'face)
20410 (next-single-property-change p 'face)) clist)))
20411 ((org-at-table-p 'any)
20412 (push (list :table-table) clist)))
20413 (goto-char p)
20415 (let ((case-fold-search t))
20416 ;; New the "medium" contexts: clocktables, source blocks
20417 (cond ((org-in-clocktable-p)
20418 (push (list :clocktable
20419 (and (or (looking-at "#\\+BEGIN: clocktable")
20420 (search-backward "#+BEGIN: clocktable" nil t))
20421 (match-beginning 0))
20422 (and (re-search-forward "#\\+END:?" nil t)
20423 (match-end 0))) clist))
20424 ((org-in-src-block-p)
20425 (push (list :src-block
20426 (and (or (looking-at "#\\+BEGIN_SRC")
20427 (search-backward "#+BEGIN_SRC" nil t))
20428 (match-beginning 0))
20429 (and (search-forward "#+END_SRC" nil t)
20430 (match-beginning 0))) clist))))
20431 (goto-char p)
20433 ;; Now the small context
20434 (cond
20435 ((org-at-timestamp-p)
20436 (push (org-point-in-group p 0 :timestamp) clist))
20437 ((memq 'org-link faces)
20438 (push (list :link
20439 (previous-single-property-change p 'face)
20440 (next-single-property-change p 'face)) clist))
20441 ((memq 'org-special-keyword faces)
20442 (push (list :keyword
20443 (previous-single-property-change p 'face)
20444 (next-single-property-change p 'face)) clist))
20445 ((org-at-target-p)
20446 (push (org-point-in-group p 0 :target) clist)
20447 (goto-char (1- (match-beginning 0)))
20448 (if (looking-at org-radio-target-regexp)
20449 (push (org-point-in-group p 0 :radio-target) clist))
20450 (goto-char p))
20451 ((setq o (car (delq nil
20452 (mapcar
20453 (lambda (x)
20454 (if (memq x org-latex-fragment-image-overlays) x))
20455 (overlays-at (point))))))
20456 (push (list :latex-fragment
20457 (overlay-start o) (overlay-end o)) clist)
20458 (push (list :latex-preview
20459 (overlay-start o) (overlay-end o)) clist))
20460 ((org-inside-LaTeX-fragment-p)
20461 ;; FIXME: positions wrong.
20462 (push (list :latex-fragment (point) (point)) clist)))
20464 (setq clist (nreverse (delq nil clist)))
20465 clist))
20467 ;; FIXME: Compare with at-regexp-p Do we need both?
20468 (defun org-in-regexp (re &optional nlines visually)
20469 "Check if point is inside a match of regexp.
20470 Normally only the current line is checked, but you can include NLINES extra
20471 lines both before and after point into the search.
20472 If VISUALLY is set, require that the cursor is not after the match but
20473 really on, so that the block visually is on the match."
20474 (catch 'exit
20475 (let ((pos (point))
20476 (eol (point-at-eol (+ 1 (or nlines 0))))
20477 (inc (if visually 1 0)))
20478 (save-excursion
20479 (beginning-of-line (- 1 (or nlines 0)))
20480 (while (re-search-forward re eol t)
20481 (if (and (<= (match-beginning 0) pos)
20482 (>= (+ inc (match-end 0)) pos))
20483 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20485 (defun org-at-regexp-p (regexp)
20486 "Is point inside a match of REGEXP in the current line?"
20487 (catch 'exit
20488 (save-excursion
20489 (let ((pos (point)) (end (point-at-eol)))
20490 (beginning-of-line 1)
20491 (while (re-search-forward regexp end t)
20492 (if (and (<= (match-beginning 0) pos)
20493 (>= (match-end 0) pos))
20494 (throw 'exit t)))
20495 nil))))
20497 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20498 "Non-nil when point is between matches of START-RE and END-RE.
20500 Also return a non-nil value when point is on one of the matches.
20502 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20503 buffer positions. Default values are the positions of headlines
20504 surrounding the point.
20506 The functions returns a cons cell whose car (resp. cdr) is the
20507 position before START-RE (resp. after END-RE)."
20508 (save-match-data
20509 (let ((pos (point))
20510 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20511 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20512 beg end)
20513 (save-excursion
20514 ;; Point is on a block when on START-RE or if START-RE can be
20515 ;; found before it...
20516 (and (or (org-at-regexp-p start-re)
20517 (re-search-backward start-re limit-up t))
20518 (setq beg (match-beginning 0))
20519 ;; ... and END-RE after it...
20520 (goto-char (match-end 0))
20521 (re-search-forward end-re limit-down t)
20522 (> (setq end (match-end 0)) pos)
20523 ;; ... without another START-RE in-between.
20524 (goto-char (match-beginning 0))
20525 (not (re-search-backward start-re (1+ beg) t))
20526 ;; Return value.
20527 (cons beg end))))))
20529 (defun org-in-block-p (names)
20530 "Non-nil when point belongs to a block whose name belongs to NAMES.
20532 NAMES is a list of strings containing names of blocks.
20534 Return first block name matched, or nil. Beware that in case of
20535 nested blocks, the returned name may not belong to the closest
20536 block from point."
20537 (save-match-data
20538 (catch 'exit
20539 (let ((case-fold-search t)
20540 (lim-up (save-excursion (outline-previous-heading)))
20541 (lim-down (save-excursion (outline-next-heading))))
20542 (mapc (lambda (name)
20543 (let ((n (regexp-quote name)))
20544 (when (org-between-regexps-p
20545 (concat "^[ \t]*#\\+begin_" n)
20546 (concat "^[ \t]*#\\+end_" n)
20547 lim-up lim-down)
20548 (throw 'exit n))))
20549 names))
20550 nil)))
20552 (defun org-occur-in-agenda-files (regexp &optional nlines)
20553 "Call `multi-occur' with buffers for all agenda files."
20554 (interactive "sOrg-files matching: \np")
20555 (let* ((files (org-agenda-files))
20556 (tnames (mapcar 'file-truename files))
20557 (extra org-agenda-text-search-extra-files)
20559 (when (eq (car extra) 'agenda-archives)
20560 (setq extra (cdr extra))
20561 (setq files (org-add-archive-files files)))
20562 (while (setq f (pop extra))
20563 (unless (member (file-truename f) tnames)
20564 (add-to-list 'files f 'append)
20565 (add-to-list 'tnames (file-truename f) 'append)))
20566 (multi-occur
20567 (mapcar (lambda (x)
20568 (with-current-buffer
20569 (or (get-file-buffer x) (find-file-noselect x))
20570 (widen)
20571 (current-buffer)))
20572 files)
20573 regexp)))
20575 (if (boundp 'occur-mode-find-occurrence-hook)
20576 ;; Emacs 23
20577 (add-hook 'occur-mode-find-occurrence-hook
20578 (lambda ()
20579 (when (derived-mode-p 'org-mode)
20580 (org-reveal))))
20581 ;; Emacs 22
20582 (defadvice occur-mode-goto-occurrence
20583 (after org-occur-reveal activate)
20584 (and (derived-mode-p 'org-mode) (org-reveal)))
20585 (defadvice occur-mode-goto-occurrence-other-window
20586 (after org-occur-reveal activate)
20587 (and (derived-mode-p 'org-mode) (org-reveal)))
20588 (defadvice occur-mode-display-occurrence
20589 (after org-occur-reveal activate)
20590 (when (derived-mode-p 'org-mode)
20591 (let ((pos (occur-mode-find-occurrence)))
20592 (with-current-buffer (marker-buffer pos)
20593 (save-excursion
20594 (goto-char pos)
20595 (org-reveal)))))))
20597 (defun org-occur-link-in-agenda-files ()
20598 "Create a link and search for it in the agendas.
20599 The link is not stored in `org-stored-links', it is just created
20600 for the search purpose."
20601 (interactive)
20602 (let ((link (condition-case nil
20603 (org-store-link nil)
20604 (error "Unable to create a link to here"))))
20605 (org-occur-in-agenda-files (regexp-quote link))))
20607 (defun org-uniquify (list)
20608 "Remove duplicate elements from LIST."
20609 (let (res)
20610 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20611 res))
20613 (defun org-delete-all (elts list)
20614 "Remove all elements in ELTS from LIST."
20615 (while elts
20616 (setq list (delete (pop elts) list)))
20617 list)
20619 (defun org-count (cl-item cl-seq)
20620 "Count the number of occurrences of ITEM in SEQ.
20621 Taken from `count' in cl-seq.el with all keyword arguments removed."
20622 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20623 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20624 (while (< cl-start cl-end)
20625 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20626 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20627 (setq cl-start (1+ cl-start)))
20628 cl-count))
20630 (defun org-remove-if (predicate seq)
20631 "Remove everything from SEQ that fulfills PREDICATE."
20632 (let (res e)
20633 (while seq
20634 (setq e (pop seq))
20635 (if (not (funcall predicate e)) (push e res)))
20636 (nreverse res)))
20638 (defun org-remove-if-not (predicate seq)
20639 "Remove everything from SEQ that does not fulfill PREDICATE."
20640 (let (res e)
20641 (while seq
20642 (setq e (pop seq))
20643 (if (funcall predicate e) (push e res)))
20644 (nreverse res)))
20646 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20647 "Reduce two-argument FUNCTION across SEQ.
20648 Taken from `reduce' in cl-seq.el with all keyword arguments but
20649 \":initial-value\" removed."
20650 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20651 (cadr (memq :initial-value cl-keys)))
20652 (cl-seq (pop cl-seq))
20653 (t (funcall cl-func)))))
20654 (while cl-seq
20655 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20656 cl-accum))
20658 (defun org-back-over-empty-lines ()
20659 "Move backwards over whitespace, to the beginning of the first empty line.
20660 Returns the number of empty lines passed."
20661 (let ((pos (point)))
20662 (if (cdr (assoc 'heading org-blank-before-new-entry))
20663 (skip-chars-backward " \t\n\r")
20664 (unless (eobp)
20665 (forward-line -1)))
20666 (beginning-of-line 2)
20667 (goto-char (min (point) pos))
20668 (count-lines (point) pos)))
20670 (defun org-skip-whitespace ()
20671 (skip-chars-forward " \t\n\r"))
20673 (defun org-point-in-group (point group &optional context)
20674 "Check if POINT is in match-group GROUP.
20675 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20676 match. If the match group does not exist or point is not inside it,
20677 return nil."
20678 (and (match-beginning group)
20679 (>= point (match-beginning group))
20680 (<= point (match-end group))
20681 (if context
20682 (list context (match-beginning group) (match-end group))
20683 t)))
20685 (defun org-switch-to-buffer-other-window (&rest args)
20686 "Switch to buffer in a second window on the current frame.
20687 In particular, do not allow pop-up frames.
20688 Returns the newly created buffer."
20689 (let (pop-up-frames special-display-buffer-names special-display-regexps
20690 special-display-function)
20691 (apply 'switch-to-buffer-other-window args)))
20693 (defun org-combine-plists (&rest plists)
20694 "Create a single property list from all plists in PLISTS.
20695 The process starts by copying the first list, and then setting properties
20696 from the other lists. Settings in the last list are the most significant
20697 ones and overrule settings in the other lists."
20698 (let ((rtn (copy-sequence (pop plists)))
20699 p v ls)
20700 (while plists
20701 (setq ls (pop plists))
20702 (while ls
20703 (setq p (pop ls) v (pop ls))
20704 (setq rtn (plist-put rtn p v))))
20705 rtn))
20707 (defun org-replace-escapes (string table)
20708 "Replace %-escapes in STRING with values in TABLE.
20709 TABLE is an association list with keys like \"%a\" and string values.
20710 The sequences in STRING may contain normal field width and padding information,
20711 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20712 so values can contain further %-escapes if they are define later in TABLE."
20713 (let ((tbl (copy-alist table))
20714 (case-fold-search nil)
20715 (pchg 0)
20716 e re rpl)
20717 (while (setq e (pop tbl))
20718 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20719 (when (and (cdr e) (string-match re (cdr e)))
20720 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20721 (safe "SREF"))
20722 (add-text-properties 0 3 (list 'sref sref) safe)
20723 (setcdr e (replace-match safe t t (cdr e)))))
20724 (while (string-match re string)
20725 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20726 (cdr e)))
20727 (setq string (replace-match rpl t t string))))
20728 (while (setq pchg (next-property-change pchg string))
20729 (let ((sref (get-text-property pchg 'sref string)))
20730 (when (and sref (string-match "SREF" string pchg))
20731 (setq string (replace-match sref t t string)))))
20732 string))
20734 (defun org-sublist (list start end)
20735 "Return a section of LIST, from START to END.
20736 Counting starts at 1."
20737 (let (rtn (c start))
20738 (setq list (nthcdr (1- start) list))
20739 (while (and list (<= c end))
20740 (push (pop list) rtn)
20741 (setq c (1+ c)))
20742 (nreverse rtn)))
20744 (defun org-find-base-buffer-visiting (file)
20745 "Like `find-buffer-visiting' but always return the base buffer and
20746 not an indirect buffer."
20747 (let ((buf (or (get-file-buffer file)
20748 (find-buffer-visiting file))))
20749 (if buf
20750 (or (buffer-base-buffer buf) buf)
20751 nil)))
20753 (defun org-image-file-name-regexp (&optional extensions)
20754 "Return regexp matching the file names of images.
20755 If EXTENSIONS is given, only match these."
20756 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20757 (image-file-name-regexp)
20758 (let ((image-file-name-extensions
20759 (or extensions
20760 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20761 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20762 (concat "\\."
20763 (regexp-opt (nconc (mapcar 'upcase
20764 image-file-name-extensions)
20765 image-file-name-extensions)
20767 "\\'"))))
20769 (defun org-file-image-p (file &optional extensions)
20770 "Return non-nil if FILE is an image."
20771 (save-match-data
20772 (string-match (org-image-file-name-regexp extensions) file)))
20774 (defun org-get-cursor-date ()
20775 "Return the date at cursor in as a time.
20776 This works in the calendar and in the agenda, anywhere else it just
20777 returns the current time."
20778 (let (date day defd)
20779 (cond
20780 ((eq major-mode 'calendar-mode)
20781 (setq date (calendar-cursor-to-date)
20782 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20783 ((eq major-mode 'org-agenda-mode)
20784 (setq day (get-text-property (point) 'day))
20785 (if day
20786 (setq date (calendar-gregorian-from-absolute day)
20787 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20788 (nth 2 date))))))
20789 (or defd (current-time))))
20791 (defun org-mark-subtree (&optional up)
20792 "Mark the current subtree.
20793 This puts point at the start of the current subtree, and mark at
20794 the end. If a numeric prefix UP is given, move up into the
20795 hierarchy of headlines by UP levels before marking the subtree."
20796 (interactive "P")
20797 (org-with-limited-levels
20798 (cond ((org-at-heading-p) (beginning-of-line))
20799 ((org-before-first-heading-p) (error "Not in a subtree"))
20800 (t (outline-previous-visible-heading 1))))
20801 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20802 (if (org-called-interactively-p 'any)
20803 (call-interactively 'org-mark-element)
20804 (org-mark-element)))
20806 ;;; Indentation
20808 (defun org-indent-line ()
20809 "Indent line depending on context."
20810 (interactive)
20811 (let* ((pos (point))
20812 (itemp (org-at-item-p))
20813 (case-fold-search t)
20814 (org-drawer-regexp (or org-drawer-regexp "\000"))
20815 (inline-task-p (and (featurep 'org-inlinetask)
20816 (org-inlinetask-in-task-p)))
20817 (inline-re (and inline-task-p
20818 (org-inlinetask-outline-regexp)))
20819 column)
20820 (if (and orgstruct-is-++ (eq pos (point)))
20821 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20822 (indent-according-to-mode))
20823 (beginning-of-line 1)
20824 (cond
20825 ;; Headings
20826 ((looking-at org-outline-regexp) (setq column 0))
20827 ;; Included files
20828 ((looking-at "#\\+include:") (setq column 0))
20829 ;; Footnote definition
20830 ((looking-at org-footnote-definition-re) (setq column 0))
20831 ;; Literal examples
20832 ((looking-at "[ \t]*:\\( \\|$\\)")
20833 (setq column (org-get-indentation))) ; do nothing
20834 ;; Lists
20835 ((ignore-errors (goto-char (org-in-item-p)))
20836 (setq column (if itemp
20837 (org-get-indentation)
20838 (org-list-item-body-column (point))))
20839 (goto-char pos))
20840 ;; Drawers
20841 ((and (looking-at "[ \t]*:END:")
20842 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20843 (save-excursion
20844 (goto-char (1- (match-beginning 1)))
20845 (setq column (current-column))))
20846 ;; Special blocks
20847 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20848 (save-excursion
20849 (re-search-backward
20850 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20851 (setq column (org-get-indentation (match-string 0))))
20852 ((and (not (looking-at "[ \t]*#\\+begin_"))
20853 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20854 (save-excursion
20855 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20856 (setq column
20857 (cond ((equal (downcase (match-string 1)) "src")
20858 ;; src blocks: let `org-edit-src-exit' handle them
20859 (org-get-indentation))
20860 ((equal (downcase (match-string 1)) "example")
20861 (max (org-get-indentation)
20862 (org-get-indentation (match-string 0))))
20864 (org-get-indentation (match-string 0))))))
20865 ;; This line has nothing special, look at the previous relevant
20866 ;; line to compute indentation
20868 (beginning-of-line 0)
20869 (while (and (not (bobp))
20870 (not (looking-at org-drawer-regexp))
20871 ;; When point started in an inline task, do not move
20872 ;; above task starting line.
20873 (not (and inline-task-p (looking-at inline-re)))
20874 ;; Skip drawers, blocks, empty lines, verbatim,
20875 ;; comments, tables, footnotes definitions, lists,
20876 ;; inline tasks.
20877 (or (and (looking-at "[ \t]*:END:")
20878 (re-search-backward org-drawer-regexp nil t))
20879 (and (looking-at "[ \t]*#\\+end_")
20880 (re-search-backward "[ \t]*#\\+begin_"nil t))
20881 (looking-at "[ \t]*[\n:#|]")
20882 (looking-at org-footnote-definition-re)
20883 (and (ignore-errors (goto-char (org-in-item-p)))
20884 (goto-char
20885 (org-list-get-top-point (org-list-struct))))
20886 (and (not inline-task-p)
20887 (featurep 'org-inlinetask)
20888 (org-inlinetask-in-task-p)
20889 (or (org-inlinetask-goto-beginning) t))))
20890 (beginning-of-line 0))
20891 (cond
20892 ;; There was an heading above.
20893 ((looking-at "\\*+[ \t]+")
20894 (if (not org-adapt-indentation)
20895 (setq column 0)
20896 (goto-char (match-end 0))
20897 (setq column (current-column))))
20898 ;; A drawer had started and is unfinished
20899 ((looking-at org-drawer-regexp)
20900 (goto-char (1- (match-beginning 1)))
20901 (setq column (current-column)))
20902 ;; Else, nothing noticeable found: get indentation and go on.
20903 (t (setq column (org-get-indentation))))))
20904 ;; Now apply indentation and move cursor accordingly
20905 (goto-char pos)
20906 (if (<= (current-column) (current-indentation))
20907 (org-indent-line-to column)
20908 (save-excursion (org-indent-line-to column)))
20909 ;; Special polishing for properties, see `org-property-format'
20910 (setq column (current-column))
20911 (beginning-of-line 1)
20912 (if (looking-at
20913 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20914 (replace-match (concat (match-string 1)
20915 (format org-property-format
20916 (match-string 2) (match-string 3)))
20917 t t))
20918 (org-move-to-column column))))
20920 (defun org-indent-drawer ()
20921 "Indent the drawer at point."
20922 (interactive)
20923 (let ((p (point))
20924 (e (and (save-excursion (re-search-forward ":END:" nil t))
20925 (match-end 0)))
20926 (folded
20927 (save-excursion
20928 (end-of-line)
20929 (when (overlays-at (point))
20930 (member 'invisible (overlay-properties
20931 (car (overlays-at (point)))))))))
20932 (when folded (org-cycle))
20933 (indent-for-tab-command)
20934 (while (and (move-beginning-of-line 2) (< (point) e))
20935 (indent-for-tab-command))
20936 (goto-char p)
20937 (when folded (org-cycle)))
20938 (message "Drawer at point indented"))
20940 (defun org-indent-block ()
20941 "Indent the block at point."
20942 (interactive)
20943 (let ((p (point))
20944 (case-fold-search t)
20945 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20946 (match-end 0)))
20947 (folded
20948 (save-excursion
20949 (end-of-line)
20950 (when (overlays-at (point))
20951 (member 'invisible (overlay-properties
20952 (car (overlays-at (point)))))))))
20953 (when folded (org-cycle))
20954 (indent-for-tab-command)
20955 (while (and (move-beginning-of-line 2) (< (point) e))
20956 (indent-for-tab-command))
20957 (goto-char p)
20958 (when folded (org-cycle)))
20959 (message "Block at point indented"))
20961 (defun org-indent-region (start end)
20962 "Indent region."
20963 (interactive "r")
20964 (save-excursion
20965 (let ((line-end (org-current-line end)))
20966 (goto-char start)
20967 (while (< (org-current-line) line-end)
20968 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20969 (t (call-interactively 'org-indent-line)))
20970 (move-beginning-of-line 2)))))
20973 ;;; Filling
20975 ;; We use our own fill-paragraph and auto-fill functions.
20977 ;; `org-fill-paragraph' relies on adaptive filling and context
20978 ;; checking. Appropriate `fill-prefix' is computed with
20979 ;; `org-adaptive-fill-function'.
20981 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20982 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20983 ;; `org-adaptive-fill-function' value. Internally,
20984 ;; `org-comment-line-break-function' breaks the line.
20986 ;; `org-setup-filling' installs filling and auto-filling related
20987 ;; variables during `org-mode' initialization.
20989 (defun org-setup-filling ()
20990 (interactive)
20991 ;; Prevent auto-fill from inserting unwanted new items.
20992 (when (boundp 'fill-nobreak-predicate)
20993 (org-set-local
20994 'fill-nobreak-predicate
20995 (org-uniquify
20996 (append fill-nobreak-predicate
20997 '(org-fill-paragraph-separate-nobreak-p
20998 org-fill-line-break-nobreak-p)))))
20999 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21000 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21001 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21002 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21004 (defvar org-element-paragraph-separate) ; org-element.el
21005 (defun org-fill-paragraph-separate-nobreak-p ()
21006 "Non-nil when a line break at point would insert a new item."
21007 (looking-at (substring org-element-paragraph-separate 1)))
21009 (defun org-fill-line-break-nobreak-p ()
21010 "Non-nil when a line break at point would create an Org line break."
21011 (save-excursion
21012 (skip-chars-backward "[ \t]")
21013 (skip-chars-backward "\\\\")
21014 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21016 (declare-function message-in-body-p "message" ())
21017 (defvar org-element--affiliated-re) ; From org-element.el
21018 (defun org-adaptive-fill-function ()
21019 "Compute a fill prefix for the current line.
21020 Return fill prefix, as a string, or nil if current line isn't
21021 meant to be filled."
21022 (org-with-wide-buffer
21023 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21024 ;; FIXME: This is really the job of orgstruct++-mode
21025 (let* ((p (line-beginning-position))
21026 (element (save-excursion (beginning-of-line)
21027 (org-element-at-point)))
21028 (type (org-element-type element))
21029 (post-affiliated
21030 (save-excursion
21031 (goto-char (org-element-property :begin element))
21032 (while (looking-at org-element--affiliated-re) (forward-line))
21033 (point))))
21034 (unless (< p post-affiliated)
21035 (case type
21036 (comment (looking-at "[ \t]*# ?") (match-string 0))
21037 (footnote-definition "")
21038 ((item plain-list)
21039 (make-string (org-list-item-body-column post-affiliated) ? ))
21040 (paragraph
21041 ;; Fill prefix is usually the same as the current line,
21042 ;; except if the paragraph is at the beginning of an item.
21043 (let ((parent (org-element-property :parent element)))
21044 (cond ((eq (org-element-type parent) 'item)
21045 (make-string (org-list-item-body-column
21046 (org-element-property :begin parent))
21047 ? ))
21048 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21049 (match-string 0))
21050 (t ""))))
21051 (comment-block
21052 ;; Only fill contents if P is within block boundaries.
21053 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21054 (forward-line)
21055 (point)))
21056 (cend (save-excursion
21057 (goto-char (org-element-property :end element))
21058 (skip-chars-backward " \r\t\n")
21059 (line-beginning-position))))
21060 (when (and (>= p cbeg) (< p cend))
21061 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21062 (match-string 0)
21063 ""))))))))))
21065 (declare-function message-goto-body "message" ())
21066 (defvar message-cite-prefix-regexp) ; From message.el
21067 (defvar org-element-all-objects) ; From org-element.el
21068 (defun org-fill-paragraph (&optional justify)
21069 "Fill element at point, when applicable.
21071 This function only applies to comment blocks, comments, example
21072 blocks and paragraphs. Also, as a special case, re-align table
21073 when point is at one.
21075 If JUSTIFY is non-nil (interactively, with prefix argument),
21076 justify as well. If `sentence-end-double-space' is non-nil, then
21077 period followed by one space does not end a sentence, so don't
21078 break a line there. The variable `fill-column' controls the
21079 width for filling.
21081 For convenience, when point is at a plain list, an item or
21082 a footnote definition, try to fill the first paragraph within."
21083 ;; Falls back on message-fill-paragraph when necessary
21084 (interactive)
21085 (if (and (derived-mode-p 'message-mode)
21086 (or (not (message-in-body-p))
21087 (save-excursion (move-beginning-of-line 1)
21088 (looking-at message-cite-prefix-regexp))))
21089 (let ((fill-paragraph-function
21090 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21091 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21092 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21093 (paragraph-separate
21094 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21095 (fill-paragraph nil))
21096 (save-excursion
21097 ;; Move to end of line in order to get the first paragraph
21098 ;; within a plain list or a footnote definition.
21099 (end-of-line)
21100 (let ((element (org-element-at-point)))
21101 ;; First check if point is in a blank line at the beginning of
21102 ;; the buffer. In that case, ignore filling.
21103 (if (< (point) (org-element-property :begin element)) t
21104 (case (org-element-type element)
21105 ;; Align Org tables, leave table.el tables as-is.
21106 (table-row (org-table-align) t)
21107 (table
21108 (when (eq (org-element-property :type element) 'org)
21109 (org-table-align))
21111 (paragraph
21112 ;; Paragraphs may contain `line-break' type objects.
21113 (let ((beg (max (point-min)
21114 (org-element-property :contents-begin element)))
21115 (end (min (point-max)
21116 (org-element-property :contents-end element))))
21117 ;; Do nothing if point is at an affiliated keyword.
21118 (if (< (point) beg) t
21119 (when (derived-mode-p 'message-mode)
21120 ;; In `message-mode', do not fill following
21121 ;; citation in current paragraph nor text before
21122 ;; message body.
21123 (let ((body-start (save-excursion (message-goto-body))))
21124 (when body-start (setq beg (max body-start beg))))
21125 (when (save-excursion
21126 (re-search-forward
21127 (concat "^" message-cite-prefix-regexp) end t))
21128 (setq end (match-beginning 0))))
21129 ;; Fill paragraph, taking line breaks into
21130 ;; consideration. For that, slice the paragraph
21131 ;; using line breaks as separators, and fill the
21132 ;; parts in reverse order to avoid messing with
21133 ;; markers.
21134 (save-excursion
21135 (goto-char end)
21136 (mapc
21137 (lambda (pos)
21138 (fill-region-as-paragraph pos (point) justify)
21139 (goto-char pos))
21140 ;; Find the list of ending positions for line
21141 ;; breaks in the current paragraph. Add paragraph
21142 ;; beginning to include first slice.
21143 (nreverse
21144 (cons
21146 (org-element-map
21147 (org-element--parse-objects
21148 beg end nil org-element-all-objects)
21149 'line-break
21150 (lambda (lb) (org-element-property :end lb)))))))
21151 t)))
21152 ;; Contents of `comment-block' type elements should be
21153 ;; filled as plain text, but only if point is within block
21154 ;; markers.
21155 (comment-block
21156 (let* ((case-fold-search t)
21157 (beg (save-excursion
21158 (goto-char (org-element-property :begin element))
21159 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21160 (forward-line)
21161 (point)))
21162 (end (save-excursion
21163 (goto-char (org-element-property :end element))
21164 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21165 (line-beginning-position))))
21166 (when (and (>= (point) beg) (< (point) end))
21167 (fill-region-as-paragraph
21168 (save-excursion
21169 (end-of-line)
21170 (re-search-backward "^[ \t]*$" beg 'move)
21171 (line-beginning-position))
21172 (save-excursion
21173 (beginning-of-line)
21174 (re-search-forward "^[ \t]*$" end 'move)
21175 (line-beginning-position))
21176 justify)))
21178 ;; Fill comments.
21179 (comment (fill-comment-paragraph justify))
21180 ;; Ignore every other element.
21181 (otherwise t)))))))
21183 (defun org-auto-fill-function ()
21184 "Auto-fill function."
21185 ;; Check if auto-filling is meaningful.
21186 (let ((fc (current-fill-column)))
21187 (when (and fc (> (current-column) fc))
21188 (let ((fill-prefix (org-adaptive-fill-function)))
21189 (when fill-prefix (do-auto-fill))))))
21191 (defun org-comment-line-break-function (&optional soft)
21192 "Break line at point and indent, continuing comment if within one.
21193 The inserted newline is marked hard if variable
21194 `use-hard-newlines' is true, unless optional argument SOFT is
21195 non-nil."
21196 (if soft (insert-and-inherit ?\n) (newline 1))
21197 (save-excursion (forward-char -1) (delete-horizontal-space))
21198 (delete-horizontal-space)
21199 (indent-to-left-margin)
21200 (insert-before-markers-and-inherit fill-prefix))
21203 ;;; Comments
21205 ;; Org comments syntax is quite complex. It requires the entire line
21206 ;; to be just a comment. Also, even with the right syntax at the
21207 ;; beginning of line, some some elements (i.e. verse-block or
21208 ;; example-block) don't accept comments. Usual Emacs comment commands
21209 ;; cannot cope with those requirements. Therefore, Org replaces them.
21211 ;; Org still relies on `comment-dwim', but cannot trust
21212 ;; `comment-only-p'. So, `comment-region-function' and
21213 ;; `uncomment-region-function' both point
21214 ;; to`org-comment-or-uncomment-region'. Eventually,
21215 ;; `org-insert-comment' takes care of insertion of comments at the
21216 ;; beginning of line.
21218 ;; `org-setup-comments-handling' install comments related variables
21219 ;; during `org-mode' initialization.
21221 (defun org-setup-comments-handling ()
21222 (interactive)
21223 (org-set-local 'comment-use-syntax nil)
21224 (org-set-local 'comment-start "# ")
21225 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21226 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21227 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21228 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21230 (defun org-insert-comment ()
21231 "Insert an empty comment above current line.
21232 If the line is empty, insert comment at its beginning."
21233 (beginning-of-line)
21234 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21235 (org-indent-line)
21236 (insert "# "))
21238 (defvar comment-empty-lines) ; From newcomment.el.
21239 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21240 "Comment or uncomment each non-blank line in the region.
21241 Uncomment each non-blank line between BEG and END if it only
21242 contains commented lines. Otherwise, comment them."
21243 (save-restriction
21244 ;; Restrict region
21245 (narrow-to-region (save-excursion (goto-char beg)
21246 (skip-chars-forward " \r\t\n" end)
21247 (line-beginning-position))
21248 (save-excursion (goto-char end)
21249 (skip-chars-backward " \r\t\n" beg)
21250 (line-end-position)))
21251 (let ((uncommentp
21252 ;; UNCOMMENTP is non-nil when every non blank line between
21253 ;; BEG and END is a comment.
21254 (save-excursion
21255 (goto-char (point-min))
21256 (while (and (not (eobp))
21257 (let ((element (org-element-at-point)))
21258 (and (eq (org-element-type element) 'comment)
21259 (goto-char (min (point-max)
21260 (org-element-property
21261 :end element)))))))
21262 (eobp))))
21263 (if uncommentp
21264 ;; Only blank lines and comments in region: uncomment it.
21265 (save-excursion
21266 (goto-char (point-min))
21267 (while (not (eobp))
21268 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21269 (replace-match "" nil nil nil 1))
21270 (forward-line)))
21271 ;; Comment each line in region.
21272 (let ((min-indent (point-max)))
21273 ;; First find the minimum indentation across all lines.
21274 (save-excursion
21275 (goto-char (point-min))
21276 (while (and (not (eobp)) (not (zerop min-indent)))
21277 (unless (looking-at "[ \t]*$")
21278 (setq min-indent (min min-indent (current-indentation))))
21279 (forward-line)))
21280 ;; Then loop over all lines.
21281 (save-excursion
21282 (goto-char (point-min))
21283 (while (not (eobp))
21284 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21285 (org-move-to-column min-indent t)
21286 (insert comment-start))
21287 (forward-line))))))))
21290 ;;; Other stuff.
21292 (defun org-toggle-fixed-width-section (arg)
21293 "Toggle the fixed-width export.
21294 If there is no active region, the QUOTE keyword at the current headline is
21295 inserted or removed. When present, it causes the text between this headline
21296 and the next to be exported as fixed-width text, and unmodified.
21297 If there is an active region, this command adds or removes a colon as the
21298 first character of this line. If the first character of a line is a colon,
21299 this line is also exported in fixed-width font."
21300 (interactive "P")
21301 (let* ((cc 0)
21302 (regionp (org-region-active-p))
21303 (beg (if regionp (region-beginning) (point)))
21304 (end (if regionp (region-end)))
21305 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21306 (case-fold-search nil)
21307 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21308 off)
21309 (if regionp
21310 (save-excursion
21311 (goto-char beg)
21312 (setq cc (current-column))
21313 (beginning-of-line 1)
21314 (setq off (looking-at re))
21315 (while (> nlines 0)
21316 (setq nlines (1- nlines))
21317 (beginning-of-line 1)
21318 (cond
21319 (arg
21320 (org-move-to-column cc t)
21321 (insert ": \n")
21322 (forward-line -1))
21323 ((and off (looking-at re))
21324 (replace-match "" t t nil 1))
21325 ((not off) (org-move-to-column cc t) (insert ": ")))
21326 (forward-line 1)))
21327 (save-excursion
21328 (org-back-to-heading)
21329 (cond
21330 ((looking-at (format org-heading-keyword-regexp-format
21331 org-quote-string))
21332 (goto-char (match-end 1))
21333 (looking-at (concat " +" org-quote-string))
21334 (replace-match "" t t)
21335 (when (eolp) (insert " ")))
21336 ((looking-at org-outline-regexp)
21337 (goto-char (match-end 0))
21338 (insert org-quote-string " ")))))))
21340 (defun org-reftex-citation ()
21341 "Use reftex-citation to insert a citation into the buffer.
21342 This looks for a line like
21344 #+BIBLIOGRAPHY: foo plain option:-d
21346 and derives from it that foo.bib is the bibliography file relevant
21347 for this document. It then installs the necessary environment for RefTeX
21348 to work in this buffer and calls `reftex-citation' to insert a citation
21349 into the buffer.
21351 Export of such citations to both LaTeX and HTML is handled by the contributed
21352 package org-exp-bibtex by Taru Karttunen."
21353 (interactive)
21354 (let ((reftex-docstruct-symbol 'rds)
21355 (reftex-cite-format "\\cite{%l}")
21356 rds bib)
21357 (save-excursion
21358 (save-restriction
21359 (widen)
21360 (let ((case-fold-search t)
21361 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21362 (if (not (save-excursion
21363 (or (re-search-forward re nil t)
21364 (re-search-backward re nil t))))
21365 (error "No bibliography defined in file")
21366 (setq bib (concat (match-string 1) ".bib")
21367 rds (list (list 'bib bib)))))))
21368 (call-interactively 'reftex-citation)))
21370 ;;;; Functions extending outline functionality
21372 (defun org-beginning-of-line (&optional arg)
21373 "Go to the beginning of the current line. If that is invisible, continue
21374 to a visible line beginning. This makes the function of C-a more intuitive.
21375 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21376 first attempt, and only move to after the tags when the cursor is already
21377 beyond the end of the headline."
21378 (interactive "P")
21379 (let ((pos (point))
21380 (special (if (consp org-special-ctrl-a/e)
21381 (car org-special-ctrl-a/e)
21382 org-special-ctrl-a/e))
21383 refpos)
21384 (if (org-bound-and-true-p line-move-visual)
21385 (beginning-of-visual-line 1)
21386 (beginning-of-line 1))
21387 (if (and arg (fboundp 'move-beginning-of-line))
21388 (call-interactively 'move-beginning-of-line)
21389 (if (bobp)
21391 (backward-char 1)
21392 (if (org-truely-invisible-p)
21393 (while (and (not (bobp)) (org-truely-invisible-p))
21394 (backward-char 1)
21395 (beginning-of-line 1))
21396 (forward-char 1))))
21397 (when special
21398 (cond
21399 ((and (looking-at org-complex-heading-regexp)
21400 (= (char-after (match-end 1)) ?\ ))
21401 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21402 (point-at-eol)))
21403 (goto-char
21404 (if (eq special t)
21405 (cond ((> pos refpos) refpos)
21406 ((= pos (point)) refpos)
21407 (t (point)))
21408 (cond ((> pos (point)) (point))
21409 ((not (eq last-command this-command)) (point))
21410 (t refpos)))))
21411 ((org-at-item-p)
21412 ;; Being at an item and not looking at an the item means point
21413 ;; was previously moved to beginning of a visual line, which
21414 ;; doesn't contain the item. Therefore, do nothing special,
21415 ;; just stay here.
21416 (when (looking-at org-list-full-item-re)
21417 ;; Set special position at first white space character after
21418 ;; bullet, and check-box, if any.
21419 (let ((after-bullet
21420 (let ((box (match-end 3)))
21421 (if (not box) (match-end 1)
21422 (let ((after (char-after box)))
21423 (if (and after (= after ? )) (1+ box) box))))))
21424 ;; Special case: Move point to special position when
21425 ;; currently after it or at beginning of line.
21426 (if (eq special t)
21427 (when (or (> pos after-bullet) (= (point) pos))
21428 (goto-char after-bullet))
21429 ;; Reversed case: Move point to special position when
21430 ;; point was already at beginning of line and command is
21431 ;; repeated.
21432 (when (and (= (point) pos) (eq last-command this-command))
21433 (goto-char after-bullet))))))))
21434 (org-no-warnings
21435 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21437 (defun org-end-of-line (&optional arg)
21438 "Go to the end of the line.
21439 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21440 first attempt, and only move to after the tags when the cursor is already
21441 beyond the end of the headline."
21442 (interactive "P")
21443 (let ((special (if (consp org-special-ctrl-a/e)
21444 (cdr org-special-ctrl-a/e)
21445 org-special-ctrl-a/e)))
21446 (cond
21447 ((or (not special) arg
21448 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21449 (call-interactively
21450 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21451 ((fboundp 'move-end-of-line) 'move-end-of-line)
21452 (t 'end-of-line))))
21453 ((org-at-heading-p)
21454 (let ((pos (point)))
21455 (beginning-of-line 1)
21456 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21457 (if (eq special t)
21458 (if (or (< pos (match-beginning 1))
21459 (= pos (match-end 0)))
21460 (goto-char (match-beginning 1))
21461 (goto-char (match-end 0)))
21462 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21463 (goto-char (match-end 0))
21464 (goto-char (match-beginning 1))))
21465 (call-interactively (if (fboundp 'move-end-of-line)
21466 'move-end-of-line
21467 'end-of-line)))))
21468 ((org-at-drawer-p)
21469 (move-end-of-line 1)
21470 (when (overlays-at (1- (point))) (backward-char 1)))
21471 ;; At an item: Move before any hidden text.
21472 (t (call-interactively
21473 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21474 ((fboundp 'move-end-of-line) 'move-end-of-line)
21475 (t 'end-of-line)))))
21476 (org-no-warnings
21477 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21479 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21480 (define-key org-mode-map "\C-e" 'org-end-of-line)
21482 (defun org-backward-sentence (&optional arg)
21483 "Go to beginning of sentence, or beginning of table field.
21484 This will call `backward-sentence' or `org-table-beginning-of-field',
21485 depending on context."
21486 (interactive "P")
21487 (cond
21488 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21489 (t (call-interactively 'backward-sentence))))
21491 (defun org-forward-sentence (&optional arg)
21492 "Go to end of sentence, or end of table field.
21493 This will call `forward-sentence' or `org-table-end-of-field',
21494 depending on context."
21495 (interactive "P")
21496 (cond
21497 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21498 (t (call-interactively 'forward-sentence))))
21500 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21501 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21503 (defun org-kill-line (&optional arg)
21504 "Kill line, to tags or end of line."
21505 (interactive "P")
21506 (cond
21507 ((or (not org-special-ctrl-k)
21508 (bolp)
21509 (not (org-at-heading-p)))
21510 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21511 org-ctrl-k-protect-subtree)
21512 (if (or (eq org-ctrl-k-protect-subtree 'error)
21513 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21514 (error "C-k aborted - would kill hidden subtree")))
21515 (call-interactively
21516 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21517 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21518 (kill-region (point) (match-beginning 1))
21519 (org-set-tags nil t))
21520 (t (kill-region (point) (point-at-eol)))))
21522 (define-key org-mode-map "\C-k" 'org-kill-line)
21524 (defun org-yank (&optional arg)
21525 "Yank. If the kill is a subtree, treat it specially.
21526 This command will look at the current kill and check if is a single
21527 subtree, or a series of subtrees[1]. If it passes the test, and if the
21528 cursor is at the beginning of a line or after the stars of a currently
21529 empty headline, then the yank is handled specially. How exactly depends
21530 on the value of the following variables, both set by default.
21532 org-yank-folded-subtrees
21533 When set, the subtree(s) will be folded after insertion, but only
21534 if doing so would now swallow text after the yanked text.
21536 org-yank-adjusted-subtrees
21537 When set, the subtree will be promoted or demoted in order to
21538 fit into the local outline tree structure, which means that the level
21539 will be adjusted so that it becomes the smaller one of the two
21540 *visible* surrounding headings.
21542 Any prefix to this command will cause `yank' to be called directly with
21543 no special treatment. In particular, a simple \\[universal-argument] prefix \
21544 will just
21545 plainly yank the text as it is.
21547 \[1] The test checks if the first non-white line is a heading
21548 and if there are no other headings with fewer stars."
21549 (interactive "P")
21550 (org-yank-generic 'yank arg))
21552 (defun org-yank-generic (command arg)
21553 "Perform some yank-like command.
21555 This function implements the behavior described in the `org-yank'
21556 documentation. However, it has been generalized to work for any
21557 interactive command with similar behavior."
21559 ;; pretend to be command COMMAND
21560 (setq this-command command)
21562 (if arg
21563 (call-interactively command)
21565 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21566 (and (org-kill-is-subtree-p)
21567 (or (bolp)
21568 (and (looking-at "[ \t]*$")
21569 (string-match
21570 "\\`\\*+\\'"
21571 (buffer-substring (point-at-bol) (point)))))))
21572 swallowp)
21573 (cond
21574 ((and subtreep org-yank-folded-subtrees)
21575 (let ((beg (point))
21576 end)
21577 (if (and subtreep org-yank-adjusted-subtrees)
21578 (org-paste-subtree nil nil 'for-yank)
21579 (call-interactively command))
21581 (setq end (point))
21582 (goto-char beg)
21583 (when (and (bolp) subtreep
21584 (not (setq swallowp
21585 (org-yank-folding-would-swallow-text beg end))))
21586 (org-with-limited-levels
21587 (or (looking-at org-outline-regexp)
21588 (re-search-forward org-outline-regexp-bol end t))
21589 (while (and (< (point) end) (looking-at org-outline-regexp))
21590 (hide-subtree)
21591 (org-cycle-show-empty-lines 'folded)
21592 (condition-case nil
21593 (outline-forward-same-level 1)
21594 (error (goto-char end))))))
21595 (when swallowp
21596 (message
21597 "Inserted text not folded because that would swallow text"))
21599 (goto-char end)
21600 (skip-chars-forward " \t\n\r")
21601 (beginning-of-line 1)
21602 (push-mark beg 'nomsg)))
21603 ((and subtreep org-yank-adjusted-subtrees)
21604 (let ((beg (point-at-bol)))
21605 (org-paste-subtree nil nil 'for-yank)
21606 (push-mark beg 'nomsg)))
21608 (call-interactively command))))))
21610 (defun org-yank-folding-would-swallow-text (beg end)
21611 "Would hide-subtree at BEG swallow any text after END?"
21612 (let (level)
21613 (org-with-limited-levels
21614 (save-excursion
21615 (goto-char beg)
21616 (when (or (looking-at org-outline-regexp)
21617 (re-search-forward org-outline-regexp-bol end t))
21618 (setq level (org-outline-level)))
21619 (goto-char end)
21620 (skip-chars-forward " \t\r\n\v\f")
21621 (if (or (eobp)
21622 (and (bolp) (looking-at org-outline-regexp)
21623 (<= (org-outline-level) level)))
21624 nil ; Nothing would be swallowed
21625 t))))) ; something would swallow
21627 (define-key org-mode-map "\C-y" 'org-yank)
21629 (defun org-truely-invisible-p ()
21630 "Check if point is at a character currently not visible.
21631 This version does not only check the character property, but also
21632 `visible-mode'."
21633 ;; Early versions of noutline don't have `outline-invisible-p'.
21634 (if (org-bound-and-true-p visible-mode)
21636 (outline-invisible-p)))
21638 (defun org-invisible-p2 ()
21639 "Check if point is at a character currently not visible."
21640 (save-excursion
21641 (if (and (eolp) (not (bobp))) (backward-char 1))
21642 ;; Early versions of noutline don't have `outline-invisible-p'.
21643 (outline-invisible-p)))
21645 (defun org-back-to-heading (&optional invisible-ok)
21646 "Call `outline-back-to-heading', but provide a better error message."
21647 (condition-case nil
21648 (outline-back-to-heading invisible-ok)
21649 (error (error "Before first headline at position %d in buffer %s"
21650 (point) (current-buffer)))))
21652 (defun org-before-first-heading-p ()
21653 "Before first heading?"
21654 (save-excursion
21655 (end-of-line)
21656 (null (re-search-backward org-outline-regexp-bol nil t))))
21658 (defun org-at-heading-p (&optional ignored)
21659 (outline-on-heading-p t))
21660 ;; Compatibility alias with Org versions < 7.8.03
21661 (defalias 'org-on-heading-p 'org-at-heading-p)
21663 (defun org-at-comment-p nil
21664 "Is cursor in a line starting with a # character?"
21665 (save-excursion
21666 (beginning-of-line)
21667 (looking-at "^#")))
21669 (defun org-at-drawer-p nil
21670 "Is cursor at a drawer keyword?"
21671 (save-excursion
21672 (move-beginning-of-line 1)
21673 (looking-at org-drawer-regexp)))
21675 (defun org-at-block-p nil
21676 "Is cursor at a block keyword?"
21677 (save-excursion
21678 (move-beginning-of-line 1)
21679 (looking-at org-block-regexp)))
21681 (defun org-point-at-end-of-empty-headline ()
21682 "If point is at the end of an empty headline, return t, else nil.
21683 If the heading only contains a TODO keyword, it is still still considered
21684 empty."
21685 (and (looking-at "[ \t]*$")
21686 (when org-todo-line-regexp
21687 (save-excursion
21688 (beginning-of-line 1)
21689 (let ((case-fold-search nil))
21690 (looking-at org-todo-line-regexp)
21691 (string= (match-string 3) ""))))))
21693 (defun org-at-heading-or-item-p ()
21694 (or (org-at-heading-p) (org-at-item-p)))
21696 (defun org-at-target-p ()
21697 (or (org-in-regexp org-radio-target-regexp)
21698 (org-in-regexp org-target-regexp)))
21699 ;; Compatibility alias with Org versions < 7.8.03
21700 (defalias 'org-on-target-p 'org-at-target-p)
21702 (defun org-up-heading-all (arg)
21703 "Move to the heading line of which the present line is a subheading.
21704 This function considers both visible and invisible heading lines.
21705 With argument, move up ARG levels."
21706 (if (fboundp 'outline-up-heading-all)
21707 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21708 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21710 (defun org-up-heading-safe ()
21711 "Move to the heading line of which the present line is a subheading.
21712 This version will not throw an error. It will return the level of the
21713 headline found, or nil if no higher level is found.
21715 Also, this function will be a lot faster than `outline-up-heading',
21716 because it relies on stars being the outline starters. This can really
21717 make a significant difference in outlines with very many siblings."
21718 (let (start-level re)
21719 (org-back-to-heading t)
21720 (setq start-level (funcall outline-level))
21721 (if (equal start-level 1)
21723 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21724 (if (re-search-backward re nil t)
21725 (funcall outline-level)))))
21727 (defun org-first-sibling-p ()
21728 "Is this heading the first child of its parents?"
21729 (interactive)
21730 (let ((re org-outline-regexp-bol)
21731 level l)
21732 (unless (org-at-heading-p t)
21733 (error "Not at a heading"))
21734 (setq level (funcall outline-level))
21735 (save-excursion
21736 (if (not (re-search-backward re nil t))
21738 (setq l (funcall outline-level))
21739 (< l level)))))
21741 (defun org-goto-sibling (&optional previous)
21742 "Goto the next sibling, even if it is invisible.
21743 When PREVIOUS is set, go to the previous sibling instead. Returns t
21744 when a sibling was found. When none is found, return nil and don't
21745 move point."
21746 (let ((fun (if previous 're-search-backward 're-search-forward))
21747 (pos (point))
21748 (re org-outline-regexp-bol)
21749 level l)
21750 (when (condition-case nil (org-back-to-heading t) (error nil))
21751 (setq level (funcall outline-level))
21752 (catch 'exit
21753 (or previous (forward-char 1))
21754 (while (funcall fun re nil t)
21755 (setq l (funcall outline-level))
21756 (when (< l level) (goto-char pos) (throw 'exit nil))
21757 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21758 (goto-char pos)
21759 nil))))
21761 (defun org-show-siblings ()
21762 "Show all siblings of the current headline."
21763 (save-excursion
21764 (while (org-goto-sibling) (org-flag-heading nil)))
21765 (save-excursion
21766 (while (org-goto-sibling 'previous)
21767 (org-flag-heading nil))))
21769 (defun org-goto-first-child ()
21770 "Goto the first child, even if it is invisible.
21771 Return t when a child was found. Otherwise don't move point and
21772 return nil."
21773 (let (level (pos (point)) (re org-outline-regexp-bol))
21774 (when (condition-case nil (org-back-to-heading t) (error nil))
21775 (setq level (outline-level))
21776 (forward-char 1)
21777 (if (and (re-search-forward re nil t) (> (outline-level) level))
21778 (progn (goto-char (match-beginning 0)) t)
21779 (goto-char pos) nil))))
21781 (defun org-show-hidden-entry ()
21782 "Show an entry where even the heading is hidden."
21783 (save-excursion
21784 (org-show-entry)))
21786 (defun org-flag-heading (flag &optional entry)
21787 "Flag the current heading. FLAG non-nil means make invisible.
21788 When ENTRY is non-nil, show the entire entry."
21789 (save-excursion
21790 (org-back-to-heading t)
21791 ;; Check if we should show the entire entry
21792 (if entry
21793 (progn
21794 (org-show-entry)
21795 (save-excursion
21796 (and (outline-next-heading)
21797 (org-flag-heading nil))))
21798 (outline-flag-region (max (point-min) (1- (point)))
21799 (save-excursion (outline-end-of-heading) (point))
21800 flag))))
21802 (defun org-get-next-sibling ()
21803 "Move to next heading of the same level, and return point.
21804 If there is no such heading, return nil.
21805 This is like outline-next-sibling, but invisible headings are ok."
21806 (let ((level (funcall outline-level)))
21807 (outline-next-heading)
21808 (while (and (not (eobp)) (> (funcall outline-level) level))
21809 (outline-next-heading))
21810 (if (or (eobp) (< (funcall outline-level) level))
21812 (point))))
21814 (defun org-get-last-sibling ()
21815 "Move to previous heading of the same level, and return point.
21816 If there is no such heading, return nil."
21817 (let ((opoint (point))
21818 (level (funcall outline-level)))
21819 (outline-previous-heading)
21820 (when (and (/= (point) opoint) (outline-on-heading-p t))
21821 (while (and (> (funcall outline-level) level)
21822 (not (bobp)))
21823 (outline-previous-heading))
21824 (if (< (funcall outline-level) level)
21826 (point)))))
21828 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21829 "Goto to the end of a subtree."
21830 ;; This contains an exact copy of the original function, but it uses
21831 ;; `org-back-to-heading', to make it work also in invisible
21832 ;; trees. And is uses an invisible-ok argument.
21833 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21834 ;; Furthermore, when used inside Org, finding the end of a large subtree
21835 ;; with many children and grandchildren etc, this can be much faster
21836 ;; than the outline version.
21837 (org-back-to-heading invisible-ok)
21838 (let ((first t)
21839 (level (funcall outline-level)))
21840 (if (and (derived-mode-p 'org-mode) (< level 1000))
21841 ;; A true heading (not a plain list item), in Org-mode
21842 ;; This means we can easily find the end by looking
21843 ;; only for the right number of stars. Using a regexp to do
21844 ;; this is so much faster than using a Lisp loop.
21845 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21846 (forward-char 1)
21847 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21848 ;; something else, do it the slow way
21849 (while (and (not (eobp))
21850 (or first (> (funcall outline-level) level)))
21851 (setq first nil)
21852 (outline-next-heading)))
21853 (unless to-heading
21854 (if (memq (preceding-char) '(?\n ?\^M))
21855 (progn
21856 ;; Go to end of line before heading
21857 (forward-char -1)
21858 (if (memq (preceding-char) '(?\n ?\^M))
21859 ;; leave blank line before heading
21860 (forward-char -1))))))
21861 (point))
21863 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21864 "Use Org version in org-mode, for dramatic speed-up."
21865 (if (derived-mode-p 'org-mode)
21866 (progn
21867 (org-end-of-subtree nil t)
21868 (unless (eobp) (backward-char 1)))
21869 ad-do-it))
21871 (defun org-end-of-meta-data-and-drawers ()
21872 "Jump to the first text after meta data and drawers in the current entry.
21873 This will move over empty lines, lines with planning time stamps,
21874 clocking lines, and drawers."
21875 (org-back-to-heading t)
21876 (let ((end (save-excursion (outline-next-heading) (point)))
21877 (re (concat "\\(" org-drawer-regexp "\\)"
21878 "\\|" "[ \t]*" org-keyword-time-regexp)))
21879 (forward-line 1)
21880 (while (re-search-forward re end t)
21881 (if (not (match-end 1))
21882 ;; empty or planning line
21883 (forward-line 1)
21884 ;; a drawer, find the end
21885 (re-search-forward "^[ \t]*:END:" end 'move)
21886 (forward-line 1)))
21887 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21888 (point)))
21890 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21891 "Move forward to the arg'th subheading at same level as this one.
21892 Stop at the first and last subheadings of a superior heading.
21893 Normally this only looks at visible headings, but when INVISIBLE-OK is
21894 non-nil it will also look at invisible ones."
21895 (interactive "p")
21896 (org-back-to-heading invisible-ok)
21897 (org-at-heading-p)
21898 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21899 (re (format "^\\*\\{1,%d\\} " level))
21901 (forward-char 1)
21902 (while (> arg 0)
21903 (while (and (re-search-forward re nil 'move)
21904 (setq l (- (match-end 0) (match-beginning 0) 1))
21905 (= l level)
21906 (not invisible-ok)
21907 (progn (backward-char 1) (outline-invisible-p)))
21908 (if (< l level) (setq arg 1)))
21909 (setq arg (1- arg)))
21910 (beginning-of-line 1)))
21912 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21913 "Move backward to the arg'th subheading at same level as this one.
21914 Stop at the first and last subheadings of a superior heading."
21915 (interactive "p")
21916 (org-back-to-heading)
21917 (org-at-heading-p)
21918 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21919 (re (format "^\\*\\{1,%d\\} " level))
21921 (while (> arg 0)
21922 (while (and (re-search-backward re nil 'move)
21923 (setq l (- (match-end 0) (match-beginning 0) 1))
21924 (= l level)
21925 (not invisible-ok)
21926 (outline-invisible-p))
21927 (if (< l level) (setq arg 1)))
21928 (setq arg (1- arg)))))
21930 ;;;###autoload
21931 (defun org-forward-element ()
21932 "Move forward by one element.
21933 Move to the next element at the same level, when possible."
21934 (interactive)
21935 (cond ((eobp) (error "Cannot move further down"))
21936 ((org-with-limited-levels (org-at-heading-p))
21937 (let ((origin (point)))
21938 (org-forward-heading-same-level 1)
21939 (unless (org-with-limited-levels (org-at-heading-p))
21940 (goto-char origin)
21941 (error "Cannot move further down"))))
21943 (let* ((elem (org-element-at-point))
21944 (end (org-element-property :end elem))
21945 (parent (org-element-property :parent elem)))
21946 (if (and parent (= (org-element-property :contents-end parent) end))
21947 (goto-char (org-element-property :end parent))
21948 (goto-char end))))))
21950 ;;;###autoload
21951 (defun org-backward-element ()
21952 "Move backward by one element.
21953 Move to the previous element at the same level, when possible."
21954 (interactive)
21955 (cond ((bobp) (error "Cannot move further up"))
21956 ((org-with-limited-levels (org-at-heading-p))
21957 ;; At an headline, move to the previous one, if any, or stay
21958 ;; here.
21959 (let ((origin (point)))
21960 (org-backward-heading-same-level 1)
21961 (unless (org-with-limited-levels (org-at-heading-p))
21962 (goto-char origin)
21963 (error "Cannot move further up"))))
21965 (let* ((trail (org-element-at-point 'keep-trail))
21966 (elem (car trail))
21967 (prev-elem (nth 1 trail))
21968 (beg (org-element-property :begin elem)))
21969 (cond
21970 ;; Move to beginning of current element if point isn't
21971 ;; there already.
21972 ((/= (point) beg) (goto-char beg))
21973 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21974 ((org-before-first-heading-p) (goto-char (point-min)))
21975 (t (org-back-to-heading)))))))
21977 ;;;###autoload
21978 (defun org-up-element ()
21979 "Move to upper element."
21980 (interactive)
21981 (if (org-with-limited-levels (org-at-heading-p))
21982 (unless (org-up-heading-safe) (error "No surrounding element"))
21983 (let* ((elem (org-element-at-point))
21984 (parent (org-element-property :parent elem)))
21985 (if parent (goto-char (org-element-property :begin parent))
21986 (if (org-with-limited-levels (org-before-first-heading-p))
21987 (error "No surrounding element")
21988 (org-with-limited-levels (org-back-to-heading)))))))
21990 ;;;###autoload
21991 (defvar org-element-greater-elements)
21992 (defun org-down-element ()
21993 "Move to inner element."
21994 (interactive)
21995 (let ((element (org-element-at-point)))
21996 (cond
21997 ((memq (org-element-type element) '(plain-list table))
21998 (goto-char (org-element-property :contents-begin element))
21999 (forward-char))
22000 ((memq (org-element-type element) org-element-greater-elements)
22001 ;; If contents are hidden, first disclose them.
22002 (when (org-element-property :hiddenp element) (org-cycle))
22003 (goto-char (or (org-element-property :contents-begin element)
22004 (error "No content for this element"))))
22005 (t (error "No inner element")))))
22007 ;;;###autoload
22008 (defun org-drag-element-backward ()
22009 "Move backward element at point."
22010 (interactive)
22011 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22012 (let* ((trail (org-element-at-point 'keep-trail))
22013 (elem (car trail))
22014 (prev-elem (nth 1 trail)))
22015 ;; Error out if no previous element or previous element is
22016 ;; a parent of the current one.
22017 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22018 (error "Cannot drag element backward")
22019 (let ((pos (point)))
22020 (org-element-swap-A-B prev-elem elem)
22021 (goto-char (+ (org-element-property :begin prev-elem)
22022 (- pos (org-element-property :begin elem)))))))))
22024 ;;;###autoload
22025 (defun org-drag-element-forward ()
22026 "Move forward element at point."
22027 (interactive)
22028 (let* ((pos (point))
22029 (elem (org-element-at-point)))
22030 (when (= (point-max) (org-element-property :end elem))
22031 (error "Cannot drag element forward"))
22032 (goto-char (org-element-property :end elem))
22033 (let ((next-elem (org-element-at-point)))
22034 (when (or (org-element-nested-p elem next-elem)
22035 (and (eq (org-element-type next-elem) 'headline)
22036 (not (eq (org-element-type elem) 'headline))))
22037 (goto-char pos)
22038 (error "Cannot drag element forward"))
22039 ;; Compute new position of point: it's shifted by NEXT-ELEM
22040 ;; body's length (without final blanks) and by the length of
22041 ;; blanks between ELEM and NEXT-ELEM.
22042 (let ((size-next (- (save-excursion
22043 (goto-char (org-element-property :end next-elem))
22044 (skip-chars-backward " \r\t\n")
22045 (forward-line)
22046 ;; Small correction if buffer doesn't end
22047 ;; with a newline character.
22048 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22049 (org-element-property :begin next-elem)))
22050 (size-blank (- (org-element-property :end elem)
22051 (save-excursion
22052 (goto-char (org-element-property :end elem))
22053 (skip-chars-backward " \r\t\n")
22054 (forward-line)
22055 (point)))))
22056 (org-element-swap-A-B elem next-elem)
22057 (goto-char (+ pos size-next size-blank))))))
22059 ;;;###autoload
22060 (defun org-mark-element ()
22061 "Put point at beginning of this element, mark at end.
22063 Interactively, if this command is repeated or (in Transient Mark
22064 mode) if the mark is active, it marks the next element after the
22065 ones already marked."
22066 (interactive)
22067 (let (deactivate-mark)
22068 (if (and (org-called-interactively-p 'any)
22069 (or (and (eq last-command this-command) (mark t))
22070 (and transient-mark-mode mark-active)))
22071 (set-mark
22072 (save-excursion
22073 (goto-char (mark))
22074 (goto-char (org-element-property :end (org-element-at-point)))))
22075 (let ((element (org-element-at-point)))
22076 (end-of-line)
22077 (push-mark (org-element-property :end element) t t)
22078 (goto-char (org-element-property :begin element))))))
22080 ;;;###autoload
22081 (defun org-narrow-to-element ()
22082 "Narrow buffer to current element."
22083 (interactive)
22084 (let ((elem (org-element-at-point)))
22085 (cond
22086 ((eq (car elem) 'headline)
22087 (narrow-to-region
22088 (org-element-property :begin elem)
22089 (org-element-property :end elem)))
22090 ((memq (car elem) org-element-greater-elements)
22091 (narrow-to-region
22092 (org-element-property :contents-begin elem)
22093 (org-element-property :contents-end elem)))
22095 (narrow-to-region
22096 (org-element-property :begin elem)
22097 (org-element-property :end elem))))))
22099 ;;;###autoload
22100 (defun org-transpose-element ()
22101 "Transpose current and previous elements, keeping blank lines between.
22102 Point is moved after both elements."
22103 (interactive)
22104 (org-skip-whitespace)
22105 (let ((end (org-element-property :end (org-element-at-point))))
22106 (org-drag-element-backward)
22107 (goto-char end)))
22109 ;;;###autoload
22110 (defun org-unindent-buffer ()
22111 "Un-indent the visible part of the buffer.
22112 Relative indentation (between items, inside blocks, etc.) isn't
22113 modified."
22114 (interactive)
22115 (unless (eq major-mode 'org-mode)
22116 (error "Cannot un-indent a buffer not in Org mode"))
22117 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22118 unindent-tree ; For byte-compiler.
22119 (unindent-tree
22120 (function
22121 (lambda (contents)
22122 (mapc
22123 (lambda (element)
22124 (if (memq (org-element-type element) '(headline section))
22125 (funcall unindent-tree (org-element-contents element))
22126 (save-excursion
22127 (save-restriction
22128 (narrow-to-region
22129 (org-element-property :begin element)
22130 (org-element-property :end element))
22131 (org-do-remove-indentation)))))
22132 (reverse contents))))))
22133 (funcall unindent-tree (org-element-contents parse-tree))))
22135 (defun org-show-subtree ()
22136 "Show everything after this heading at deeper levels."
22137 (interactive)
22138 (outline-flag-region
22139 (point)
22140 (save-excursion
22141 (org-end-of-subtree t t))
22142 nil))
22144 (defun org-show-entry ()
22145 "Show the body directly following this heading.
22146 Show the heading too, if it is currently invisible."
22147 (interactive)
22148 (save-excursion
22149 (condition-case nil
22150 (progn
22151 (org-back-to-heading t)
22152 (outline-flag-region
22153 (max (point-min) (1- (point)))
22154 (save-excursion
22155 (if (re-search-forward
22156 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22157 (match-beginning 1)
22158 (point-max)))
22159 nil)
22160 (org-cycle-hide-drawers 'children))
22161 (error nil))))
22163 (defun org-make-options-regexp (kwds &optional extra)
22164 "Make a regular expression for keyword lines."
22165 (concat
22166 "^#\\+\\("
22167 (mapconcat 'regexp-quote kwds "\\|")
22168 (if extra (concat "\\|" extra))
22169 "\\):[ \t]*\\(.*\\)"))
22171 ;; Make isearch reveal the necessary context
22172 (defun org-isearch-end ()
22173 "Reveal context after isearch exits."
22174 (when isearch-success ; only if search was successful
22175 (if (featurep 'xemacs)
22176 ;; Under XEmacs, the hook is run in the correct place,
22177 ;; we directly show the context.
22178 (org-show-context 'isearch)
22179 ;; In Emacs the hook runs *before* restoring the overlays.
22180 ;; So we have to use a one-time post-command-hook to do this.
22181 ;; (Emacs 22 has a special variable, see function `org-mode')
22182 (unless (and (boundp 'isearch-mode-end-hook-quit)
22183 isearch-mode-end-hook-quit)
22184 ;; Only when the isearch was not quitted.
22185 (org-add-hook 'post-command-hook 'org-isearch-post-command
22186 'append 'local)))))
22188 (defun org-isearch-post-command ()
22189 "Remove self from hook, and show context."
22190 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22191 (org-show-context 'isearch))
22194 ;;;; Integration with and fixes for other packages
22196 ;;; Imenu support
22198 (defvar org-imenu-markers nil
22199 "All markers currently used by Imenu.")
22200 (make-variable-buffer-local 'org-imenu-markers)
22202 (defun org-imenu-new-marker (&optional pos)
22203 "Return a new marker for use by Imenu, and remember the marker."
22204 (let ((m (make-marker)))
22205 (move-marker m (or pos (point)))
22206 (push m org-imenu-markers)
22209 (defun org-imenu-get-tree ()
22210 "Produce the index for Imenu."
22211 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22212 (setq org-imenu-markers nil)
22213 (let* ((n org-imenu-depth)
22214 (re (concat "^" (org-get-limited-outline-regexp)))
22215 (subs (make-vector (1+ n) nil))
22216 (last-level 0)
22217 m level head)
22218 (save-excursion
22219 (save-restriction
22220 (widen)
22221 (goto-char (point-max))
22222 (while (re-search-backward re nil t)
22223 (setq level (org-reduced-level (funcall outline-level)))
22224 (when (and (<= level n)
22225 (looking-at org-complex-heading-regexp))
22226 (setq head (org-link-display-format
22227 (org-match-string-no-properties 4))
22228 m (org-imenu-new-marker))
22229 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22230 (if (>= level last-level)
22231 (push (cons head m) (aref subs level))
22232 (push (cons head (aref subs (1+ level))) (aref subs level))
22233 (loop for i from (1+ level) to n do (aset subs i nil)))
22234 (setq last-level level)))))
22235 (aref subs 1)))
22237 (eval-after-load "imenu"
22238 '(progn
22239 (add-hook 'imenu-after-jump-hook
22240 (lambda ()
22241 (if (derived-mode-p 'org-mode)
22242 (org-show-context 'org-goto))))))
22244 (defun org-link-display-format (link)
22245 "Replace a link with either the description, or the link target
22246 if no description is present"
22247 (save-match-data
22248 (if (string-match org-bracket-link-analytic-regexp link)
22249 (replace-match (if (match-end 5)
22250 (match-string 5 link)
22251 (concat (match-string 1 link)
22252 (match-string 3 link)))
22253 nil t link)
22254 link)))
22256 (defun org-toggle-link-display ()
22257 "Toggle the literal or descriptive display of links."
22258 (interactive)
22259 (if org-descriptive-links
22260 (progn (org-remove-from-invisibility-spec '(org-link))
22261 (org-restart-font-lock)
22262 (setq org-descriptive-links nil))
22263 (progn (add-to-invisibility-spec '(org-link))
22264 (org-restart-font-lock)
22265 (setq org-descriptive-links t))))
22267 ;; Speedbar support
22269 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22270 "Overlay marking the agenda restriction line in speedbar.")
22271 (overlay-put org-speedbar-restriction-lock-overlay
22272 'face 'org-agenda-restriction-lock)
22273 (overlay-put org-speedbar-restriction-lock-overlay
22274 'help-echo "Agendas are currently limited to this item.")
22275 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22277 (defun org-speedbar-set-agenda-restriction ()
22278 "Restrict future agenda commands to the location at point in speedbar.
22279 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22280 (interactive)
22281 (require 'org-agenda)
22282 (let (p m tp np dir txt)
22283 (cond
22284 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22285 'org-imenu t))
22286 (setq m (get-text-property p 'org-imenu-marker))
22287 (with-current-buffer (marker-buffer m)
22288 (goto-char m)
22289 (org-agenda-set-restriction-lock 'subtree)))
22290 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22291 'speedbar-function 'speedbar-find-file))
22292 (setq tp (previous-single-property-change
22293 (1+ p) 'speedbar-function)
22294 np (next-single-property-change
22295 tp 'speedbar-function)
22296 dir (speedbar-line-directory)
22297 txt (buffer-substring-no-properties (or tp (point-min))
22298 (or np (point-max))))
22299 (with-current-buffer (find-file-noselect
22300 (let ((default-directory dir))
22301 (expand-file-name txt)))
22302 (unless (derived-mode-p 'org-mode)
22303 (error "Cannot restrict to non-Org-mode file"))
22304 (org-agenda-set-restriction-lock 'file)))
22305 (t (error "Don't know how to restrict Org-mode's agenda")))
22306 (move-overlay org-speedbar-restriction-lock-overlay
22307 (point-at-bol) (point-at-eol))
22308 (setq current-prefix-arg nil)
22309 (org-agenda-maybe-redo)))
22311 (eval-after-load "speedbar"
22312 '(progn
22313 (speedbar-add-supported-extension ".org")
22314 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22315 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22316 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22317 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22318 (add-hook 'speedbar-visiting-tag-hook
22319 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22321 ;;; Fixes and Hacks for problems with other packages
22323 ;; Make flyspell not check words in links, to not mess up our keymap
22324 (defun org-mode-flyspell-verify ()
22325 "Don't let flyspell put overlays at active buttons, or on
22326 {todo,all-time,additional-option-like}-keywords."
22327 (let ((pos (max (1- (point)) (point-min)))
22328 (word (thing-at-point 'word)))
22329 (and (not (get-text-property pos 'keymap))
22330 (not (get-text-property pos 'org-no-flyspell))
22331 (not (member word org-todo-keywords-1))
22332 (not (member word org-all-time-keywords))
22333 (not (member word org-options-keywords))
22334 (not (member word (mapcar 'car org-startup-options)))
22335 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22337 (defun org-remove-flyspell-overlays-in (beg end)
22338 "Remove flyspell overlays in region."
22339 (and (org-bound-and-true-p flyspell-mode)
22340 (fboundp 'flyspell-delete-region-overlays)
22341 (flyspell-delete-region-overlays beg end))
22342 (add-text-properties beg end '(org-no-flyspell t)))
22344 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22345 (eval-after-load "bookmark"
22346 '(if (boundp 'bookmark-after-jump-hook)
22347 ;; We can use the hook
22348 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22349 ;; Hook not available, use advice
22350 (defadvice bookmark-jump (after org-make-visible activate)
22351 "Make the position visible."
22352 (org-bookmark-jump-unhide))))
22354 ;; Make sure saveplace shows the location if it was hidden
22355 (eval-after-load "saveplace"
22356 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22357 "Make the position visible."
22358 (org-bookmark-jump-unhide)))
22360 ;; Make sure ecb shows the location if it was hidden
22361 (eval-after-load "ecb"
22362 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22363 "Make hierarchy visible when jumping into location from ECB tree buffer."
22364 (if (derived-mode-p 'org-mode)
22365 (org-show-context))))
22367 (defun org-bookmark-jump-unhide ()
22368 "Unhide the current position, to show the bookmark location."
22369 (and (derived-mode-p 'org-mode)
22370 (or (outline-invisible-p)
22371 (save-excursion (goto-char (max (point-min) (1- (point))))
22372 (outline-invisible-p)))
22373 (org-show-context 'bookmark-jump)))
22375 ;; Make session.el ignore our circular variable
22376 (eval-after-load "session"
22377 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22379 ;;;; Experimental code
22381 (defun org-closed-in-range ()
22382 "Sparse tree of items closed in a certain time range.
22383 Still experimental, may disappear in the future."
22384 (interactive)
22385 ;; Get the time interval from the user.
22386 (let* ((time1 (org-float-time
22387 (org-read-date nil 'to-time nil "Starting date: ")))
22388 (time2 (org-float-time
22389 (org-read-date nil 'to-time nil "End date:")))
22390 ;; callback function
22391 (callback (lambda ()
22392 (let ((time
22393 (org-float-time
22394 (apply 'encode-time
22395 (org-parse-time-string
22396 (match-string 1))))))
22397 ;; check if time in interval
22398 (and (>= time time1) (<= time time2))))))
22399 ;; make tree, check each match with the callback
22400 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22402 ;;;; Finish up
22404 (provide 'org)
22406 (run-hooks 'org-load-hook)
22408 ;;; org.el ends here